Note:
- This tutorial is available in an Oracle-provided free lab environment.
- It uses example values for Oracle Cloud Infrastructure credentials, tenancy, and compartments. When completing your lab, substitute these values with ones specific to your cloud environment.
Manage KVM Virtual Machines using Oracle Linux Automation Manager
Introduction
The community.libvirt collection provides libvirt modules and plugins supported by the Ansible libvirt community. These modules and plugins help manage virtual machines (VMs) and containers using the libvirt API.
This tutorial shows how to use this collection in Oracle Linux Automation Manager and interacts with an Oracle Linux instance running KVM.
Objectives
In this lab, you’ll learn how to:
- Create a playbook that uses the community.libvirt collection
- Configure credentials for Ansible Galaxy
- Create a Job Template
- Run the Job
Prerequisites
- A system with Oracle Linux Automation Manager installed
- Access to a git repository
- An Oracle Linux system with KVM installed
Note: For details on installing Oracle Linux Automation Manager or KVM, see the links at the end of this lab.
Create a Playbook
Note: When using the free lab environment, see Oracle Linux Lab Basics for connection and other usage instructions.
Information: The free lab environment deploys a running single-host Oracle Linux Automation Manager and a KVM and Git server. The deployment takes approximately 20 minutes to finish after launch. Therefore, you might want to step away while this runs and promptly return to complete the lab.
-
Open a terminal on the free lab desktop.
-
Create the project directory.
mkdir ~/olamkvm
cd ~/olamkvm
-
Create a requirements file.
Oracle Linux Automation Engine uses the requirements file to pull any required collections or roles into the project at runtime.
cat << EOF > requirements.yml --- collections: - name: community.libvirt - name: community.general - name: community.crypto EOF
-
Create a variables file.
The file stores variables and their default values. The playbook imports this file at runtime.
-
Create a directory to store the file.
mkdir vars
-
Create the file.
cat << EOF > vars/defaults.yml --- username: oracle base_image_name: OL9U1_x86_64-kvm-b158.qcow base_image_url: https://yum.oracle.com/templates/OracleLinux/OL9/u1/x86_64/ base_image_sha: ca655beba34038349827c5ab365df4f7936a7f6226a04d0452bbe4430f4d6658 libvirt_pool_dir: "/var/lib/libvirt/images" vm_name: ol9-dev vm_vcpus: 2 vm_ram_mb: 2048 vm_net: default vm_root_pass: cleanup_tmp: no EOF
-
-
Create the cloud-init templates.
These templates create the
meta-data
and theuser-data
files to provision the VM configuration via cloud-init.-
Create a directory to store the templates.
mkdir templates
-
Create the meta-data template.
cat << EOF > templates/meta-data.j2 instance-id: iid-local01 local-hostname: EOF
-
Create the user-data template.
cat << EOF > templates/user-data.j2 #cloud-config system_info: default_user: name: opc ssh_authorized_keys: - EOF
-
-
Create the libvirt VM definition template.
cat << EOF > templates/vm-template.xml.j2 <domain type="kvm"> <name></name> <memory unit='MiB'></memory> <vcpu placement='static'></vcpu> <os> <type arch="x86_64" machine="q35">hvm</type> <boot dev="hd"/> </os> <features> <acpi/> <apic/> </features> <cpu mode="host-model"/> <clock offset="utc"> <timer name="rtc" tickpolicy="catchup"/> <timer name="pit" tickpolicy="delay"/> <timer name="hpet" present="no"/> </clock> <pm> <suspend-to-mem enabled="no"/> <suspend-to-disk enabled="no"/> </pm> <devices> <emulator>/usr/libexec/qemu-kvm</emulator> <disk type="file" device="disk"> <driver name="qemu" type="qcow2"/> <source file="/.qcow"/> <target dev="vda" bus="virtio"/> </disk> <disk type="file" device="cdrom"> <driver name="qemu" type="raw"/> <source file="/.iso"/> <target dev="sda" bus="sata"/> <readonly/> </disk> <controller type="usb" model="qemu-xhci" ports="15"/> <interface type="network"> <source network=""/> <model type="virtio"/> </interface> <console type="pty"/> <channel type="unix"> <source mode="bind"/> <target type="virtio" name="org.qemu.guest_agent.0"/> </channel> <memballoon model="virtio"/> <rng model="virtio"> <backend model="random">/dev/urandom</backend> </rng> </devices> </domain> EOF
-
Create a playbook.
This playbook queries the KVM server for existing VMs and then deploys a new Oracle Linux Cloud Image.
cat << EOF > create_vm.yml --- - name: create vm with community.libvirt collection hosts: kvm collections: - community.libvirt - community.crypto become: yes vars_files: - vars/defaults.yml tasks: - name: get list of existing VMs community.libvirt.virt: command: list_vms register: existing_vms changed_when: no - name: print list of existing VMs debug: var: existing_vms - name: create VM when not exist block: - name: download base image get_url: url: "" dest: "/tmp/" checksum: "sha256:" - name: copy base image to libvirt directory ansible.builtin.copy: dest: "/.qcow" src: "/tmp/" force: no remote_src: yes owner: qemu group: qemu mode: 0660 register: copy_results - name: generate a vm ssh keypair community.crypto.openssh_keypair: path: ~/.ssh/id_rsa size: 2048 comment: vm ssh keypair register: vm_ssh_keypair become_user: "" - name: create vm meta-data ansible.builtin.template: src: templates/meta-data.j2 dest: "~/meta-data" become_user: "" - name: read the vm ssh private key slurp: src: "~/.ssh/id_rsa.pub" register: vm_ssh_private_key become_user: "" - name: create var for private key ansible.builtin.set_fact: vm_private_key: "" - name: create vm user-data ansible.builtin.template: src: templates/user-data.j2 dest: ~/user-data become_user: "" - name: generate iso containing cloud-init configuration shell: | genisoimage -output /tmp/.iso -volid cidata -joliet -rock ~/user-data ~/meta-data become_user: "" - name: copy vm iso image to libvirt directory ansible.builtin.copy: dest: "/.iso" src: "/tmp/.iso" force: no remote_src: yes owner: qemu group: qemu mode: 0660 - name: remove vm iso image from tmp ansible.builtin.file: path: "/tmp/.iso" state: absent - name: define the vm community.libvirt.virt: command: define xml: "" when: ( vm_name not in existing_vms.list_vms ) - name: start the vm community.libvirt.virt: name: "" state: running register: vm_start_results until: "vm_start_results is success" retries: 15 delay: 2 - name: remove the temporary file file: path: "/tmp/" state: absent when: cleanup_tmp | bool EOF
Add the Project to Source Control
-
Initialize the project’s working directory into a Git repository.
Before initializing the repository, you need to perform some Git first-time setup steps.
-
Set the default branch name used when initializing a project.
git config --global init.defaultBranch main
-
Set your Identity.
Note: The email and name below are examples within this tutorial. Using your actual email and name outside this tutorial is essential, and this information gets immutably baked into each of your commits.
git config --global user.email johndoe@example.com git config --global user.name "John Doe"
-
Initialize the directory as a local Git repository.
git init
The command returns that it
Initialized
the empty Git repository.
-
-
Check the state of the working directory and project staging area.
git status
The state of the local repository indicates two untracked files,
create_vm.yml
andrequirements.yml
, and the directoriesvars
andtemplates
. -
Add and track the new files in the staging area.
git add --all
The
--all
option adds all untracked and changed files to the staging area. -
Commit the changes currently in the staging area.
git commit -m 'initial commit'
The
-m
option allows adding a comment to the committed changes. -
Create and initialize the remote Git repository.
The free lab environment provides a Git server where we’ll push the playbook project along with all the other dependencies.
A remote is a shared repository all project contributors use and stored on a code-hosting service like GitHub or a self-hosted server.
ssh git@<hostname or ip address of the Git server> "git init --bare /git-server/repos/olamkvm.git"
Use the public IP address shown for the
git-server
VM on the free lab environment’s Luna Lab Resources page.Accept the ECDSA key fingerprint to continue if a prompt appears.
Example Output:
[luna.user@lunabox olamkvm]$ ssh git@130.61.55.145 "git init --bare /git-server/repos/olamkvm.git" The authenticity of host '130.61.55.145 (130.61.55.145)' can't be established. ECDSA key fingerprint is SHA256:evXYs/yvZPo+tik03B9Q/2J8GCL/E+NPTA3rvcmcQdc. Are you sure you want to continue connecting (yes/no/[fingerprint])? yes Warning: Permanently added '130.61.55.145' (ECDSA) to the list of known hosts. Initialized empty Git repository in /git-server/repos/olamkvm.git/
-
Add the new remote repository connection record.
After adding the remote to the local repository, you can use it as a shortcut in other Git commands.
git remote add origin git@<hostname or IP address of the Git server>:/git-server/repos/olamkvm.git
The IP address is the address of the remote Git server, and the path after the colon is the repository’s location on the remote Git server.
-
Verify the newly added connection record.
git remote -v
Example Output:
[luna.user@lunabox olamkvm]$ git remote -v origin git@130.61.55.145:/git-server/repos/olamkvm.git (fetch) origin git@130.61.55.145:/git-server/repos/olamkvm.git (push)
The output shows the connection record
origin
pointing to the remote Git repository location for both thefetch
andpush
Git commands. -
Push local repository changes to the remote repository.
git push origin main
Example Output
[luna.user@lunabox olamkvm]$ git push origin main Enumerating objects: 4, done. Counting objects: 100% (4/4), done. Delta compression using up to 4 threads Compressing objects: 100% (4/4), done. Writing objects: 100% (4/4), 468 bytes | 468.00 KiB/s, done. Total 4 (delta 0), reused 0 (delta 0), pack-reused 0 To 130.61.55.145:/git-server/repos/olamkvm.git * [new branch] main -> main
With the create_vm.yml
sample code existing on the remote Git repository, the playbook is available to an Oracle Linux Automation Manager Project.
Create Ansible Galaxy Credentials
These credentials allow Oracle Linux Automation Manager to pull the OCI Ansible Collection from the public Ansible Galaxy Hub.
-
Open a terminal from the Luna Desktop and configure an SSH tunnel to the deployed Oracle Linux Automation Manager instance.
ssh -L 8444:localhost:443 oracle@<hostname or ip address>
In the free lab environment, use the IP address of the
ol-node
VM as it runs the Oracle Linux Automation Manager deployment. -
Open a web browser and enter the URL.
https://localhost:8444
Note: Approve the security warning based on the browser used. For Chrome, click the
Advanced
button and then theProceed to localhost (unsafe)
link. -
Log in to the Oracle Linux Automation Manager WebUI. Use the Username
admin
and the Passwordadmin
created during the automated deployment. -
The WebUI displays after a successful login.
-
Click
Credentials
underResources
in the navigation menu. -
Click the
Add
button. -
Enter or select the following values in the specific fields.
For fields with a search or list of values, we can start typing the requested value and then select it.
- Name:
My Ansible Galaxy
- Organization:
Default
- Credential Type:
Ansible Galaxy/Automation Hub API Token
Oracle Linux Automation Manager uses the Ansible Galaxy credentials to set the order to download roles/collections using the
ansible-galaxy
command.- Galaxy Server URL:
https://galaxy.ansible.com
- Name:
-
Review the entries and click the
Save
button. -
Click
Organizations
underAccess
in the navigation menu.Assigning the Ansible Galaxy credential within the Organization enables the download of any required roles or collections from within the git project.
-
Click the
Default
organization link and then theEdit
button. -
Select the My Ansible Galaxy credential in the Galaxy Credentials field and click the Select button.
-
Review and click the
Save
button.
Create Machine Credentials
These credentials allow Oracle Linux Automation Manager to connect via ssh to the KVM virtualization system.
-
Click
Credentials
underResources
in the navigation menu. -
Click the
Add
button. -
Enter or select the following values in the specific fields.
For fields with a search or list of values, we can start typing the requested value and then select it.
- Name:
My KVM Server
- Organization:
Default
- Credential Type:
Machine
Oracle Linux Automation Manager uses the Machine credentials to set the information required when establishing an ssh connection to a host.
The page refreshes, requesting the
Type Details
.- Username:
oracle
-
Click the
Browse
button for the SSH Private Key.A dialog box appears displaying the Open File window.
-
Right-click in the central panel of the Open File window and select
Show Hidden Files
in the pop-up dialog box. -
Click anywhere in the central panel to dismiss the dialog box.
-
Click the
Home
location in the navigation menu on the left side of the Open File window. -
Double-click the
.ssh
folder in the list, then double-click theid_rsa
file..This action copies the contents of the
id_rsa
file to the SSH Private Key.
- Name:
-
Review the entries, then scroll to the bottom and click the
Save
button.
Create an Inventory
-
Click
Inventories
in the navigation menu. -
Click the
Add
button and selectAdd inventory
from the drop-down list of values. -
Enter or select the following values in the specific fields.
- Name:
KVM Servers
- Instance Groups:
controlplane
- Name:
-
Review and click the
Save
button.
Add a Group to an Inventory
A group within an inventory is a classification of hosts or other groups that allow controlling a set of hosts for a given task.
-
Click the
Groups
tab on the KVM ServersDetails
page. -
Click the
Add
button. -
Enter or select the following values in the specific fields.
- Name:
kvm
- Name:
-
Review and click the
Save
button.
Add a Host to the Inventory Group
-
Click the
Hosts
tab on the kvmGroup details
page. -
Click the
Add
button and selectAdd new host
from the drop-down list of values. -
Enter or select the following values in the specific fields.
- Name:
hostname
,fqdn
, orIP address
of the host
In the free lab environment, use the IP address of the
kvm-server
VM listed on the Luna LabResources
page. - Name:
-
Review and click the
Save
button.
Ping the Inventory Group
Use the ping
module to verify Oracle Linux Automation can connect to the host within the inventory group.
-
Use the breadcrumbs and click on
KVM Servers
. -
Click the
Groups
tab. -
Check the box next to the
kvm
group and click theRun Command
button.The
Run Command
pop-up dialog appears. -
Select the
ping
module and click theNext
button. -
Select the
OLAM EE (latest)
Execution Environment and click theNext
button. -
Select the
My KVM Server
Machine Credential and click theNext
button. -
Review and click the
Launch
button.A job launches and displays the output from the
ping
module.
Add Source Control Credential
-
Click
Credentials
in the navigation menu. -
Click the
Add
. button. -
Enter or select the following values in the specific fields.
- Name:
Git Server
- Organization:
Default
- Credential Type:
Source Control
The page refreshes, requesting the
Type Details
.- Username:
git
- SCM Private Key:
Copy and paste the contents of the
~/.ssh/id_rsa
file from the free lab environment desktop into theSCM Private Key
field. - Name:
-
Review and click the
Save
button.
Create a Project
-
Click
Projects
in the navigation menu. -
Click the
Add
button. -
Enter or select the following values in the specific fields.
- Name:
My Project
- Execution Environment:
OLAM EE (latest)
- Source Control Credential Type:
Git
The page refreshes, requesting the
Type Details
.- Source Control URL:
git@<hostname or ip address of git server>:/git-server/repos/olamkvm.git
- Source Control Credential:
Git Server
Replace the hostname or IP address in the Source Control URL with the actual git server in the free lab environment.
- Name:
-
Review and click the
Save
button. -
Review the project sync status.
After project creation, the project will display its status in the
Details
summary as the sync begins. The status transitions fromRunning
toSuccessful
if the configuration is correct and the git server is reachable.
Create a Job Template
-
Click
Templates
in the navigation menu. -
Click the
Add
button and selectAdd job template
from the drop-down list of values. -
Enter the required values.
- Name:
My Template
- Job Type:
Run
- Inventory:
KVM Servers
- Project:
My Project
- Execution Environment:
OLAM EE (latest)
- Playbook:
create_vm.yml
- Credentials:
My KVM Server
- Name:
-
Review, scroll down, and click the
Save
button. -
Launch the template.
Launch a job from the template summary page by clicking the
Launch
button.If successful, the job launches and displays the output from the template. The standard output shows the playbook running and outputs the results of the playbook.
Verify Virtual Machine Creation
-
Open a terminal and connect via ssh to the kvm-server node.
ssh oracle@<hostname or IP address>
-
Get a list of running VMs.
sudo virsh list
Example Output:
[oracle@kvm-server ~]$ sudo virsh list Id Name State ------------------------- 1 ol9-dev running
-
Get the IP address of the
ol9-dev
VM.sudo virsh net-dhcp-leases default
Example Output:
[oracle@kvm-server ~]$ sudo virsh net-dhcp-leases default Expiry Time MAC address Protocol IP address Hostname Client ID or DUID ------------------------------------------------------------------------------------------------------------ 2023-04-06 18:59:33 52:54:00:6e:93:07 ipv4 192.168.122.167/24 ol9-dev 01:52:54:00:6e:93:07
-
Connect to the VM.
ssh opc@<ip address of the virtual machine>
-
Disconnect from the VM.
exit
(Optional) Create Another Virtual Machine
The playbook allows the creation of another VM by changing the vm_name
variable.
-
Switch to the browser window containing the Oracle Linux Automation Manager WebUI, and log in if necessary.
-
Click
Templates
in the navigation menu. -
Click the
Edit Template
icon forMy Template
. -
Add the variable
vm_name
with a value ofol9-new
to theVariables
section. -
Scroll down and click the
Save
button. -
Launch the template.
-
Repeat the virtual machine verification steps and connect to the newly created VM.
Summary
The Oracle Linux Automation Manager job output and the ability to connect using ssh to the virtual machine confirm everything works.
For More Information
Oracle Linux Automation Manager Documentation
Oracle Linux Automation Manager Installation Guide
Oracle Linux Automation Manager Training
Create VMs with KVM on Oracle Linux
Oracle Linux Training Station
More Learning Resources
Explore other labs on docs.oracle.com/learn or access more free learning content on the Oracle Learning YouTube channel. Additionally, visit education.oracle.com/learning-explorer to become an Oracle Learning Explorer.
For product documentation, visit Oracle Help Center.
Manage KVM Virtual Machines using Oracle Linux Automation Manager
F80318-02
April 2023
Copyright © 2023, Oracle and/or its affiliates.