VM Management with Ansible Automation Platform and Red Hat OpenShift Virtualization

Lab Overview

In this hands-on lab, you will learn how to manage the lifecycle of your virtual machines (VMs) using Ansible and the Red Hat OpenShift Virtualization collection. You will focus on essential VM operations, including starting, stopping, and restarting virtual machines.

By the end of this lab, you will have the foundational skills to apply these techniques in your own environments, setting the stage for broader automation initiatives. These include tasks like performing system updates and optimizing resource utilization, which will be explored in subsequent exercises.

Update the tasks/main.yml file

Before you begin, you’ll work with a redhatone.vm_management collection stored in your Gitea virt-aap-day2 repository. This collection includes a vm_management role, which you will use to create tasks for starting, stopping, and restarting a virtual machine.

Before creating these tasks, you will update the main.yml file within the vm_management role to invoke the appropriate task based on the action value defined in the Ansible playbook that you will create later. This setup allows a single playbook to handle all three VM management tasks dynamically, depending on the specified action.

  1. Within your VSCode editor, navigate to the virt-aap-day2/collections/ansible_collections/redhatone/vm_management/roles/vm_management/tasks/

  2. Edit the following content to the main.yml file

    ---
    # tasks file for vm_management
    
    - name: Run the specific vm_management task
      include_tasks: "{{ task_file }}"
  3. After making and saving the changes, ensure you commit and push them to your Gitea repository. For detailed instructions, refer to Appendix: Using VS Code or Terminal to Commit and Push Changes.

Create the Ansible VM Management Playbook

This Ansible playbook dynamically calls the role and executes the appropriate task based on the task_file variable given.

  1. Within your VSCode editor, right click virt-aap-day2 and create a New File labeled manage_vm_playbook.yml

  2. Add the following content to the manage_vm_playbook.yml

    ---
    - name: Manage a Virtual Machine
      hosts: localhost
      roles:
        - redhatone.vm_management.vm_management
  3. After making and saving the changes, ensure you commit and push them to your Gitea repository. For detailed instructions, refer to Appendix: Using VS Code or Terminal to Commit and Push Changes.

Stop a VM Task

Create a task to wait until a virtual machine (VM) is stopped. This task will be included in the vm_management role, specifically under the tasks directory, in a file named stop_vm.yml. Later in the lab, you will call this task from an Ansible playbook to demonstrate its capability.

  1. Within your VSCode editor, right click tasks of the vm_management collection and create a New File labeled stop_vm.yml

    new file
    Figure 1. New File Creation
  2. Add the following content to the stop_vm.yml

    ---
    - name: Wait until the VirtualMachine is stopped
      redhat.openshift_virtualization.kubevirt_vm:
        name: "{{ vm_name }}"
        namespace: "{{ vm_namespace }}"
        running: false
        wait: true

    Explanation of the Task:

    • The kubevirt_vm module that is part of the redhat.openshift_virtualization collection is used to modify a VM

    • The name parameter uses a user defined variable named vm_name to specify which VM to stop

    • The running: false ensures the VM is not running

    • The wait: true ensures the next Ansible task isn’t triggered until the stop is complete

  3. After making and saving the changes, ensure you commit and push them to your Gitea repository. For detailed instructions, refer to Appendix: Using VS Code or Terminal to Commit and Push Changes.

Create & Run a Job Template with Ansible Automation Platform

In order to run the manage_vm_playbook.yml within Ansible Automation Platform, create a Job Template to run the automation as follows:

  1. Login to your AAP Dashboard UI using your credentials.

  2. Re-sync the Workshop Project with your latest updates within the Ansible Automation Platform UI

    • Navigate to Automation Execution → Projects and select Workshop Project

    • On the top right, select the Sync Project button and wait for Last job status to provide the status of Success.

  3. Next, go to Automation Execution → Templates, click the Create template button, and choose Create job template.

  4. Fill out the following details:

    Parameter Value

    Name

    Stop VMs

    Job type

    Run

    Inventory

    OpenShift Virtual Machines

    Project

    Workshop Project

    Playbook

    manage_vm_playbook.yml

    Execution environment

    Day2 EE

    Credentials

    OpenShift Credential

    Extra variables

    vm_name: rhel9-vm1
    vm_namespace: vms-aap-day2
    task_file: stop_vm.yml

  5. Click Create job template.

  6. Once the Stop VMs Job Template is created, select the Launch Template button on the top right corner to run the job.

stop vms
Figure 2. Stopping a VM

Extending stop_vm.yml to Handle All VMs in a Namespace

While the ability to manage a specific VM is important, the real value of automation lies in managing multiple VMs at scale. In this section, you’ll extend the functionality of the stop_vm.yml task file to handle all the Virtual Machines that reside within the vms-aap-day2 namespace and learn how to use the debug task to understand the structure of the VM resource vm_info to identify key fields required to create dynamic Ansible tasks.

  1. Head back to the VSCode editor to access the stop_vm.yml file

  2. Modify the existing stop_vm.yml content with the following:

    ---
    - name: Get all VirtualMachines in the namespace
      redhat.openshift_virtualization.kubevirt_vm_info:
        namespace: "{{ vm_namespace }}"
      register: vm_info
    
    - name: Debug the vm_info variable
      ansible.builtin.debug:
        var: vm_info
    
    - name: Wait until the VirtualMachine is stopped
      redhat.openshift_virtualization.kubevirt_vm:
        name: "{{ item.metadata.name }}"
        namespace: "{{ item.metadata.namespace }}"
        running: false
        wait: true
      loop: "{{ vm_info.resources }}"
      loop_control:
        label: "{{ item.metadata.name }}"
      when: item.status.printableStatus != "Stopped"

    Explanation of Key Fields:

    • The kubevirt_vm_info module retrieves all VMs in the namespace.

    • metadata.name: The name of the VirtualMachine.

    • metadata.namespace: The namespace the VM belongs to.

    • The loop_control option sets a label for each task iteration, showing the VM name (item.metadata.name) in the output. This makes the playbook output more readable and easier to debug.

    • status.printableStatus: The current status of the VM (e.g., Stopped).

      These key fields originate from the vm_info structure output provided by the ansible.builtin.debug module. The structure looks as follows and is abbreviated for easier viewing below.

      changed: true
      result:
        apiVersion: kubevirt.io/v1
        kind: VirtualMachine
        metadata:
          annotations:
            kubectl.kubernetes.io/last-applied-configuration: >
              ...
          ...
          name: rhel9-vm1
          namespace: vms-aap-day2
        spec:
          ...
        status:
          ...
          printableStatus: Stopped
        ...
  3. After making and saving the changes, ensure you commit and push them to your Gitea repository.

  4. Head back to the AAP Dashboard UI, go to the Automation Execution → Templates, select the Stop VMs Job Template and select the pencil icon Edit template to edit the template.

  5. Modify the existing Stop VMs Job Template by removing the following variable from the Extra variables section and selecting Save job template when finished.

    vm_name: rhel9-vm1
  6. Re-run via the Launch Template button.

    stop vms multiple
    Figure 3. Stopping the VMs
  7. Head to the OpenShift UI dashboard, you can verify the VMs are stopped within the Virtualization → Virtual Machines section.

Start VM Task

In this lab exercise, you will build on your knowledge of managing multiple VMs by creating a task to start your VMs within the vm_management role. This task will be added to the tasks directory in a file named start_vm.yml.

The following steps will guide you in creating the start_vm.yml file.

  1. Within your VSCode editor, right click tasks of the vm_management collection and create a New File labeled start_vm.yml

  2. Add the following content to the start_vm.yml

    ---
    - name: Get all VirtualMachines in the namespace
      redhat.openshift_virtualization.kubevirt_vm_info:
        namespace: "{{ vm_namespace }}"
      register: vm_info
    
    - name: Debug the vm_info variable
      ansible.builtin.debug:
        var: vm_info
    
    - name: Start the VirtualMachines
      redhat.openshift_virtualization.kubevirt_vm:
        name: "{{ item.metadata.name }}"
        namespace: "{{ item.metadata.namespace }}"
        running: true
        wait: true
      loop: "{{ vm_info.resources }}"
      loop_control:
        label: "{{ item.metadata.name }}"
      when: item.status.printableStatus != "Running"
  3. After making and saving the changes, ensure you commit and push them to your Gitea repository.

Create & Run Start VM Job Template with Ansible Automation Platform

To execute the manage_vm_playbook.yml within Ansible Automation Platform, create a Job Template as follows:

  1. Head to the AAP UI dashboard, navigate to Automation Execution → Templates, click the Create template button, and choose Create job template.

  2. Fill out the following details:

    Parameter Value

    Name

    Start VMs

    Job Type

    Run

    Inventory

    OpenShift Virtual Machines

    Project

    Workshop Project

    Playbook

    manage_vm_playbook.yml

    Execution Environment

    Day2 EE

    Credentials

    OpenShift Credential

    Extra variables

    vm_namespace: vms-aap-day2
    task_file: start_vm.yml

  3. Click Create job template.

  4. Once the Start VMs Job Template is created, select the Launch Template button on the top right corner to run the job.

  5. Head to the OpenShift UI dashboard, you can verify the VMs are running within the Virtualization → Virtual Machines section.

Restart VM Task

In this lab exercise, you will focus on managing multiple VMs by creating a task to reboot your VMs. This task will be added to the tasks directory in a file named restart_vm.yml.

The following steps will guide you in creating the restart_vm.yml file.

  1. Within your VSCode editor, right click tasks of the vm_management collection and create a New File labeled restart_vm.yml

  2. Add the following content to the restart_vm.yml

    ---
    - name: Get all Virtual Machines in the namespace
      redhat.openshift_virtualization.kubevirt_vm_info:
        namespace: "{{ vm_namespace }}"
      register: vm_info
    
    - name: Stop Running Virtual Machines
      redhat.openshift_virtualization.kubevirt_vm:
        name: "{{ item.metadata.name }}"
        namespace: "{{ item.metadata.namespace }}"
        running: false
        wait: true
      loop: "{{ vm_info.resources }}"
      loop_control:
        label: "{{ item.metadata.name }}"
      when: item.status.printableStatus == "Running"
    
    - name: Refresh VM info after stopping
      redhat.openshift_virtualization.kubevirt_vm_info:
        namespace: "{{ vm_namespace }}"
      register: updated_vm_info
    
    - name: Start the Virtual Machines
      redhat.openshift_virtualization.kubevirt_vm:
        name: "{{ item.metadata.name }}"
        namespace: "{{ item.metadata.namespace }}"
        running: true
        wait: true
      loop: "{{ updated_vm_info.resources }}"
      loop_control:
        label: "{{ item.metadata.name }}"
      when: item.status.printableStatus != "Running"

    Explanation of Key Points

    • The kubevirt_vm_info module retrieves all VMs in the namespace. The first retrieval stores their initial state in vm_info. This is used to identify VMs that need to be stopped. After stopping, the second retrieval updates the VM state in updated_vm_info, ensuring accurate information is used for the subsequent start operation.

  3. After making and saving the changes, ensure you commit and push them to your Gitea repository.

Create & Run Restart VM Job Template with Ansible Automation Platform

To execute the manage_vm_playbook.yml within Ansible Automation Platform, create a Job Template as follows:

  1. Head to the AAP UI Dashboard, navigate to Automation Execution → Templates, click the Create template button, and choose Create job template.

  2. Fill out the following details:

    Parameter Value

    Name

    Restart VMs

    Job Type

    Run

    Inventory

    OpenShift Virtual Machines

    Project

    Workshop Project

    Playbook

    manage_vm_playbook.yml

    Execution Environment

    Day2 EE

    Credentials

    OpenShift Credential

    Extra variables

    vm_namespace: vms-aap-day2
    task_file: restart_vm.yml

  3. Click Create job template.

  4. Once the Restart VMs Job Template is created, select the Launch Template button on the top right corner to run the job.

  5. Head to the OpenShift UI Dashboard to view the changes of the VMs.

Conclusion

Congratulations on completing the lab!

In this lab, you explored how to effectively manage the lifecycle of virtual machines using Ansible Automation Platform and the Red Hat OpenShift Virtualization collection. By working through tasks to start, stop, and restart VMs, you gained practical experience in leveraging automation to manage VMs at scale.

By the end of this lab, you should now understand:

  • How to dynamically retrieve and process VM information using the ansible.builtin.debug module

  • How to modify a collection and role for starting, stopping, and restarting VMs.

  • How to integrate the redhatone.vm_management collection into an Ansible playbook and run it using the Ansible Automation Platform.

These foundational skills set the stage for further automation, enabling you to automate new tasks and optimize resource usage in your environment. In subsequent labs, you’ll build on this knowledge to tackle other re-world scenarios, such as system updates and disaster recovery planning.

Your ability to automate routine VM management tasks not only saves time but also minimizes human error, ensuring consistency and reliability in your virtualized infrastructure.

Well done, and keep experimenting with new ways to apply automation in your day-to-day operations!