Hello all. This is my first tutorial on KVM Virtualization prepared as a reference and to help you automate boring GUI-based installation questions. We’re using Kickstart on KVM to deploy VMs. If you have a good hands-on knowledge of Linux and Virtualization, my bet is you have already worked with KVM and Kickstart.
In case this is the first time you are giving KVM a shot, worry less since you don’t need a deep understanding of KVM virtualization internals to use this guide. Just know that Virtualization enables rapid deployment by isolating the application in a known controlled environment and adds a layer of abstraction between the virtual machine and underlying physical hardware. The easiest way to get many VMs running on KVM is by using templates and Kickstart on KVM deployment model.
Major Advantages of Virtualization
- Service Isolation : Application isolation and elimination of compatibility issues
- Improved system security and reliability : Abstraction between the virtual machine and the underlying physical hardware
- Faster server provisioning : Use of snapshots and templates.
- Quicker disaster recovery : Keeping up-to-date snapshots of virtual machines – easy to redeploy
- Dynamic load balancing : Live migration of overload to underutilized servers
What is Kickstart?
A tool created by Red Hat for system administrators to help them automate installation of Red Hat Linux family of Distributions. A single file containing the answers to all the questions that would normally be asked during a typical installation has to be created. Kickstart files can be kept on a single server system and read by individual computers during the installation, ready for Kickstart on KVM.
How to Perform Kickstart on KVM Installation?
Kickstart installations can be performed using a local CD-ROM, a local hard drive, or via NFS, FTP, or HTTP.
To use kickstart, you must:
- Create a kickstart file.
- Create a boot media with the kickstart file or make the kickstart file available on the network.
- Make the installation tree available.
- Start the kickstart installation.
In this post, I’ll provide you with basic kickstart file for quickstart; you can modify and advance it to suite your use case and environment setup. Used
virt-install
commands are provided as well. To save you quite some time, i wrote a simple bash script that makes the process of spinning new virtual machine easy and less tiresome.kickstart file
This is a kickstart file to help you get started. With penchant goal, edit and save it as
ks.cfg
under your web server root directory.###############################################################
#
# Environment setup
#
###############################################################
# url --url="http://192.168.122.1:8090/cent7"
text
cdrom
auth --enableshadow --passalgo=sha512
keyboard --vckeymap=us --xlayouts='us'
lang en_US.UTF-8
eula --agreed
reboot
###############################################################
#
# network configuration
#
###############################################################
network --bootproto=static --ip=192.168.122.100 --gateway=192.168.122.1 --netmask=255.255.255.0 --noipv6 --device=eth0 --nameserver=192.168.122.1,8.8.8.8 --activate
#network --bootproto=dhcp --device=eth0 --ipv6=auto --activate
network --hostname=server1.example.com
timezone Africa/Nairobi --isUtc
###############################################################
#
# partitioning
#
###############################################################
ignoredisk --only-use=vda
bootloader --location=mbr --boot-drive=vda
zerombr
clearpart --none --initlabel
autopart --type=lvm
# part swap --asprimary --fstype="swap" --size=1024
# part /boot --fstype xfs --size=200
# part pv.01 --size=1 --grow
# volgroup rootvg01 pv.01
# logvol / --fstype xfs --name=lv01 --vgname=rootvg01 --size=1 --grow
###########################################################################################
#
# User Accounts
# Generate encrypted password: python -c 'import crypt; print(crypt.crypt("My Password"))'
# Or openssl passwd -1 password
#
###########################################################################################
rootpw password
# user --groups=wheel --name=josepy --password=password --gecos="Mutai Josphat"
###############################################################
#
# SELinux and Firewalld
#
###############################################################
selinux --enforcing
#selinux --permissive
#selinux --disabled
# firewall --enabled --http --ssh --ftp --port=https:tcp --port=ipp:tcp
# firewall --disabled
###############################################################
#
# Software Packages
#
###############################################################
%packages --nobase --ignoremissing
@core
@base
vim
bash-completion
%end
Few parameters are to be changed, maybe the
IP address
and hostname
. Below bash script is used to install a new vm – will ask you few questions#!/usr/bin/env bash
# Update kickstart file
echo -en "Enter Hostname: "
read HOST_NAME
echo -en "Enter IP Address: "
read IP_ADDRESS
sudo sed -i 's/server1/'$HOST_NAME'/g' /srv/http/ks.cfg
sudo sed -i 's/192.168.122.100/'$IP_ADDRESS'/g' /srv/http/ks.cfg
## Pre-defined variables
echo ""
MEM_SIZE=1024
VCPUS=1
OS_VARIANT="rhel7"
ISO_FILE="$HOME/iso/CentOS-7-x86_64-Everything-1611.iso"
echo -en "Enter vm name: "
read VM_NAME
OS_TYPE="linux"
echo -en "Enter virtual disk size : "
read DISK_SIZE
sudo virt-install \
--name ${VM_NAME} \
--memory=${MEM_SIZE} \
--vcpus=${VCPUS} \
--os-type ${OS_TYPE} \
--location ${ISO_FILE} \
--disk size=${DISK_SIZE} \
--network bridge=virbr0 --network bridge=docker0 \
--graphics=none \
--os-variant=${OS_VARIANT} \
--console pty,target_type=serial \
-x 'console=ttyS0,115200n8 serial' \
-x "ks=http://192.168.122.1:8090/ks.cfg"
Replace
$HOME/iso/CentOS-7-x86_64-Everything-1611.iso
with the path to your ISO file, 192.168.122.1:8090
with your web server ip address hosting ks.cfg
file.
You can modify other parameters like
VCPU,RAM and Bridge
to fit your use.
For virtual disk size, just enter number, e.g
10
for 10 GB
Save the script to a file called
create_vm.sh
. Make it executable and run it$ chmod +x create_vm.sh
$ ./create_vm.sh
FROM https://computingforgeeks.com/rhel-centos-kickstart-automated-installation-kvm-virt-install/
----------------
Virsh create a vm
If you would like to create a new virtual machine with virsh, the relevant command to use is `virt-install. This is crucial and can’t miss on virsh commands cheatsheet arsenal. Example below will install a new operating system from CentOS 7 ISO Image.
sudo virt-install \
--name centos7 \
--description "Test VM with CentOS 7" \
--ram=1024 \
--vcpus=2 \
--os-type=Linux \
--os-variant=rhel7 \
--disk path=/var/lib/libvirt/images/centos7.qcow2,bus=virtio,size=10 \
--graphics none \
--location $HOME/iso/CentOS-7-x86_64-Everything-1611.iso \
--network bridge:virbr0 \
--console pty,target_type=serial -x 'console=ttyS0,115200n8 serial'
Virsh connect to vm console
To connect to the guest console, use the command:
$ sudo virsh console test
This will return a fail message if an active console session exists for the provided domain.
Virsh edit vm xml file
To edit a vm xml file, use:
# To use vim text editor
$ sudo EDITOR=vim virsh edit test
# To use nano text editor
$ sudo EDITOR=nano virsh edit test
Virsh suspend vm, virsh resume vm
To suspend a guest with virsh
command called test
:
$ sudo virsh suspend test
Domain test suspended
NOTE: When a domain is in a suspended state, it still consumes system RAM. Disk and network I/O will not occur while the guest is suspended.
Resuming a guest vm:
To restore a suspended guest with virsh using the resume option:
$ sudo virsh resume test
Domain test resumed
Virsh save vm
To save the current state of a vm to a file using the virsh
command :
The syntax is:
$ sudo virsh save test test.saved
Domain test saved to test.save
$ ls -l test.save
-rw------- 1 root root 328645215 Mar 18 01:35 test.saved
Restoring a saved vm
To restore saved vm from the file:
$ virsh restore test.save
Domain restored from test.save
$ sudo virsh list
Id Name State
----------------------------------------------------
7 test running
The next section of virsh commands cheatsheet will cover managing volumes with virsh
command:
Virsh Manage Volumes
Here we’ll cover how to create a storage volume , attach it to a vm , detach it from a vm and how to delete a volume.
Virsh create volume
To create a 2GB
volume named test_vol2
on the default storage pool, use:
$ sudo virsh vol-create-as default test_vol2.qcow2 2G
Vol test_vol2.qcow2 created
$ sudo du -sh /var/lib/libvirt/images/test_vol2.qcow2
2.0G/var/lib/libvirt/images/test_vol2.qcow2
default: Is the pool name.
test_vol2: This is the name of the volume.
2G: This is the storage capacity of the volume.
Virsh attach a volume to vm
To attach created volume above to vm test
, run:
# virsh attach-disk --domain test \
--source /var/lib/libvirt/images/test_vol2.qcow2 \
--persistent --target vdb
Disk attached successfully
--persistent
: Make live change persistent
--target vdb
: Target of disk device
You can confirm that the volume was added to the vm as block device /dev/vdb
# ssh test
Last login: Fri Mar 17 19:30:54 2017 from gateway
[root@test ~]#
[root@test ~]# lsblk --output NAME,SIZE,TYPE
NAME SIZE TYPE
sr0 1024M rom
vda 10G disk
├─vda1 1G part
└─vda2 9G part
├─cl_test-root 8G lvm
└─cl_test-swap 1G lvm
vdb 2G disk
Virsh detach volume on vm
To detach above attached volume test_vol2
from the vm test
:
$ sudo virsh detach-disk --domain test --persistent --live --target vdb
Disk detached successfully
$ ssh test
Last login: Sat Mar 18 01:52:33 2017 from gateway
[root@test ~]#
[root@test ~]# lsblk --output NAME,SIZE,TYPE
NAME SIZE TYPE
sr0 1024M rom
vda 10G disk
├─vda1 1G part
└─vda2 9G part
├─cl_test-root 8G lvm
└─cl_test-swap 1G lvm
[root@test ~]#
You can indeed confirm from this output that the device /dev/vdb
has been detached
Please note that you can directly grow disk image for the vm using qemu-img command, this will look something like this:
$ sudo qemu-img resize /var/lib/libvirt/images/test.qcow2 +1G
The main shortcoming of above command is that you cannot resize an image which has snapshots.
Virsh delete volume
To delete volume with virsh
command, use:
$ sudo virsh vol-delete test_vol2.qcow2 --pool default
Vol test_vol2.qcow2 deleted
$ sudo virsh pool-refresh default
Pool default refreshed
$ sudo virsh vol-list default
Name Path
------------------------------------------------------------------------------
admin.qcow2 /var/lib/libvirt/images/admin.qcow2
cloudstack.qcow2 /var/lib/libvirt/images/cloudstack.qcow2
ipa.qcow2 /var/lib/libvirt/images/ipa.qcow2
katello.qcow2 /var/lib/libvirt/images/katello.qcow2
node1.qcow2 /var/lib/libvirt/images/node1.qcow2
node2.qcow2 /var/lib/libvirt/images/node2.qcow2
node3.qcow2 /var/lib/libvirt/images/node3.qcow2
test.qcow2 /var/lib/libvirt/images/test.qcow2
ubuntu14.04.qcow2 /var/lib/libvirt/images/ubuntu14.04.qcow2
zenoss.qcow2 /var/lib/libvirt/images/zenoss.qcow2
From the output of vol-list
virsh command, it is observed that the volume has been deleted.
Virsh Manage Snapshots
In this second last section of managing kvm guest machines with virsh command, we’ll have a look at managing VM snapshots.
Virsh Create Snapshot for a vm
Let’s create snapshot for our test vm.
$ sudo virsh snapshot-create-as --domain test \
--name "test_vm_snapshot1" \
--description "test vm snapshot 1-working"
Domain snapshot test_vm_snapshot1 created
Virsh list Snapshots for a vm
To list available snapshots for a vm, use:
$ sudo virsh snapshot-list test
Name Creation Time State
------------------------------------------------------------
1489689679 2017-03-16 21:41:19 +0300 shutoff
test_fresh 2017-03-16 22:11:48 +0300 shutoff
test_vm_snapshot1 2017-03-18 02:15:58 +0300 running
Virsh display info about a snapshot
To retrieve more information about a domain, use:
$ sudo virsh snapshot-info --domain test --snapshotname test_vm_snapshot1
Name: test_vm_snapshot1
Domain: test
Current: yes
State: running
Location: internal
Parent: test_fresh
Children: 0
Descendants: 0
Metadata: yes
Virsh revert vm snapshot
Here we’ll create another snapshot called test_vm_snapshot2
, then revert to snapshot test_vm_snapshot1
$ sudo virsh snapshot-create-as \
--domain test --name "test_vm_snapshot2" \
--description "test vm snapshot 2-working"
Domain snapshot test_vm_snapshot2 created
Let’s revert the snapshot we created before:
$ sudo virsh snapshot-list test
Name Creation Time State
------------------------------------------------------------
1489689679 2017-03-16 21:41:19 +0300 shutoff
test_fresh 2017-03-16 22:11:48 +0300 shutoff
test_vm_snapshot1 2017-03-18 02:15:58 +0300 running
test_vm_snapshot2 2017-03-18 02:23:29 +0300 running
$ sudo virsh snapshot-revert --domain test --snapshotname test_vm_snapshot1 --running
Virsh delete snapshot
Let’s delete the two snapshots we created:
$ sudo virsh snapshot-delete --domain test --snapshotname test_vm_snapshot2
Domain snapshot test_vm_snapshot2 deleted
$ sudo virsh snapshot-delete --domain test --snapshotname test_vm_snapshot1
Domain snapshot test_vm_snapshot1 deleted
$ sudo virsh snapshot-list test
Name Creation Time State
------------------------------------------------------------
1489689679 2017-03-16 21:41:19 +0300 shutoff
test_fresh 2017-03-16 22:11:48 +0300 shutoff
Virsh clone a vm
Domain with devices to clone must be paused or shutoff. So let’s shut it down:
$ sudo virsh destroy test
Domain test destroyed
Then clone a vm, do it as shown below:
$ sudo virt-clone --connect qemu:///system \
--original test \
--name test_clone \
--file /var/lib/libvirt/images/test_clone.qcow2
Allocating 'test_clone.qcow2' | 10 GB 00:00:06
Clone 'test_clone' created successfully.
$ sudo virsh dominfo test_clone
Id: -
Name: test_clone
UUID: be0621fd-51b5-4d2b-a05c-ce76e59baafa
OS Type: hvm
State: shut off
CPU(s): 1
Max memory: 1048576 KiB
Used memory: 1048576 KiB
Persistent: yes
Autostart: disable
Managed save: no
Security model: none
Security DOI: 0
Virsh manage VM vcpus
This virsh commands cheatsheet section covers how to add additional virtual cpus to a virtual machine:
sudo virsh setvcpus --domain test --maximum 2 --config
sudo virsh setvcpus --domain test --count 2 --config
sudo virsh reboot test
Domain test is being rebooted
Confirm that the number of vcpu has changed, the previous was 1
, the current value is 2
:
$ virsh dominfo test
Id: -
Name: test
UUID: a943ed42-ba62-4270-a41d-7f81e793d754
OS Type: hvm
State: shut off
CPU(s): 2
Max memory: 1048576 KiB
Used memory: 1048576 KiB
Persistent: yes
Autostart: disable
Managed save: no
Security model: none
Security DOI: 0
Virsh manage vm ram
Also on virsh commands cheatsheet is managing RAM with virsh. To adjust the total ram used by guest operating system, the following commands are used:
sudo virsh setmaxmem test 2048 --config
sudo virsh setmem test 2048 --config
sudo virsh reboot test
Domain test is being rebooted
Check domain info to confirm the current RAM allocated to the VM.
virsh dominfo test
Id: 9
Name: test
UUID: a943ed42-ba62-4270-a41d-7f81e793d754
OS Type: hvm
State: running
CPU(s): 2
CPU time: 70.7s
Max memory: 2048 KiB
Used memory: 2048 KiB
Persistent: yes
Autostart: disable
Managed save: no
Security model: none
Security DOI: 0
Notice that the current ram allocated to the VM is 2048
.
Virsh Manage networking
To wrap up our virsh commands cheatsheet content, please read my previous article:
for how to use virsh to manage KVM networking.
Conclusion
Our virsh commands cheatsheet is now complete. In our next tutorial on virsh
commands, I’ll share with you my bash functions that come in handy when managing Guest machines on KVM.
I would like to thank you for taking your time to read this post. Please share and comment if you have any issue.
FROM https://computingforgeeks.com/virsh-commands-cheatsheet/
----------
Configure KVM Networking With virsh, nmcli and brctl in Linux
There are many choices for network configurations in the KVM host. In this post, I’ll guide you through two main choices to configure KVM networking. We’ll consider internal networking and external networking for Guest operating systems running on KVM.
The two ways to configure KVM networking we’ll cover are:
- Using a Linux bridge with NAT for KVM guests
- Using a Linux bridge (without NAT) for KVM guests
The other available ways to configure KVM networking that we won’t cover on this post are:
- Using an Open vSwitch bridge with KVM guests
- Using the MacVTap driver with KVM guests
Creating KVM Linux NAT-based bridge network
This network configuration uses a Linux bridge in combination with Network Address Translation (NAT) to enable a guest OS to get outbound connectivity regardless of the type of networking (wired, wireless, dial-up, and so on) used in the KVM host without requiring any specific administrator configuration. Using this method to configure KVM networking is simple and straightforward.
The diagram below illustrate how NAT networking works under the hood in KVM:
https://i.imgur.com/vGWiACU.png
The quickest way to get started is by utilizing existing default
network configuration. Dump default network xml configuration using below command.
# virsh net-dumpxml default > br.xml
You can edit this file accordingly and use it to define new network interface
Manually create xml file
Have a look at below file for general overview of how the file should look like:
Create a new file br1.xml
# vim br1.xml
Add following content, edit to your liking, then save.
<network>
<name>br1</name>
<forward mode='nat'>
<nat>
<port start='1024' end='65535'/>
</nat>
</forward>
<bridge name='br1' stp='on' delay='0'/>
<ip address='192.168.10.1' netmask='255.255.255.0'>
<dhcp>
<range start='192.168.10.10' end='192.168.10.100'/>
</dhcp>
</ip>
</network>
To define a network from an XML file without starting it, use:
# virsh net-define br1.xml
Network br1 defined from br1.xml
To start a (previously defined) inactive network, use:
# virsh net-start br1
Network br1 started
To create transient network that cannot be set to autostart use:
# virsh net-create br1.xml
Network br1 created from br1.xml
To autostart a network, use:
# virsh net-autostart br1
Network br1 marked as autostarted
Check to Confirm if autostart flag is turned to yes
– Persistent should read yes as well.
# virsh net-list --all
Name State Autostart Persistent
----------------------------------------------------------
br1 active yes yes
default active yes yes
To convert a network name to network UUID – previously defined UUID, use:
# virsh net-uuid br1
ed90dfcf-c895-4d5c-9d34-bd307f8c3ec0
Confirm that the bridge was successfully created
You can use brctl
command provided by bridge-utils
package to check available bridges on your Linux system
# brctl show br1
bridge name bridge id STP enabled interfaces
br1 8000.525400515825 yes br1-nic
Checking Ip address assigned to the interface
You can use ip
command for this:
# ip addr show dev br1
19: br1: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
link/ether 52:54:00:51:58:25 brd ff:ff:ff:ff:ff:ff
inet 192.168.10.1/24 brd 192.168.10.255 scope global br1
valid_lft forever preferred_lft forever
Attaching an interface to a VM
In this example, I’ll attach br1
interface to the vm pxe
that will be configured as Preboot eXecution Environment server.
- This takes effect immediately, and the NIC will be persistent on further reboots.
- Attach the interface as below:
# virsh attach-interface --domain pxe --type bridge --source br1 --model virtio --config --live
# virsh domiflist pxe
Interface Type Source Model MAC
-------------------------------------------------------
vnet0 bridge virbr0 virtio 52:54:00:e9:ad:17
vnet1 bridge br1 virtio 52:54:00:47:2f:eb
Detaching an interface attached to a VM
# virsh detach-interface --domain pxe --type bridge --mac 52:54:00:47:2f:eb --config
# virsh domiflist pxe
Interface Type Source Model MAC
-------------------------------------------------------
vnet0 bridge virbr0 virtio 52:54:00:e9:ad:17
Removing a network
To fully remove a network , follow steps below:
- First destroy the network to put it in inactive mode:
# virsh net-destroy br1
Network br1 destroyed
- Next, undefine the network.
# virsh net-undefine br1
Network br1 has been undefined
- Confirm that the network is not listed as inactive/active.
# virsh net-list --all
Name State Autostart Persistent
----------------------------------------------------------
default active yes yes
- You can as well use
brctl
command to check:
# brctl show br1
bridge br1 does not exist!
Creating KVM Linux bridge (without NAT) for KVM guests
An alternative to using a NAT-based network to configure KVM networking would be to use a standard Linux network bridge.
A network bridge is a Link Layer device which forwards traffic between networks based on MAC addresses and is therefore also referred to as a Layer 2 device. It makes forwarding decisions based on tables of MAC addresses which it builds by learning what hosts are connected to each network.
A software bridge can be used within a Linux host in order to emulate a hardware bridge, for example in virtualization applications for sharing a NIC with one or more virtual NICs.
Create Linux Bridge using nmcli
Nmcli is a command-line client for NetworkManager. It allows controlling NetworkManager and reporting its status.
To create a Linux bridge called br0
using nmcli, run the following commands:
nmcli con add type bridge con-name br0 ifname br0 autoconnect yes
nmcli con add type ethernet con-name br0-slave-1 ifname ens3 master br0 autoconnect yes nmcli con modify br0 bridge.stp no
This example demonstrates adding a bridge master connection and one slave.
- The first command adds a master bridge connection, naming the bridge interface and the profile as
br0
.
- The second command add slaves profile enslaved to
br0
. The slave will be tied to ens3
interface.
- The last command will disable
802.1D
STP for the br0
profile.
Furthe modify the bridge to enable autoconnect, add ipv4 address and gateway:
nmcli connection modify br0 ipv4.addresses 192.168.10.5/24 \
ipv4.method manual ipv4.gateway 192.168.10.1 ipv4.dns 8.8.8.8
Bring up the interface:
# nmcli con up br0
Connection successfully activated (master waiting for slaves) (D-Bus active path: /org/freedesktop/NetworkManager/ActiveConnection/15)
# brctl show br0
bridge namebridge idurlSTP enabledinterfaces
br0-slave-18000.000000000000no
Create Linux Bridge using brctl
If you don’t have networkmanager installed, you can use brctl
command installed with installation of bridge-utils
to configure Linux bridge that we’ll use to configure KVM networking.
- Create a new bridge:
# brctl addbr br0
- Add a device to a bridge, for example eth0:
# brctl addif br0 eth0
- Assigning an IP address
# ip addr add dev br0 192.168.2.4/24
# ip route add default via 192.168.2.1 dev br0
- Show current bridges and what interfaces they are connected to:
# brctl show
- Set the bridge device up:
# ip link set up dev br0
- Delete a bridge, you need to first set it to down:
# ip link set dev br0 down
# brctl delbr br0
# brctl delbr br0
Reference and Further reading
- https://wiki.libvirt.org/page/VirtualNetworking
- http://www.linux-kvm.org/page/Networking
- IBM – KVM knowledgecenter
from https://computingforgeeks.com/managing-kvm-network-interfaces-in-linux/