Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/bin/bash
- # Take one argument from the commandline: VM name
- if ! [ $# -eq 3 ]; then
- echo "Usage: $0 <node-name> <ram-MB> <vcpus>"
- exit 1
- fi
- # Check if domain already exists
- virsh dominfo $1 > /dev/null 2>&1
- if [ "$?" -eq 0 ]; then
- echo -n "[WARNING] $1 already exists. "
- read -p "Do you want to overwrite $1 [y/N]? " -r
- if [[ $REPLY =~ ^[Yy]$ ]]; then
- echo ""
- else
- echo -e "\nNot overwriting $1. Exiting..."
- exit 1
- fi
- fi
- # Directory to store images
- DIR=/virt/images
- # Location of cloud image
- IMAGE=$DIR/rhel-7.4.qcow2
- # Amount of RAM in MB
- MEM=$2
- # Number of virtual CPUs
- CPUS=$3
- DISK=$1.qcow2
- BRIDGE=virbr0
- USER_DATA=user-data
- META_DATA=meta-data
- CI_ISO=$1-cidata.iso
- echo "$(date -R) Destroying the $1 domain (if it exists)..."
- # Remove domain with the same name
- virsh destroy $1
- virsh undefine $1
- echo "$(date -R) creating machine named $1 with $MEM MB of RAM and $CPUS vcpu(s) ...."
- echo "$(date -R) creating cloud-init iso"
- SSH_PUB_KEY=`cat ~/.ssh/id_rsa.pub`
- cat > $USER_DATA << _EOF_
- #cloud-config
- ssh_pwauth: True
- ssh_authorized_keys:
- - $SSH_PUB_KEY
- chpasswd:
- list: |
- root:password
- cloud-user:password
- expire: False
- rh_subscription:
- username: XXXXXX
- password: XXXXXX
- auto-attach: True
- service-level: self-support
- _EOF_
- cat > $META_DATA << _EOF_
- instance-id: $1
- local-hostname: $1
- _EOF_
- genisoimage -output $CI_ISO -volid cidata -joliet -rock $USER_DATA $META_DATA
- echo "$(date -R) Copying template image..."
- qemu-img create -f qcow2 -o backing_file=$IMAGE /virt/runtime/$DISK
- echo "$(date -R) Installing the domain and adjusting the configuration..."
- echo "virt-install --import --name $1 --ram $MEM --vcpus $CPUS --disk
- $DISK,format=qcow2,bus=virtio --disk $CI_ISO,device=cdrom --network
- bridge=virbr0,model=virtio --os-type=linux --os-variant=rhel7 --noautoconsole"
- virt-install --import --name $1 --ram $MEM --vcpus $CPUS --disk \
- $DISK,format=qcow2,bus=virtio --disk $CI_ISO,device=cdrom --network \
- bridge=virbr0,model=virtio --os-type=linux --os-variant=rhel7 --noautoconsole
- MAC=$(virsh dumpxml $1 | awk -F\' '/mac address/ {print $2}')
- while true
- do
- IP=$(grep -B1 $MAC /var/lib/libvirt/dnsmasq/$BRIDGE.status | head \
- -n 1 | awk '{print $2}' | sed -e s/\"//g -e s/,//)
- if [ "$IP" = "" ]
- then
- sleep 1
- else
- break
- fi
- done
- # Eject cdrom
- echo "$(date -R) Cleaning up cloud-init..."
- virsh change-media $1 hda --eject --config
- # Remove the unnecessary cloud init files
- rm $USER_DATA $CI_ISO $META_DATA
- echo "$(date -R) DONE. SSH to $1 using $IP , with username 'cloud-user'."
Add Comment
Please, Sign In to add comment