Berton L. Ansible For VMware by Examples. A Step-by-Step Guide... 2023
Berton L. Ansible For VMware by Examples. A Step-by-Step Guide... 2023
Berton L. Ansible For VMware by Examples. A Step-by-Step Guide... 2023
This work is subject to copyright. All rights are solely and exclusively
licensed by the Publisher, whether the whole or part of the material is
concerned, speci ically the rights of translation, reprinting, reuse of
illustrations, recitation, broadcasting, reproduction on micro ilms or in
any other physical way, and transmission or information storage and
retrieval, electronic adaptation, computer software, or by similar or
dissimilar methodology now known or hereafter developed.
The publisher, the authors, and the editors are safe to assume that the
advice and information in this book are believed to be true and accurate
at the date of publication. Neither the publisher nor the authors or the
editors give a warranty, expressed or implied, with respect to the
material contained herein or for any errors or omissions that may have
been made. The publisher remains neutral with regard to jurisdictional
claims in published maps and institutional af iliations.
Modern IT Infrastructure
Deploying and managing applications requires more and more server
machines that are reliable and ef icient. Traditionally, system
administrators took care of this burden for the internal (developers)
and external (users) stakeholders who interact with the systems.
The day-to-day tasks of a system administrator involved the manual
installation of software, changing of con igurations, and management of
services on servers, virtual machines, and nodes. And every day the IT
department received requests to boost the data center’s resources in
order to accommodate the business needs or better tackle the
marketplace. System administrators realized they couldn’t scale their
manual systems management scripts as fast as the business
stakeholders demanded: the hosted web applications increased the
complexity, email low increased, and new releases of the operating
systems continued. API-driven server management and con iguration
management tools like Ansible helped make things manageable for a
time.
You could see this trend in the rise of the application-as-service,
developer-centric methodologies DevOps and DevSecOps.
Microservices, and serverless application architecture meant that a
more seismic shift was coming. Instead of thinking in terms of servers
and infrastructure, developers expect to be able to manage
containerized application lifecycles, with no regard for the servers on
which their applications run.
Modern business applications require one or more of the following
features:
Self-healing infrastructure
Auto-scaling/elasticity
High availability with multi-server failover
Flexible or multi-tier storage backends
Multi-cloud compatibility
Enabling DevSecOps
The containerized app development and deployment became more
and more popular with a huge number of technologies to real-time
check these boxes, like Apache Mesos and Docker Swarm. Some cloud
vendors even built their container orchestration and management
products to meet the needs of cloud-native applications. Examples:
Amazon Elastic Container Service (Amazon ECS) by Amazon Web
Services (AWS), Google Container Engine (GKE) by Google Cloud
Platform (GCP), Azure Container Service by Microsoft Azure, IBM
Bluemix Cloud Kubernetes Container Service by IBM Cloud, Oracle
Container Cloud Service (OCCS) by Oracle Cloud, and Alibaba Cloud
Container Registry.
Creative software engineers and solution creators love to use the
Ansible Automation Platform (formerly Ansible Tower). It is the
enterprise product used to store resources across your team and
trigger automation recipes and work lows in the DevSecOps
environment. Other popular tools like Jenkins, Rundeck, GitHub
Actions, GitLab CI/CD, Atlassian Bamboo, CircleCI, TeamCity, Travis CI,
BuildMaster, Bitrise, Buddy, or Go CI may also be used to enable
continuous integration and continuous deployment in your
organization.
Author Bio
I’m Luca Berton and we’re going to have a lot of fun together.
I’ve been an Ansible expert and working directly with the Ansible
Engineering Team of Red Hat for three years.
I have more than 15 years of system administration experience,
working with infrastructures either on-premises or with the major
cloud providers and technologies.
I’m an enthusiast of open source and I support the community by
sharing my knowledge in different events of public access.
I’m also a co-founder of the FSUG Padova, my hometown Linux
Users Group, visited by Richard Stallman, the founder of the Free
Software Movement in 2007.
I consider myself a lazy person, so I always try new ways to
automate the repetitive task of my work.
After years of Perl, Bash, and Python scripting, I landed on the
Ansible technology. I took the certi ication and worked for more than
three years with the Ansible Engineer Team.
I consider Ansible the best infrastructure automation technology
nowadays. It’s human-readable, the learning curve is accessible, and it
is very requested by the recruiters in the market.
On every page of this book, I’m going to share with you one speci ic
use case, the possible solution, the code, the execution, and the
veri ication of the target system. All these solutions are battle-tested
and used by me in my everyday automation.
You can easily jump between lessons and review them as many
times as you need.
Awards and Recognitions
Since 2021, I have shared my knowledge about Ansible in my Ansible
Pilot project and it is gaining more traction among IT professionals
every day.
Some major milestones:
“Ansible Anwendertreffen - From Zero to Hero: How to build the
Ansible Pilot Community” by Luca Berton (Red Hat CZ) 15:15 - 16:00
February 22, 2022
Author of Red Hat Ansible Playbook included in RHSB-2021-009
Log4Shell trigger Remote Code Execution in log4j (CVE-2021-44228)
January 12, 2022
The Ansible Bullhorn #41 - A Newsletter for the Ansible Developer
Community, January 7, 2022
The Ansible Bullhorn #34 - A Newsletter for the Ansible Developer
Community, September 17, 2021
Are you ready to have fun together?
---
# YAML file example
Chapters at a Glance
This book is going to become a cornerstone on your journey through
the Ansible platform for the VMware infrastructure. Although there are
four chapters, the book is jam-packed with code samples and
command-line commands that save time and avoid human mistakes
enabling IaC for DevOps and DevSecOps methodologies.
Learn about the state-of-the-art Ansible platform today in Chapter
1. Concepts like inventories, Playbooks, tasks, common computer
coding language statements concepts and code reuse, facts and magic
variables, roles, and collections are explained and clari ied as well as
powerful key advantages such as idempotency.
Learn how to successfully install the Ansible platform on the most
used modern operating systems in Chapter 2. Familiarize yourself with
the Ansible community vs. ansible-core packages for the most used
Linux distributions, macOS, and Windows.
Learn how to apply all this knowledge to the VMware infrastructure
domain with speci ic Ansible Playbook code, such as how to upgrade
VMware Guest Tools or move virtual machines between servers in
Chapter 3.
Any source code or other supplementary material referenced by the
author in this book is available to readers on GitHub via the book’s
product page, located at www.apress.com/978-1-4842-8878-8. For
more detailed information, please visit www.apress.com/source-code.
You can also download the codes from GitHub at
https://github.com/Apress/Ansible-for-VMware-by-Examples_Luca-
Berton.
Acknowledgments
To my son, family, and friends who make life worth living and whose
support and encouragement makes this work possible.
I’d like to thank my technical reviewer, Nikhil Jain, previously a Red
Hat colleague, who joined my effort early on and contributed to the
project.
To everyone I’ve worked with over the years and shared any ideas
for this book: thank you for the knowledge you’ve shared.
Table of Contents
Chapter 1: Ansible for Beginners with Examples
What Is Ansible?
Ansible
Three Main Use Cases
Four Key Tenets of Ansible
Six Values of Ansible
Ansible History
Ansible, Ansible Tower, and the Ansible Automation
Platform
Getting Started
Ansible Architecture
Connecting with Managed Nodes
Ansible Installation
Running Ad-Hoc Commands with Privilege Escalation on
Ansible
Recap
Inventory
Simple INI Inventory
Simple YAML Inventory
Adding Ranges of Hosts
Hosting in Multiple Groups
Host Variables
Group Variables
Inheriting Variable Values
Using Multiple Inventory Sources
The localhost Inventory
Recap
Playbook
YAML Syntax
helloworld.yml
Tip 1: ansible-playbook –check Option
Tip 2: Debug Day-to-Day Usage
Idempotency
multipleplays.yml
privilege_escalation.yml
Common Ansible Modules
Recap
Variables
Not Permitted Variable Names
variableprint.yml
variableprint.yml - Extra Variables
Host Variables and Group Variables
Array Variables
array.yml Execution
Registered Variables
registeredvariables.yml Execution
Filters and Templates
Recap
Facts and Magic Variables
Ansible Facts
Magic Variables
Recap
Vault
Creating an Encrypted File
Viewing an Encrypted File
Editing an Existing Encrypted File
Encrypting an Existing File
Decrypting an Existing File
Changing the Password of an Encrypted File
Playbooks and Ansible Vault
Recap
Conditional
Basic Conditionals with “when”
Conditionals Based on ansible_facts
Recap
Loop
with_* Statement
loop_with_items.yml
Recap
Handler
rollingupdate.yml
Role
Role Tree Directories
Using Ansible Roles in a Playbook
Order of Execution
Ansible Galaxy
Installing Roles from Ansible Galaxy Manually
Installing Roles from Ansible Galaxy requirements.yml
Collection
Ansible Plugins
Key Takeaways
Chapter 2: Installing Ansible
Ansible Community vs. ansible-core Packages
ansible-core
The Ansible Community Package
Additional Collections Installation
Installing the community.vmware Collection via the ansible-
galaxy Command
Installing the community.vmware Collection via the
requirements.yml File
Verifying the Currently Installed Version of community.
vmware
Links
Ansible Installation for RedHat Enterprise Linux (RHEL) 8
Code
Ansible Installation for Ubuntu 22.04 LTS
Code
Ansible Installation for Fedora 36
Code
Ansible Installation for CentOS 9 Stream
Links
Code
Ansible Installation on Windows
Links
Code
Ansible Installation for macOS
Code
Ansible Installation for SUSE SLES (Linux Enterprise Server) 15
SP3
Links
Code
Ansible Installation with PIP
Code
Ansible Installation for RedHat Enterprise Linux 9
Links
Demo
Ansible Installation for Amazon Linux 2 (AWS EC2)
Links
Code
Ansible Installation for Debian 11
Code
Key Takeaways
Chapter 3: Ansible for VMware
Con iguring Ansible for VMware
The Ansible vmware.vmware_rest Collection
Con iguring a Python Virtual Environment for Ansible
VMware
Ansible Troubleshooting: VMware Failed to Import
pyVmomi
Ansible Troubleshooting: VMware Unknown Error While
Connecting to vCenter or ESXi
Ansible Troubleshooting: VMware Certi icate Veri ication
Failed Connecting to vCenter or ESXi
Creating a VMware Virtual Machine
Deploying a VMware Virtual Machine from a Template
Starting a VMware Virtual Machine
Stopping a VMware Virtual Machine
Taking a VMware Virtual Machine Snapshot
Deleting a VMware Virtual Machine Snapshot
Adding a New Hard Disk to a VMware Virtual Machine
Expanding a Virtual Disk in a VMware Virtual Machine
Gathering VMware Host Information on a Cluster
Getting a VMware Virtual Machine UUID
Ansible Dynamic Inventory For VMware
Getting a VMware Virtual Machine Running Host
Getting VMware Datastore Status
Uploading a File to the VMware Datastore
Getting the Status of VMware Guest Tools
Upgrading VMware Guest Tools
Live Migration of a VMware Virtual Machine Using vMotion
Changing the Boot Device Order of a VMware Virtual
Machine
Key Takeaways
Chapter 4: Closing Remarks
Key Takeaways
Index
About the Author
Luca Berton
is an Ansible Automation Expert who has
been working with the Red Hat Ansible
Engineer Team for three years. With
more than 15 years of experience as a
system administrator, he has strong
expertise in infrastructure hardening
and automation. An enthusiast of open
source, he supports the community by
sharing his knowledge in different
events of public access. Geek by nature,
Linux by choice, Fedora of course.
About the Technical Reviewer
Nikhil Jain
is an Ansible expert with over 12 years
of DevOps experience. He has been using
Ansible and contributing to it from its
inception. He currently works closely
with Ansible Engineering.
He is an open source enthusiast and
is part of the Ansible Pune Meetup
Organizing team. He has presented
multiple Ansible sessions at various
global and local events. Apart from
sitting in front of his computer
automating things using Ansible, he
loves watching sports and is a regular
part of the local cricket team.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
L. Berton, Ansible for VMware by Examples
https://doi.org/10.1007/978-1-4842-8879-5_1
What Is Ansible?
Let’s begin with a short overview about what Ansible is and why it is so
powerful.
Ansible was created more or less in February 2012 by Michael
DeHaan, a brilliant employee of Red Hat at the time. Michael was
inspired by several tools and his direct experience in the system
administrator industry. There was a strong need for con iguration
management to enable the use of the same con iguration across a Linux
administrated leet and the ability to consistently modify the con ig iles
every time. Michael started the Ansible tool in Python, the most
interesting computer language at the time, and built the foundation of
the module-based and agentless architecture. Every module performs a
speci ic task and creates some Python bytecode that gets sent directly to
the execution node via SSH for Linux, Unix (*BSD), and macOS targets.
For Windows, target Ansible produces a PowerShell or CMD deliverable,
shared via WinRM to perform the expected outcome. This simple and
extensible approach created the initial community. Michael created a
company to support the initial demand and it was acquired by Red Hat
in 2015. At the present time, Red Hat is leading the Ansible project and
creating the roadmap for the Community and Enterprise deliverables of
the Ansible project.
Ansible
Infrastructure automation tool
Open source Infrastructure-as-Code (IaC)
Let’s begin this adventure with the fabulous open source technology
named Ansible. It is classi ied as an infrastructure automation tool, so
you can automate your system administrator tasks very easily.
Ansible enables in your enterprise a process called Infrastructure-as-
Code, a way to processes the provisioning and managing of machines
using simple human-readable de inition iles. This is extremely useful in
a data center environment when the same task is commonly repeated
among a bunch of machines. Before Ansible, manual con iguration
required complex and specialized technical people for hardware
con iguration and interactive con iguration tools. Ansible lets you use
DevOps methodology principles. This programming style is also called
“declarative” because its focuses on the outcome of the execution and
not on the single action such as in the traditional imperative
programming languages (C, C++, Java, Python, etc.)
With Ansible, you can deploy your IaC on-premises and on the most
well-known public cloud providers.
Provisioning
The process of setting up the IT infrastructure
Let’s start talking about provisioning. All system administrators
know how important it is to manage a uniform leet of machines. Some
people still rely on software to create workstation images. But there is a
drawback because with imaging technology you’re only taking a
snapshot in time of the machine, so every time you need to reinstall
software because of the modern key activation systems or update
manually to the latest security patches. Ansible helps automate this
process by create a smoother process.
Application Deployment
The process of publishing your software between testing, staging, and
production environments
The third key use case where Ansible is useful is application
deployment. It can automate the continuous integration/continuous
delivery work low pipeline of your web applications, for example. Your
DevOps team will be delighted!.
Ansible For DevOps
Ansible is used to apply DevOps principles in worldwide organizations.
Let me quickly summarize. The DevOps methodology consists of a very
high-level set of best practices to follow in the full software lifecycle
from the initial design, coding, testing, releasing, active use, and
retirement from the market. These principles apply to small as well as to
big projects and are used by today’s IT professionals worldwide in small
to large organizations. Generally speaking, it applies engineering
principles to the software creation process. DevOps is so popular
because has the following strengths: performance, reuse, repeatability,
fault tolerance, and cost reduction. Also, the software used in a DevOps
environment is de ined as “toolchains” rather than a single command or
tool. The toolchains are usually speci ically designed for one speci ic
task. A common way to classify them is using DevOps categories. Each
category re lects the key aspect of the software design, development
testing, and delivery process. The eight DevOps categories are
Plan: The product/project manager analyzes the requirements and
feedback from internal and external stakeholder and creates a
product roadmap. The software is typically Jira, Azure DevOps, or
Asana.
Code: The development process that produces the code of your
project. Toolchains vary based on the computer language used and
source code versioning management tools.
Build: These toolchains are very speci ic according to the computer
language of your team. Methodologies of continuous
integration/continuous deployment (CI/CD) and build status apply.
Test: Continuous testing toolchains guarantee fast and updated
results based on business risks often based on IaC and many DevOps
pipelines.
Release: A set of tools that packages your software in a repository.
Deploy: The software enters the production phase. IaC to release in a
two stages blue-green deployment to use new production services
without any interruption of the service.
Operate: Infrastructure con iguration and management.
Infrastructure scaling and acquisition of feedback about the service.
Monitor: Application performance monitoring and end user
experience feedback.
Four Key Tenets of Ansible
1.
Declarative: You declare what you want rather than how to get to it.
2.
Agentless: You don’t need to install an agent. It takes advantage of
OpenSSH.
3.
Idempotent: An operation can be run multiple times without
changing beyond the initial operation.
4.
Community driven: Open source and extensible by Ansible Galaxy
collections and roles.
The four key tenets of Ansible are declarative, agentless, idempotent,
and community driven. With “declarative,” it means that you can use it in
a way very similar to a programming language to apply sequencing,
selection, and iteration to the code low. With “agentless,” it means that
Ansible operates in a way that doesn’t require installing an all-active
process (agent) on the target machine; it uses the SSH connection and a
Python interpreter. For Linux and Unix machines, this means using SSH,
either using OpenSSH or in constrained environments Paramiko (a
Python OpenSSH library). For Windows hosts, this means using
Windows Remote Management via PowerShell remoting.
The language itself is idempotent, which means that the code will
check a precise status on the managed machine. It means that, for
example, the irst time it runs, your code will change something and the
following runs only verify that nothing has changed and then it moves
forward. The last tenet is “community driven,” which means that Ansible
is an open source technology. Moreover, there exists a public archive of
extension resources called Ansible Galaxy where you can download code
made by other open source contributors to extend it even more. This
code is organized in roles and collections, and you’ll see them later in
this book.
Ansible History
2012: Developed by Michael DeHaan
2015: Acquired by Red Hat
2016: AnsibleFest events
2020: Red Hat Ansible Automation Platform 1.0
2021: Red Hat Ansible Automation Platform 2.1
2022: Red Hat Ansible Automation Platform 2.2
Let’s talk more about the main events in Ansible’s history. The irst
release of Ansible was on February 20, 2012. Michael DeHaan created
the Ansible tool and started advertising the irst initial community. Later,
he founded Ansible Inc. (initially AnsibleWorks Inc.), which guaranteed
the commercial support and sponsorship of the project. On October 16,
2015, Ansible Inc. was acquired by Red Hat, which evaluated Ansible as
a “powerful IT automation solution.” This is great recognition for the
Ansible technology that everyday helps enterprises innovate in the IT
industry. Every year since 2016, the Ansible Community reunites at an
event called AnsibleFest (virtually during pandemic time) with
conferences for users and contributors all around the planet.
Getting Started
It’s time to take your irst step with Ansible technology. You’ll learn how
to connect to the managed hosts and how to execute some simple tasks
using the Ansible command line tool.
Ansible Architecture
Let’s begin by talking about the Ansible architecture. The node where
Ansible is actually installed is called the Ansible control node and it
manages your leet of nodes. The controlled node is called a managed
node or target node. The target node could be Linux, Mac, Windows, or
network equipment. Each target has some speci icity like different Linux
distributions and module usage. We will discuss the speci icity in the
next sections.
Figure 1-1 Ansible architecture schema
Ansible Installation
The Ansible installation on the control node is covered in Chapter 2 of
this book.
demo.example.com
"ping": "pong"
"ping": "pong"
ping module executed on all host as user root after login with
user devops
demo.example.com replied with a changed code and print “ping”:
“pong” on the standard output
In this example, you run the ping module against the all host as
user root after a login with user devops. demo.example.com
replies with a changed code and prints “ping”: “pong” on standard
output.
Recap
In this section, you learned the basic concept of the Ansible architecture,
how to write a list of managed hosts, and how to execute some simple
commands against it.
Inventory
In this section, I’ll explain what an Ansible Inventory is, why you need it,
the different types, and how to edit and use it in your day-to-day journey.
An inventory is the set of hosts Ansible can work against.
They can be categorized as groups/patterns.
The list of multiple hosts managed by Ansible is called an inventory.
An Ansible inventory is fundamentally a list of target hosts to execute
your automation against. The target hosts can be in the same or different
infrastructure(s). The hosts can be organized in one or more groups or
patterns in order to ilter hosts according to common criteria.
all keyword
The keyword all includes all hosts of the inventory, except
localhost. The special keyword all includes all the hosts of the
inventory used. It will be very useful in the following lessons. The only
exception is localhost, which you need to specify.
host2.example.com
host3.example.com
ile name: ini_simple_inventory
host1.example.com is ungrouped
host2.example.com and host3.example.com are grouped as
frontends
The simplest inventory type is the INI inventory, by the type of the
ile stored by default in /etc/ansible/hosts. You can specify a
customized Ansible inventory using the -i parameter in your ansible
or ansible-playbook terminal. In this example, host
host1.example.com is ungrouped but host2.example.com and
host3.example.com are grouped as frontends.
---
all:
hosts:
host1.example.com:
children:
frontends:
hosts:
host2.example.com:
host3.example.com:
[frontends]
www[01:99].example.com
[backends]
back-[a-f].example.com
host1.example.com
[frontends]
host2.example.com
host3.example.com
[prod]
host2.example.com
[dev]
host3.example.com
Host Variables
In an inventory, you may want to store values as variables and associate
them with a speci ic host or group.
./ini_hostinventory
[frontends]
localhost ansible_connection=local
host1.example.com ansible_connection=ssh
ansible_user=devops
host2.example.com ansible_connection=ssh
ansible_user=ansible
host3.example.com ansible_user=example
ansible_ssh_private_key_file=~/prj/id_rsa
host4.example.com ansible_host=10.0.113.111
[frontends]
host1.example.com
host2.example.com
[frontends:vars]
ntp_server=europe.pool.ntp.org
./groupsvariables_inventory_yaml.yml
---
frontends:
hosts:
host2.example.com:
host3.example.com:
vars:
ntp_server: europe.pool.ntp.org
It is extremely useful not to repeat the same value for a lot of target
nodes, for example for the same NTP server for all your host in your
network. In the two inventory iles in the example (INI and YAML
formats), the variable ntp_server assigned the value
europe.pool.ntp.org for all the hosts of the group.
[asia]
host1.example.com
[europe]
host2.example.com
[frontends:children]
asia
europe
[frontends:vars]
ntp_server=europe.pool.ntp.org
./variableinheriting_inventory.yml
---
children:
frontends:
children:
asia:
hosts:
host1.example.com:
europe:
hosts:
host2.example.com:
vars:
ntp_server: europe.pool.ntp.org
In this example, the group frontends has two members, asia and
europe. These two groups contain only a single host each,
host1.example.com and host2.example.com, respectively, but
can contain more hosts. The variable ntp_server is de ined at the
frontends level. So, in the end, the ntp_server variable is visible in
all three groups: frontends, asia, and europe. The
host1.example.com and host2.example.com hosts inherit the
ntp_server variable from their related groups.
localhost ansible_connection="local"
Recap
Now you know more about Ansible INI and YAML inventory iles to
specify target hosts of your automation as well as variables with
parameters that affected your execution.
Playbook
In this section, I’ll explain what an Ansible Playbook is and why you need
it. I’ll cover how to start with a simple Playbook from the basic syntax
and how to add more tasks.
A playbook is a set of plays to be executed against an inventory.
YAML Syntax
# A sample YAML comment
statement # Another YAML comment
A sample string
'Another string'
"Another string"
with_newlines: |
Example Enterprise
813 Howard Street Oswego
New York, NY 13126
without_newlines: >
This is an example
of a long string,
that will become
a single sentence.
yaml_list1:
- value1
- value2
yaml_list2: [value1, value2]
helloworld.yml
helloworld.yml
---
- name: message demo
hosts: all
tasks:
- name: sample message
ansible.builtin.debug:
msg: "Sample Text"
...
file name: helloworld.yml
Name of the playbook: "message demo"
Hosts of execution: "all"
List of tasks
One task named "sample message"
Module ansible.builtin.debug
Argument `msg` of module debug
Sample Text
---
- name: message debug demo
hosts: all
tasks:
- name: sample message
ansible.builtin.debug:
msg: "Sample Text"
verbosity: 2
...
file name: helloworld_debug.yml
Name of the playbook: "message debug demo"
Hosts of execution: "all"
List of tasks
One task named "sample message"
Module debug
Argument `msg` of module debug
Argument `verbosity` is `2`
This tip allows you to keep the debug code in your Playbook and
enable the execution only when you need it. For example, the message is
printed only when Ansible is invoked with output level two.
Execution without any verbose parameter
$ ansible-playbook -i inventory
helloworld_debug.yml
skipping: [demo.example.com]
Idempotency
One important characteristic of most Ansible modules is to be
idempotent. It means that before executing any actions on the target
node, the module checks the actual status. If the actual status matches
the desired once, no action is performed. If the current status diverges
from the expected one, an action will take place. Please note that if you
execute the Playbook another time, the desired status will be found and
no further actions will be performed. This property is called
idempotency and you’re going to take advantage of it.
multipleplays.yml
---
- name: first play
hosts: www.example.com
tasks:
- name: first task
ansible.builtin.yum:
name: httpd
status: present
- name: second task
ansible.builtin.service:
name: httpd
enabled: true
- name: second play
hosts: database.example.com
tasks:
- name: first task
ansible.builtin.service:
name: mariadb
enabled: true
Recap
In this section, you put the foundation of the following operation on an
Ansible Playbook. Keep going and soon you will be able to automate all
your system administrator tasks.
Variables
In this section, I’ll explain what Ansible variables are, why you need
them, the different types, and how to edit and use them in your day-to-
day journey.
Variables store dynamic value for a given environment.
In your Playbook, it is a good practice to use variables to store all of
the dynamic values that you need. By editing variables you can reuse
your code in the future, only parameterized according to your business
needs.
variableprint.yml
./variableprint.yml
---
- name: variable demo
hosts: all
vars:
fruit: "apple"
tasks:
- name: print variable
ansible.builtin.debug:
msg: "The value of the variable {{ fruit
}}"
file name: variableprint.yml
Name of the playbook: "variable demo"
Hosts of execution: "all"
List of tasks
One task named "print variable"
Module debug
Argument "msg" of module debug
You can override the Playbook variables to specify the value in the
command line before the execution. When you set the variable value in
this way, it is called an extra variable. This output of the execution of
variableprint.yml is very similar to the previous one. Please note
the printing of the message “The value of the variable banana,” obtained
by combining the string with the value of the variable. The value passed
from the command line overrides any Playbook value.
[servers]
demo1.example.com ansible_user=devops
inventory_group_variables
[servers]
demo1.example.com
demo2.example.com
[servers:vars]
user=alice
Host and group variables can be de ined in your inventory ile. In the
left column, you see an example of a host variable. The variable
ansible_user is assigned the value devops. This host variable is
available for demo1.example.com. On the right column, you see an
example of a group variable. The variable user is assigned the value
alice. This group variable is available for demo1.example.com and
demo2.example.com with the same value.
inventory_host_dir
[servers]
demo1.example.com
host_vars/demo1.example.com
ansible_user=devops
inventory_group_dir
[servers]
demo1.example.com
demo2.example.com
group_vars/servers
user=alice
You can achieve the same result by also using directories to populate
host and group variables. As you can see, the result are the same as the
previous example but using more iles. In the left column, you see an
example of a host variable. The variable ansible_user is assigned the
value devops. This host variable is available for
demo1.example.com. On the right column, you see an example of a
group variable. The variable user is assigned the value alice. This
group variable is available for demo1.example.com and
demo2.example.com with the same value.
Array Variables
array.yml
---
- name: Array demo
hosts: all
vars:
users:
alice:
firstname: Alice
homedir: /users/alice
bob:
firstname: Bob
homedir: /users/bob
tasks:
- name: Alice's first name
ansible.builtin.debug:
var: users['alice']['firstname']
file name: array.yml
Users are organized in a hierarchical data
structure.
Returns 'Alice'
users.alice.firstname
Returns 'Alice'
users['alice']['firstname']
array.yml Execution
$ ansible-playbook -i inventory array.yml
Registered Variables
registeredvariables.yml
---
- name: wget installed demo
hosts: all
become: true
tasks:
- name: wget installed
ansible.builtin.yum:
name: wget
state: present
register: install_result
Recap
In this section, you explored variable usage inside the Ansible Playbook.
You now are aware of the use of tools like the user-de ined host, group,
and registered variables.
Ansible Facts
In Ansible jargon, the system variables related to target hosts are called
facts. Inside them you can ind system information or runtime values, as
well as the use of the behavior or the state of the system as con iguration
on other systems.
They are so powerful because you can obtain a very comprehensive
vision of the current host, the operating system, the distribution used,
the IP address, the networking con iguration, the storage con iguration,
and more.
Listing All Facts About a Machine Ad-Hoc
$ ansible -m setup one.example.com
demo.example.com | SUCCESS => {
"ansible_facts": {
"ansible_all_ipv4_addresses": [
"192.168.43.35",
"10.0.2.15"
],
"ansible_all_ipv6_addresses": [
"fe80::a00:27ff:fe71:bd5a"
],
"ansible_apparmor": {
"status": "disabled"
},
"ansible_architecture": "x86_64",
"ansible_bios_date": "12/01/2006",
"ansible_bios_vendor": "innotek GmbH",
"ansible_bios_version": "VirtualBox",
"ansible_board_asset_tag": "NA",
"ansible_board_name": "VirtualBox",
"ansible_board_serial": "NA",
"ansible_board_vendor": "Oracle Corporation",
"ansible_board_version": "1.2",
"ansible_chassis_asset_tag": "NA",
"ansible_chassis_serial": "NA",
"ansible_chassis_vendor": "Oracle Corporation",
"ansible_chassis_version": "NA",
"ansible_cmdline": {
"BOOT_IMAGE": "(hd0,msdos1)/vmlinuz-4.18.0-
348.el8.x86_64",
"biosdevname": "0",
"crashkernel": "auto",
"net.ifnames": "0",
"no_timer_check": true,
"quiet": true,
"rd.lvm.lv": "rhel_rhel8/swap",
"resume": "/dev/mapper/rhel_rhel8-swap",
"rhgb": true,
"ro": true,
"root": "/dev/mapper/rhel_rhel8-root"
},
"ansible_date_time": {
"date": "2022-07-22",
"day": "22",
"epoch": "1658504009",
"epoch_int": "1658504009",
"hour": "15",
---
- name: facts_printall
hosts: all
tasks:
- name: Print all facts
ansible.builtin.debug:
var: ansible_facts
You can access the same amount of data from the Ansible Playbook.
In this simple example, you list all Ansible facts for all hosts of the
inventory. The expected result will be the same as the previous ad-hoc
execution.
facts_printall.yml Execution
ansible-playbook -i inventory facts_printall.yml
PLAY [facts_printall]
****************************************************
TASK [Gathering Facts]
***************************************************
ok: [host1.example.com]
TASK [Print all facts]
***************************************************
ok: [host1.example.com] => {
"ansible_facts": {
"architecture": "x86_64",
"bios_date": "10/12/2020",
"bios_version": "N22ET66W (1.43 )",
"br_4332d8483447": {
"active": false,
"device": "br-4332d8483447",
"features": {
"esp_hw_offload": "off [fixed]",
"esp_tx_csum_hw_offload": "off
[fixed]",
"fcoe_mtu": "off [fixed]",
Referencing a Fact
facts_printone.yml
---
- name: facts_printone
hosts: all
tasks:
- name: Print a fact
ansible.builtin.debug:
var: "{{ ansible_facts['architecture'] }}"
You can easily interact with facts by specifying the fact name. In this
example, you’re listing the architecture of the managed nodes (example:
architecture: x86_64). Feel free to customize the code to the
Ansible facts that better it your needs.
Magic Variables
Magic variables are internal variables of Ansible used to expose some
system status or runtime con igurations.
Recap
Ansible facts and magic variables are very useful in your Ansible
Playbook especially when you need to execute operations that impact all
hosts in the inventory. For example, to generate a custom /etc/hosts
ile for all the hosts involved in the inventory, you can apply a loop or
other statements, which you’re going to explore in the next lessons.
Vault
In this section, I am going to talk about how to store secured and
encrypted sensitive data (passwords, API keys, usernames, tokens, etc.)
using Ansible Vault. Ansible Vault stores variables and iles in an
encrypted way and lets you use them in Playbooks or roles. The
encryption is strong using AES 256 as a cipher to protect your iles in the
recent versions of Ansible. The ansible-vault command line utility
is used to manage Ansible Vault iles.
Example of contents of a ile encrypted with the ansible-vault
tool:
$ANSIBLE_VAULT;1.1;AES256
39393061383130646631353339636263623336366237396361393
439626232366164306137333230
3239633330353939363733316661336339396233373337300a343
132623636653835623030316565
[...]
The command prompts for the vault password to be used two times
and then opens a new ile using your terminal default editor (Vim, Nano,
Emacs, etc.). In this example, the password used is password but I
strongly encourage you to use one as secure as possible.
You can also store the password in a ile (password.txt) and pass
it as a parameter using the --vault-password-file= option:
Please note that if you omit the --output option, the original ile
will be overwritten with the encrypted one.
Please note that if you omit the --output option, the original ile
will be overwritten with the decrypted one.
This command also allows you to rekey multiple Ansible Vault iles
at once. It prompts for the original password and then the new
password.
$ ansible-playbook --vault-password-file=vault-
password.txt playbook.yml
Recap
In this section, you explored the Ansible Vault security storage to save
secrets and con idential information inside Ansible. As you saw, these
tools are robust and completely integrated inside the Ansible technology.
Conditional
In this section, I’ll explain what Ansible conditional operations are and
how you can use them every day in your Ansible Playbook. A conditional
statement checks a condition and performs one or a set of tasks
accordingly.
Computers have the ability to execute a huge amount of operations
and tasks. Sometimes you need to execute one task or a set of tasks only
when some conditions are happening. Common use cases involve
speci ic values of a variable, in most cases boolean (True or False),
some environment variables, some running conditions, or some speci ic
version of the operating system in the running node. In Ansible, you
express the conditional with the when statement. It’s very powerful
because it’s based on the Jinjia2 tests and ilters. You may also specify
complex expressions, combined by traditional comparison operators
and also by the and, or, and not logical operations. You can use the
built-in Ansible tests and ilters or expand with a collection or create
your own. The code is executed only when the result of the when
expression is True.
For example, let’s imagine an Ansible Playbook that installs a web
server on Linux. You need to use YUM/DNF-speci ic code for RedHat-like
systems, APT for Debian-like systems, and ZYPPER for Suse-like systems.
Another example is the need to install a different package name or
version based on the operating system version, such as version 8 and
version 9 of the Red Hat Enterprise Linux.
---
- name: conditional_basic
hosts: all
vars:
configure_nginx: false
tasks:
- name: reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
when: configure_nginx
This is the basic example of the usage of the when statement in your
Ansible playbook. The task reload nginx is executed only when the
configure_nginx boolean variable is set to true. We expect this
task to be skipped. Let’s see the output of the executed code.
The execution output includes
Target host: demo1.example.com
Command result: skipping=1
Return value:
---
- name: conditional_basic
hosts: all
vars:
configure_nginx: true
tasks:
- name: reload nginx
ansible.builtin.service:
name: nginx
state: reloaded
when: configure_nginx
This is the same basic example of the usage of the when statement in
your Ansible Playbook but you changed the variable value from false
to true. The task reload nginx is now going to be executed because
the configure_nginx boolean variable is set to true. Let’s see the
output of this code execution.
The execution output includes
Target host: demo1.example.com
Command result: ok=2
Return value:
---
- name: conditional_facts
hosts: all
tasks:
- name: Shut down Debian-like systems
ansible.builtin.command: /sbin/shutdown -t now
when: ansible_facts['os_family'] == "Debian"
It is very useful to combine conditional and facts. You can adapt the
execution of your code based on variable values, runtime conditions, the
value of the IP address, the version of the operating system, some
storage or ile system object status, and so on. In this example, suppose
you want to shut down only the Debian-like target system, so Debian
and Ubuntu managed hosts.
The execution output includes
Target host: demo1.example.com
Command result: skipped=1
Return value:
As you can see, the status of the task Shut down Debian-like
systems on the target demo1.example.com is skipped. This
means that the system demo1.example.com isn’t using a Debian-like
Linux operating system.
Recap
Conditionals are very important because they enable you to create
Ansible Playbooks that respond to some events, conditions, or Ansible
facts. This statement is the foundation of the smart Ansible Playbook.
Loop
In this section, I’ll explain what Ansible loop operations are and how you
can use them every day in your Ansible Playbook. Loops automate
repetitive tasks.
Computers are great for the fast execution of a block of code of tasks.
According to Moore’s Law, every two years the number of transistors
doubles in a dense integrated circuit. Computers are faster than any
human on the planet and they make no mistakes. In computers,
programming language loops are also called iterations. Ansible includes
several statements for iteration: the loop statement and the
with_items statements. The with statement relies on plugins.
loop_simple.yml
---
- name: Check services
hosts: all
tasks:
- name: httpd and mariadb are running
ansible.builtin.service:
name: "{{ item }}"
state: started
loop:
- httpd
- mariadb
This example checks that two services (httpd and mariadb) are in
the “started” state. Every service name is listed directly as a list element
under the loop statement. Please note the usage of the variable item
that iterates the current values in each iteration. Here item is going to
be expanded for each element of the list (in this case, httpd and
mariadb).
loop_hash_or_dict.yml
---
- name: users and group example
hosts: all
tasks:
- name: add users to groups
ansible.builtin.user:
name: "{{ item.name }}"
state: present
groups: "{{ item.group }}"
loop:
- name: alice
group: wheel
- name: bob
group: root
Some use cases require more complex iteration variable types such
as hashes or dictionaries. As always, Ansible relies heavily on Python
data types. This is an example of a dictionary with two keys: name and
group for each element of the list. You can access the current item
loop variable using a dot. Speci ically, name can be retrieved with the
item.name and group with item.group variables, respectively.
with_* Statement
with_items
Like loop for simple lists, a list of strings, or a list of
hashes/dictionaries. Faster to list if lists of lists are provided
with_file
This keyword requires a list of control node ile names. The loop
variable item holds the content of the ile
with_sequence
Requires parameters to generate a list of values based on a numeric
sequence. From 0 to 10, for example.
loop_with_items.yml
---
- name: Example with_items
hosts: all
vars:
data:
- alice
- bob
tasks:
- name: Print values of data
ansible.builtin.debug:
msg: "{{ item }}"
with_items: "{{ data }}"
Recap
Loops statements are very useful to automate repetitive tasks. Loops are
the foundation of a successful Ansible Playbook.
Handler
In this section, I’ll explain what an Ansible Handler statement is and how
you can use it every day in your Ansible Playbook.
rollingupdate.yml
---
- name: Rolling update
hosts: all
become: true
tasks:
- name: latest apache httpd package is
installed
ansible.builtin.yum:
name: httpd
state: latest
notify: restart apache
handlers:
- name: restart apache
ansible.builtin.service:
name: httpd
state: restarted
Role
In this section, I’ll explain what Ansible’s role is in code reuse and how
you can use it every day in your Ansible Playbook. The Ansible role
enables code reuse in Ansible.
Roles are like functions in the traditional programming world. An
Ansible role enables code reuse and sharing in a public directory called
Ansible Galaxy (https://galaxy.ansible.com/). Creators from
all over the world contribute code in the Ansible Galaxy directory. The
usage of Ansible roles dramatically speeds up any Ansible Playbook
development, enabling access to a lot of high-quality resources. Another
amazing public resource is the Linux System Roles: A collection of
Ansible roles and modules at https://linux-system-
roles.github.io/at.
role.example/
|-- defaults
| `-- main.yml
|-- files
|-- handlers
| `-- main.yml
|-- meta
| `-- main.yml
|-- README.md
|-- tasks
| `-- main.yml
|-- templates
|-- tests
| |-- inventory
| `-- test.yml
`-- vars
`-- main.yml
Please note that not every role will have all of these directories but
it’s good to know the scope and how to take advantage of them in your
coding.
Directory description:
defaults
In the main.yml ile you can de ine the default value for each
variable user in the role. These variables are intended to be overwritten
in your Playbook when you execute the role.
files
In the files directory, you store all the static iles present inside by
role tasks.
handlers
Every handler is supposed to be de ined in the main.yml ile under
this directory.
meta
This is the most descriptive part of the Ansible role, and the
main.yml ile includes information about the creator, the iles license,
the tested platforms, and optionally the Ansible role dependencies.
tasks
This is the heart of your automation and effectively contains all the
Ansible tasks to be executed.
templates
All Jinja2 templates of the role are under this directory.
tests
Any code to test the Ansible role was originally stored under this
directory. Nowadays it’s substituted by the Ansible Molecule project
(https://molecule.readthedocs.io/en/latest/).
vars
The main.yml ile in this directory represents the Ansible role’s
internal variables. Often these variables are used for internal purposes
within the role. These variables have high precedence and are not
intended to be changed when used in a Playbook.
---
- name: role example
hosts: all
roles:
- role1
- role2
file name: role_simple.yml
Apply the "role1" and "role2" to the "all" managed
hosts
./role_vars.yml
---
- name: role example
hosts: all
roles:
- role: role1
- role: role2
var1: value
var2: value
file name: role_vars.yml
Apply the "role1" and "role2" to the "all" managed
hosts
Order of Execution
./role_vars.yml
---
- name: order of execution example
hosts: all
pre_tasks:
- debug:
msg: 'pre-task'
notify: my handler
roles:
- role1
tasks:
- debug:
msg: 'first task'
notify: my handler
post_tasks:
- debug:
msg: 'post-task'
notify: my handler
handlers:
- name: my handler
debug:
msg: Running my handler
For each play in a Playbook, tasks execute as ordered in the tasks list.
After all tasks execute, any noti ied handlers are executed. When a role is
added to a play, role tasks are added to the beginning of the tasks list. If a
second role is included in a play, its tasks list is added after the irst role.
Role handlers are added to plays in the same manner that role tasks are
added to plays. Each play de ines a handler’s list. Role handlers are
added to the handlers list irst, followed by any handlers de ined in the
handlers section of the play. In certain scenarios, it may be necessary to
execute some play tasks before the roles. To support such scenarios,
plays can be con igured with a pre_tasks section. Any task listed in
this section executes before any roles are executed. If any of these tasks
notify a handler, those handler tasks execute before the roles or normal
tasks. Plays also support a post_tasks keyword. These tasks execute
after the play’s normal tasks, and any handlers they notify are run.
Ansible Galaxy
https://galaxy.ansible.com/
- src: geerlingguy.redis
version: "1.5.0"
$ ansible-galaxy install -r
roles/requirements.yml -p roles
Collection
An Ansible Collection is a distribution format for shipping some Ansible
resources. It is usually speci ic for a single use case and contains all the
relevant Ansible resources that distribute playbooks, roles, modules, and
plugins. For users, the Ansible Collection is easy to download and share
via the Ansible Galaxy directory. For developers, the Ansible Collection is
easy to upload and share via Ansible Galaxy. Plus, an Ansible Collection
has a de ined standard directory structure and format.
Refer to the “Installation of the Additional Collection” section in
Chapter 2 for some code samples about how to install the
community.vmware Ansible Collection.
Ansible Plugins
Plugins extend the functionality of Ansible and unlock many
applications. For example, the lookup plugins enable you to extend Jinja2
to access data from outside sources within your playbooks, and they
execute and are evaluated on the Ansible control node. Famous use cases
are for reading from Windows INI style iles (ini), reading from CSV iles
(csv ile), listening iles matching shell expressions ( ileglob), reading
lines from stdout (lines), generating a random password (password),
reading from a Unix pipe (pipe), and returning content from a URL via
HTTP or HTTPS (url).
The full list of plugin types includes action, cache, callback,
connection, ilter, inventory, lookup, test, and vars.
Please refer to the of icial “Ansible Working with Plugins” guide at
https://docs.ansible.com/ansible/latest/plugins/plu
gins.xhtml for more details.
Key Takeaways
Whether a beginner or an experienced Ansible user, you now have more
familiarity with the Ansible code language, architecture, and
terminology. You explored concepts like ad-hoc commands, inventories,
Playbooks, variables, facts and magic variables, vaults, conditionals,
loops, handlers, roles, and Collections.
In the next chapter, you are going to install an Ansible control node
on the most used operating systems. The following chapter is completely
focused on VMware automation with Ansible.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
L. Berton, Ansible for VMware by Examples
https://doi.org/10.1007/978-1-4842-8879-5_2
2. Installing Ansible
Luca Berton1
You can get more details on the current releases and maintenance
plans on the Ansible of icial website.
ansible-core
The ansible-core package is for Ansible expert users or production
systems. It contains only the Ansible platform technology and enables
you to install the additional collections. This is the main building block
of the Ansible architecture. The ansible-core package includes the
Ansible platform for developing the Ansible Playbooks such as
conditionals and blocks, and it includes a loop and other Ansible
imperatives plus an extensive architectural framework to enable
Ansible collections and all the command-line tools for interacting with
automation (ansible-playbook, ansible-doc, etc.) The release
cycle is approximately twice per year by the Ansible Engineering Team.
---
collections:
- name: community.vmware
source: https://galaxy.ansible.com
– command execution
$ ansible-galaxy install -r
collections/requirements.yml
The command may return multiple results if they apply, with the
relevant ile system path and version(s). If no result is returned, it
means that no versions of the Ansible collection are currently installed
in the system right now.
Links
Ansible Core of icial documentation,
https://docs.ansible.com/ansible-
core/devel/index.xhtml
ansible-core package, https://pypi.org/project/ansible-
core/
Ansible community package,
https://pypi.org/project/ansible/
Code
The following code installs the latest version of Ansible 2.9 in your
RedHat Enterprise Linux (RHEL) 8.
Install Ansible RHEL8
Please note you need root privileges to execute the following
commands. First, you need to enable the RHSCL using the
subscription-manager tool:
This command installs the Ansible package as well as all the needed
dependencies python3-babel, python3-cffi, python3-
cryptography, python3-jinja2, python3-markupsafe,
python3-pycparser, python3-pytz, python3-pyyaml,
sshpass, and weak dependency python3-jmespath.
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in version 2.9.27 on Python 3.6.8 (July
2022).
Code
You can install the Ansible package in Ubuntu 22.04 LTS with the
universe and ansible/ansible PPA repositories.
universe
Install-Ubuntu-Universe.sh
Please note you need root privileges to execute the following
commands or use sudo before the following commands. First, you may
need to update the package manager metadata cache using the apt
tool:
# apt update
Then you can install the ansible package using the apt or apt-
get tool:
PPA
Install-Ubuntu-PPA.sh
If you prefer to install ansible-core using the
ansible/ansible PPA repository, you must irst enable it using this
command:
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in ansible-core version 2.12.4 on
Python 3.10.4 (July 2022).
Code
Install Ansible in Fedora version 36 via the AppStream system
repository using the ansible-core or Ansible community packages.
Please note you need root privileges to execute the following
commands. You can install the latest release of the Ansible community
release using the DNF tool:
install-Ansible-Fedora.sh
This command installs the Ansible package as well as all the needed
dependencies (ansible-core, libsodium, python3-bcrypt,
python3-jmespath, python3-ntlm-auth, python3-
packaging, python3-pynacl, python3-pyparsing,
python3-requests_ntlm, python3-resolvelib,
python3-xmltodict) and weak dependencies (python3-
paramiko, python3-pyasn1, python3-winrm).
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in ansible-core version 2.12.5 on
Python 3.10.4 (July 2022).
Ansible Installation for CentOS 9 Stream
You can install and maintain Ansible in CentOS 9 Stream using the
AppStream repository or the EPEL Next (Extra Packages for Enterprise
Linux) repository for your YUM/DNF package manager. The easier way
is by using DNF and the AppStream repository that comes out of the
box with CentOS Linux.
ansible-core package in the system AppStream repository
The easier way to install and maintain Ansible inside CentOS Stream
version 9 is using the system AppStream repository.
Use EPEL Next additional packages for CentOS Stream
Another way is to use the additional EPEL Next repository. This
repository contains enterprise-quality packages for CentOS Stream,
similar to EPEL packages but targeting RHEL, CentOS, Scienti ic Linux,
and Oracle Linux.
Links
CentOS Stream download, www.centos.org/centos-stream/
EPEL 9 is now available,
https://communityblog.fedoraproject.org/epel-9-
is-now-available/
Introducing CentOS Stream 9,
https://blog.centos.org/2021/12/introducing-
centos-stream-9/,
Install EPEL (Extra Packages for Enterprise Linux),
https://docs.fedoraproject.org/en-US/epel/
Code
To install the latest release of Ansible Core in CentOS Stream version 9
via the AppStream system repository, please note you need root
privileges to execute the following commands. You can install the
ansible-core package using the yum or DNF tool:
Install-Ansible-CentOS-Stream9.sh
# dnf install ansible-core
This command installs the Ansible package as well as all the needed
dependencies: emacs-filesystem, git, git-core, git-
core-doc, perl-Error, perl-Git, python3-babel,
python3-cffi, python3-cryptography, python3-
jinja2, python3-markupsafe, python3-pycparser,
python3-pytz, python3-pyyaml, and sshpass.
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in ansible-core version 2.12.0 on
Python 3.9.8 (July 2022).
Links
More technical information:
WSL (Windows Subsystem for Linux),
https://docs.microsoft.com/en-
us/windows/wsl/compare-versions
Ansible on Windows FAQ,
https://docs.ansible.com/ansible/latest/user_guid
e/windows_faq.xhtml
WSL on Windows 11,
https://arstechnica.com/gadgets/2021/10/the-best-
part-of-windows-11-is-a-revamped-windows-
subsystem-for-linux/
Code
To install the latest version of Ansible on Windows using Microsoft
WSL, you can activate it by executing PowerShell as a user with
administrator rights.
install_wsl.ps1
wsl --install
The apt package manager takes care of all the necessary package
dependencies from the ubuntu repository: ieee-data, python3-
argcomplete, python3-crypto, python3-dnspython,
python3-jmespath, python3-kerberos, python3-
libcloud, python3-lockfile, python3-netaddr,
python3-ntlm-auth, python3-requests-kerberos,
python3-requests-ntlm, python3-selinux, and python3-
winrm python3-xmltodict.
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in ansible version 2.9.6 on Python
3.8.2 (July 2022). I suggest evaluating the installation of the latest
release of Ansible via PIP in this system.
Code
First, verify that the Homebrew package manager is successfully
installed on your system or refer to the installation process on the
of icial website (one command line to copy and paste). This step usually
requires you to open a terminal on your macOS and type the
installation command. When Homebrew is successfully installed, you
can proceed with installing ansible in your system.
Install the latest release.
Links
SUSE Package Hub: Community maintained packages for SUSE Linux
Enterprise Server/Desktop, https://packagehub.suse.com/
How to register SLES using the SUSEConnect command line tool,
www.suse.com/support/kb/doc/?id=000018564
SUSE Package Hub repositories for SUSE Linux Enterprise Server,
www.suse.com/support/kb/doc/?id=000018789
Code
You can install the latest version of ansible in SUSE Linux Enterprise
Server 15 SP3 using the SUSE Package Hub repository. Please adapt the
code to your distribution version.
Please note you need root privileges to execute the following
commands.
Install-Ansible-SLES-15-SP3.sh
# SUSEConnect -p PackageHub/15.3/x86_64
The irst line activates the SUSE Package Hub repository and the
second installs ansible in your system using the Zypper package
manager.
Code
You can proceed with the installation of the latest version of Ansible
with PIP, the Python package manager.
code PIP
You can install the software for just the current user or system-wide.
First, verify that PIP is successfully installed on your system. Usually,
you need to install it with your distribution package manager such as
yum, DNF, apt, or Zypper.
Please adjust python to python3, and python3.9 as needed.
Install-pip-user.sh
Install-pip-global.sh
Installing software system-wide requires root permission
privileges.
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in ansible-core version 2.13.1 on
Python 3.9.2 (July 2022).
Links
Ansible Core package included in the RHEL AppStream,
https://access.redhat.com/articles/6325611
Using Ansible in RHEL 9,
https://access.redhat.com/articles/6393321
Demo
Perform the installation of the latest Ansible-Core in RHEL 9 using the
DNF Package Manager.
Install-Ansible-RHEL9.sh
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in ansible-core version 2.12.2 on
Python 3.9.10 (July 2022).
Links
Amazon Linux 2, https://aws.amazon.com/it/amazon-
linux-2/
Enable the EPEL repository in Amazon Linux2,
https://aws.amazon.com/it/premiumsupport/knowledg
e-center/ec2-enable-epel/
Extras library (Amazon Linux 2),
https://docs.aws.amazon.com/AWSEC2/latest/UserGuid
e/amazon-linux-ami-basics.xhtml#extras-library
Extra Packages for Enterprise Linux (EPEL),
https://docs.fedoraproject.org/en-US/epel/
Code
You can install Ansible in Amazon Linux (EC2) 2 using the Amazon
Extras Library or the EPEL repositories for the YUM package manager.
Let’s start with the Amazon Extras Library option.
Please note you need root privileges to execute the following
commands.
Install-Ansible-Amazon Linux2-Amazon Extras Library.sh
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in ansible version 2.9.23 on Python
2.7.18 (July 2022). You might consider installing the latest ansible-
core release via PIP in this system.
EPEL
You can install Ansible in Amazon Linux (EC2) 2 using the EPEL
repositories option for the YUM package manager. Please note you need
root privileges to execute the following commands or use sudo
command.
Install-Ansible-Amazon Linux2-EPEL.sh
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in ansible-core version 2.9.25 on
Python 2.7.18 (July 2022). You might consider installing the latest
ansible-core release via PIP in this system.
Code
You can install Ansible in Debian 11 using the apt package manager and
the main default repository.
Install-ansible-debian.sh
Please note you need root privileges to execute the following
commands or use sudo before the following commands.
First, you may need to update the package manage metadata cache
using the apt tool:
# apt update
Then you can install the ansible package using the apt or apt-
get tool:
This command installs the ansible package as well as all the needed
dependencies: ieee-data, python3-argcomplete, python3-
dnspython, python3-jmespath, python3-kerberos,
python3-libcloud, python3-lockfile, python3-
netaddr, python3-ntlm-auth, python3-packaging,
python3-pycryptodome, python3-requests-kerberos,
python3-requests-ntlm, python3-requests-toolbelt,
python3-selinux, python3-simplejson, python3-
winrm, and python3-xmltodict.
Veri ication
You can verify the successful installation of Ansible using the
ansible --version command in any terminal. At the time of
writing this book, it’s available in ansible version 2.10.8 on Python
2.9.2 (July 2022). You might consider installing the latest ansible-
core release via PIP in this system.
Key Takeaways
You’re now able to successfully install an Ansible Control node, the
“server” node that runs the automation, in all of the most used Linux
and Enterprise Linux distributions, macOS, and Windows operating
systems.
The newest Ansible package distribution policy (community vs.
core) enables more lexible and space-ef icient ways to deploy the
Ansible platform and add only the relevant collections for your
automation.
A lot of the most recent operating systems fully embrace this
approach, and the list goes on and on.
In the following chapter, you are going to apply all the Ansible
language code knowledge to automate the VMware infrastructure via
code nutshells and commands snippets. By automating simple and
complex tasks, you’re going to save time and build an Infrastructure as
Code (IaC) by applying DevOps methodologies.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
L. Berton, Ansible for VMware by Examples
https://doi.org/10.1007/978-1-4842-8879-5_3
Links
Introduction to Ansible for VMware,
https://docs.ansible.com/ansible/latest/scenario_
guides/vmware_scenarios/vmware_intro.xhtml
community.vmware.vmware_guest_info,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_info_module.xhtm
l
Code
Please allow me to guide you through the three main steps of
automating your VMware infrastructure using Ansible. I’m going to
share with you all the relevant resources to be successful on your
Ansible journey from the beginning. Let’s consider the use case of
gathering information about a VMware virtual machine using the
Ansible Playbook. Here’s how to con igure Ansible for VMware:
1.
Install pyVmomi.
First, you need to install pyVmomi, the VMware vSphere API Python
Bindings.
Don’t panic! The irst time you try to execute an Ansible Playbook
on a system without the required pyVmomi Python library, you will
receive a fatal error. This error may also indicate that Ansible is not able
to locate the Python library in the current Python virtual environment
or Ansible execution environment. Whenever the pyVmomi Python
library is missing, the execution terminates with a FAILED status and
you will see the following fatal error and description:
You can use PIP, the Python Package Manager, to install the required
pyVmomi Python library. Please note that you may need to adjust the
command based on the Python version running on your system. For
example, pip3 for Python 3, pip3.9 for Python 3.9. Some
distributions require installation of the python3-pip package. The
following command installs the pyVmomi Python library system-wide
using root privileges:
Under the hood, PIP takes care of all the necessary Python
dependencies: requests, six, chardet, idna, and urllib3.
After this command, you should have pyVmomi successfully
installed on your system and you’re ready to move to the following step.
2. Install the community.vmware collection.
---
collections:
- name: community.vmware
---
- name: info vm demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: get VM info
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ vcenter_datacenter }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
register: detailed_vm_info
- name: print VM info
ansible.builtin.debug:
var: detailed_vm_info
I prefer to store all the connection parameters in a separate
vars.yml Ansible Playbook ile that can be shared among different
Ansible Playbook iles. I strongly recommend you encrypt this
document as an Ansible Vault because there is the username and
password to connect to your VMware infrastructure.
vars.yml
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
These are simple variables used in the Ansible Playbook that you
must customize to re lect the one actually used in your VMware
infrastructure. The variable vcenter_hostname contains the
hostname or IP address of your VMware ESXi or vCenter. The variable
vcenter_datacenter contains the name of the data center, for
example, vmwaredatacenter. The variable
vcenter_validate_certs is a boolean that enables true or
disables false for the SSL certi icate validation. I disabled the SSL
certi icate validation in order to use a self-signed certi icate in my
infrastructure. I encourage you to use a valid SSL certi icate or insert
the local certi ication authority in the chain of trust of your system. The
variable vcenter_username contains the username to connect to
your VMware infrastructure. When it’s a local username, you should
append the suf ix @vsphere.local or use an LDAP/ActiveDirectory
credential. The variable vcenter_password contains the password
used for the connection. Please be very careful about the case and
special characters. You might need to escape some of them to use with
Ansible. The variable vm_name contains the name of the virtual
machine that you would like to get information about. In this example,
it’s myvm. Feel free to customize your code or use an extra variable in
the command line.
When the previous steps are successful, the Ansible execution is
super smooth and you will see onscreen all the details of your myvm
VMware virtual machine.
The output includes
Target host: localhost
Command result: ok=3
Return value: A long JSON output
The most important key is instance where you can read all the
relevant information about the VMware virtual machine. Let me give
you one example:
Running server: "hw_esxi_host": "vmware.example.com"
Running cluster: `"hw_cluster": "prod-cluster"
Virtual machine name:"hw_name": "myvm"
Motion id: "moid": "vm-17923"
Instance UUID: "hw_product_uuid": "4225a846-b176-
892d-0e27-10a4106269a0"
Number of CPU processors: "hw_processor_count": 1
Number of CPU cores: "hw_cores_per_socket": 1
RAM resources: "hw_memtotal_mb": 1024
Datastore name:
"hw_datastores": [
"Datastore-1"
],
"hw_files": [
"[Datastore-1] myvm/myvm.vmx",
"[Datastore-1] myvm/myvm.vmsd",
"[Datastore-1] myvm/myvm.vmdk"
],
Network interfaces and status:
"hw_interfaces": [
"eth0"
]
"hw_eth0": { ... }
Links
Ansible collection community.vmware,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/index.xhtml
Python pyVmomi, https://github.com/vmware/pyvmomi
VMware vSphere Automation SDK for Python,
https://github.com/vmware/vsphere-automation-sdk-
python
Code
In order to successfully use the Ansible collection called
community.vmware of modules and plugins to manage various
operations related to virtual machines in the given ESXi or vCenter
server, you can con igure a Python virtual environment. These two are
the main Python dependencies to handle in your Python virtual
environment for Ansible VMware:
pyVmomi: VMware vSphere API Python bindings
vsphere-automation-sdk-python: VMware vSphere
Automation SDK for Python
The Ansible For VMware resources are written on top of the
pyVmomi Python SDK for the VMware vSphere API that allows users to
manage ESX, ESXi, and the vCenter infrastructure. Another useful
library is VMware vSphere Automation SDK for Python; it is
used for additional features such as list tags in the Ansible dynamic
inventory vmware_vm_inventory plugin. This example uses Python
3.8 so the pip3.8 tool adapts to your current con iguration. Some
Linux distributions require the installation of the python-pip or
python3-pip package in order to provide the PIP tool. Please adjust
python3.8 to python, python3, and python3.9 and pip3.8 to
pip, pip3, and pip3.9 according to the running version in your
system.
configure-Python-venv.sh
The PIP package installer takes care of all the necessary Python
dependencies:
for pyVmomi: six and requests
for vSphere-Automation-SDK-Python: cffi,
cryptography, lxml, nsx-policy-python-sdk, nsx-
python-sdk, nsx-vmc-aws-integration-python-sdk,
nsx-vmc-policy-python-sdk, pyOpenSSL, pycparser,
vapi-client-bindings, vapi-common-client, vapi-
runtime, vmc-client-bindings, vmc-draas-client-
bindings.
Once installed, you can produce a requirements.txt ile, which
is useful to share with other systems or recreate the Python virtual
environment using the command
certifi==2022.6.15
cffi==1.15.1
charset-normalizer==2.1.1
cryptography==37.0.4
idna==3.3
lxml==4.9.1
nsx-policy-python-sdk @ file://localhost//tmp/pip-
req-build-lv0gh902/lib/nsx-policy-python-
sdk/nsx_policy_python_sdk-4.0.0.0.0-py2.py3-none-
any.whl
nsx-python-sdk @ file://localhost//tmp/pip-req-
build-lv0gh902/lib/nsx-python-sdk/nsx_python_sdk-
4.0.0.0.0-py2.py3-none-any.whl
nsx-vmc-aws-integration-python-sdk @
file://localhost//tmp/pip-req-build-
lv0gh902/lib/nsx-vmc-aws-integration-python-
sdk/nsx_vmc_aws_integration_python_sdk-4.0.0.0.0-
py2.py3-none-any.whl
nsx-vmc-policy-python-sdk @
file://localhost//tmp/pip-req-build-
lv0gh902/lib/nsx-vmc-policy-python-
sdk/nsx_vmc_policy_python_sdk-4.0.0.0.0-py2.py3-
none-any.whl
pycparser==2.21
pyOpenSSL==22.0.0
pyvmomi==7.0.3
requests==2.28.1
six==1.16.0
urllib3==1.26.12
vapi-client-bindings @ file://localhost//tmp/pip-
req-build-lv0gh902/lib/vapi-client-
bindings/vapi_client_bindings-3.9.0-py2.py3-none-
any.whl
vapi-common-client @ file://localhost//tmp/pip-
req-build-lv0gh902/lib/vapi-common-
client/vapi_common_client-2.34.0-py2.py3-none-
any.whl
vapi-runtime @ file://localhost//tmp/pip-req-
build-lv0gh902/lib/vapi-runtime/vapi_runtime-
2.34.0-py2.py3-none-any.whl
vmc-client-bindings @ file://localhost//tmp/pip-
req-build-lv0gh902/lib/vmc-client-
bindings/vmc_client_bindings-1.60.0-py2.py3-none-
any.whl
vmc-draas-client-bindings @
file://localhost//tmp/pip-req-build-
lv0gh902/lib/vmc-draas-client-
bindings/vmc_draas_client_bindings-1.19.0-py2.py3-
none-any.whl
vSphere-Automation-SDK==1.78.0
Code
Let me show you how to reproduce, troubleshoot, and ix the Ansible
fatal error ModuleNotFoundError: No module named
'pyVim'".
In this example, execute the code in an Ansible controller without
the pyVmomi Python SDK library installed. I’ll demonstrate this
behavior using the vm_info.yml Ansible Playbook that gathers the
myvm VMware virtual machine details from the VMware infrastructure
and prints them on screen. The irst execution leads to an (expected)
failure because the pyVmomi Python SDK library is missing. Then you
can install the necessary Python dependency using the PIP tool. The
second execution of the same code returns a successful execution.
vm_info.yml
---
- name: info vm demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: get VM info
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ vcenter_datacenter }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
register: detailed_vm_info
localhost
---
vcenter_hostname: "vm-ware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
The fatal error message gives you the full path of the system-wise
running Python interpreter (/usr/libexec/platform-python
speci ically). So, you need to perform the installation of pyVmomi in the
currently running user or system wide. The ix requires you to install
the missing pyVmomi Python library in the right place in your system.
Sometimes the root cause of the failure is the permission bits for
newly created iles. Some high-security systems have strict non-
standard settings via a global /etc/profile ile or .bashrc inside
the user's home directory.
The standard POSIX utility umask allows you to set the octal value
to set the permission for new iles.
The Ansible Engineer Team highly recommends that you run umask
0022 before installing any packages to the virtual environment.
The default umask 0022 result into a newly created directory
called permissions is 755 and ile permissions is 644.
The two options to install the pyVmomi Python library are
Install pyVmomi system wide.
Code
Let me show you how to reproduce, troubleshoot, and ix the Ansible
error Unknown error while connecting to vCenter or
ESXi API [Errno -2] Name or service not known.
In this example, I’ll introduce a very simple and common typo error
in the hostname: vm-ware.example.com instead of the correct
vmware.example.com of the VMware infrastructure. I always
suggest using your browser to try to access the URL as a irst test. You
can easily test this host by copying and pasting the address and trying
to reach the VMware vSphere web interface. If your browser returns a
“host unavailable” message, it becomes clear that the hostname was
misspelled. The issue may be more complex depending on your
network topology and may require analyzing the network traf ic
between the Ansible controller and the target machine. Please verify
the irewall, VPN, and other rules as well. Let me share with you the
example with a misspelled hostname, vm-ware.example.com
instead of the correct vmware.example.com of the VMware
infrastructure, just a simple human typo mistake.
The vm_info.yml Ansible Playbook simply gathers the VMware
virtual machine details from the VMware infrastructure and prints
them on screen. The variables used inside the Ansible Playbook are
de ined in the vars.yml ile.
vm_info.yml
---
- name: info vm demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: get VM info
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ vcenter_datacenter }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
register: detailed_vm_info
localhost
---
vcenter_hostname: "vm-ware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
The fatal error message gives you the full hostname and port vm-
ware.example.com:443 user by Ansible. Just copy and paste the
vm-ware.example.com hostname and port HTTPS (443) to spot the
misspelling human error.
The ix is very easy and requires you to only modify the
vcenter_hostname variable in the vars.yml ile with the right
hostname.
vars.yml
vcenter_hostname: "vmware.example.com"
Code
Suppose your VMware infrastructure uses a self-signed certi icate such
as the one that came out of the box with the VMware. Let me show you
what happens if you don’t specify the validate_certs parameter
for the Ansible module. The validate_certs boolean parameter
defaults to true so Ansible will perform the certi icate SSL validation.
Let me demonstrate this behavior using the vm_info.yml Ansible
Playbook that gathers the myvm VMware virtual machine details from
the VMware infrastructure and prints them on screen. The irst
execution leads to an (expected) failure because the
validate_certs boolean parameter is missing, so it defaults to
true. Then you correct the Ansible Playbook to include the
validate_certs boolean parameter with the false value to
disable the certi icate SSL validation. The second execution of the code
returns a successful execution.
Error Code
vm_info_error.yml
---
- name: info vm demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: get VM info
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ vcenter_datacenter }}"
name: "{{ vm_name }}"
register: detailed_vm_info
- name: print VM info
ansible.builtin.debug:
var: detailed_vm_info
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
localhost
Fixed Code
It’s possible to avoid SSL certi icate validation by setting the parameter
validate_certs. For a self-signed certi icate, you need to disable
the SSL certi icate validation. However, I strongly recommend creating a
custom chain of trust or using a valid SSL certi icate. The only change is
the addition of the validate_certs parameter to the
vmware_guest_info Ansible module using a
vcenter_validate_certs variable de ined in the vars.yml ile.
vm_info_fix.yml
---
- name: info vm demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: get VM info
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ vcenter_datacenter }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
register: detailed_vm_info
- name: print VM info
ansible.builtin.debug:
var: detailed_vm_info
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vcenter_validate_certs: false
vm_name: "myvm"
Links
community.vmware.vmware_guest,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_module.xhtml
Code
Here’s the code to create a virtual machine named myvm with the
following resources (see Figure 3-1):
1 CPU
1GB of RAM
10GB of thin-provisioned storage in the datastore named Datastore-1
network card named VM Network of type vmxnet3
create_vm.yml
---
- name: create vm demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: create VM folder
vcenter_folder:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
datacenter_name: "{{ vcenter_datacenter
}}"
folder_name: "{{
vcenter_destination_folder }}"
folder_type: vm
state: present
- name: create VM
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
datacenter: "{{ vcenter_datacenter }}"
name: "{{ vm_name }}"
folder: "{{ vcenter_destination_folder }}"
state: "{{ vm_state }}"
guest_id: "{{ vm_guestid }}"
cluster: "{{ vcenter_cluster }}"
disk:
- size_gb: "{{ vm_disk_gb }}"
type: "{{ vm_disk_type }}"
datastore: "{{ vm_disk_datastore }}"
hardware:
memory_mb: "{{ vm_hw_ram_mb }}"
num_cpus: "{{ vm_hw_cpu_n }}"
scsi: "{{ vm_hw_scsi }}"
networks:
- name: "{{ vm_net_name }}"
device_name: "{{ vm_net_type }}"
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vcenter_cluster: "Development"
vm_name: "myvm"
vm_guestid: "centos64Guest"
vm_disk_gb: 10
vm_disk_type: "thin"
vm_disk_datastore: "Datastore-1"
vm_hw_ram_mb: 1024
vm_hw_cpu_n: 1
vm_hw_scsi: "paravirtual"
vm_net_name: "VM Network"
vm_net_type: "vmxnet3"
vcenter_destination_folder: "myvm"
vm_state: "poweroff"
After the execution of the code, you expect the following result in
your VMware vSphere client user interface. See Figure 3-1.
Figure 3-1 VMware virtual machine created with Ansible
Links
community.vmware.vmware_guest,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_module.xhtml
Code
I’m going to show you how to deploy a virtual machine named myvm
from a template mytemplate without any customization (see Figure
3-2). The Ansible Playbook includes the ile vars.yml for some
common variables for the VMware infrastructure and has two tasks for
creating a virtual machine folder in the datastore and one for deploying
the virtual machine from the template.
vm_deploy_template.yml
---
- name: deploy vm from template demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: create VM folder
vcenter_folder:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
datacenter_name: "{{ vcenter_datacenter
}}"
folder_name: "{{
vcenter_destination_folder }}"
folder_type: vm
state: present
- name: deploy VM from template
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
datacenter: "{{ vcenter_datacenter }}"
cluster: "{{ vcenter_cluster }}"
name: "{{ vm_name }}"
folder: "{{ vcenter_destination_folder }}"
template: "{{ vm_template }}"
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vcenter_cluster: "Development"
vm_name: "myvm"
vcenter_destination_folder: "myvm"
vm_state: "poweroff"
vm_template: "mytemplate"
localhost
After the execution of the code, you expect the following result in
your VMware vSphere client user interface. See Figure 3-2.
Figure 3-2 Deploying a VMware virtual machine from a template with Ansible
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
state string: present/powered-off/powered-on/reboot-
guest/restarted/shutdown-guest/suspended
force boolean: No/yes
answer string: A list of questions to answer, should one or more arise
while waiting for the task to be complete
The following parameters are useful in order to start a VMware
vSphere virtual machine using the module
vmware_guest_powerstate. First, you need to establish the
connection with VMware vSphere or VMware vCenter using a plethora
of self-explanatory parameters: hostname, port, username,
password, datacenter, and validate_certs. Once the
connection is successfully established, you can specify the desired
power state, in this case, powered-on. You can also force the power
state change using the force parameter (default: disabled). You can
also specify the reply to some answer that can arise while waiting for
the task to complete. Some common uses are to allow a CD-ROM to be
changed even if locked or to answer the question as to whether a VM
was copied or moved.
Links
community.vmware.vmware_guest_powerstate,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_powerstate_modul
e.xhtml
Code
I’m going to show you how to start the virtual machine named myvm
from the power state Powered Off to the power state Powered On using
an Ansible Playbook. The Ansible Playbook includes the ile vars.yml
for some common variables for the VMware infrastructure and has one
task for powering one of the virtual machine with the speci ied name
myvm. Under the hood, Ansible interacts with the VMware API via
Python libraries to execute the operation and verify the successful
startup of the virtual machine.
vm_start.yml
---
- name: start vm demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: power on VM
vmware_guest_powerstate:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
name: "{{ vm_name }}"
validate_certs: "{{ vcenter_validate_certs
}}"
state: powered-on
The vars.yml ile stores all the VMware infrastructure connection
parameters that may be shared among different Ansible Playbook iles.
vars.yml
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
localhost
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
state string - present/powered-off/powered-on/reboot-
guest/restarted/shutdown-guest/suspended
force boolean: No/yes
answer string: A list of questions to answer, should one or more arise
while waiting for the task to be complete
The following parameters are useful in order to start a VMware
vSphere virtual machine using the module
vmware_guest_powerstate. First, you need to establish a
connection with VMware vSphere or VMware vCenter using a plethora
of self-explanatory parameters: hostname, port, username,
password, datacenter, and validate_certs. Once the
connection is successfully established, you can specify the desired
power state, in this case, shutdown-guest to gracefully ask the guest
operating system to shut down or powered-off to turn off the virtual
machine guest. You can also force the power state to change using the
force parameter (default: disabled).
Links
community.vmware.vmware_guest_powerstate,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_powerstate_modul
e.xhtml
Code
Here’s how to get the virtual machine named myvm from the power
state Powered On to the power state Powered Off using an Ansible
Playbook (see Figure 3-5 for before the execution and Figure 3-6 for
after the execution). Let’s irst try the shutdown-guest operation to
gracefully ask the guest operating system to shut down and then
powered-off to forcefully turn off the virtual machine guest. The
Ansible Playbook includes the ile vars.yml for some common
variables for the VMware infrastructure and has one task for powering
one of the virtual machine with the speci ied name myvm. Under the
hood, Ansible interacts with the VMware API via Python libraries to
execute the operation and verify the successful startup of the virtual
machine. A timeout of 120 seconds (2 minutes) is set for the guest
shutdown task; the default of the vmware_guest_powerstate
module returns immediately (value 0) after sending the shutdown
signal.
vm_stop.yml
---
- name: stop vm demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: guest shutdown
vmware_guest_powerstate:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
state: shutdown-guest
state_change_timeout: 120
register: shutdown
ignore_errors: true
- name: poweroff
vmware_guest_powerstate:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
state: powered-off
when: shutdown.failed
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
localhost
You can see the result of the shutdown of the VMware virtual
machine in the VMware vSphere web user interface in Figures 3-5 and
3-6.
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
state string - present/absent/revert/remove_all
remove_children boolean: No/yes
snapshot_name string description string: Name/description of the
virtual machine to work with
memory_dump boolean: No/yes because memory snapshots take
time and resources
The following parameters are useful in order to take a VMware
virtual machine snapshot using the module
vmware_guest_snapshot. First, you must establish the connection
with VMware vSphere or VMware vCenter using a plethora of self-
explanatory parameters: hostname, port, username, password,
datacenter, and validate_certs. Once the connection is
successfully established, you can specify the desired snapshot state, in
this case, present to take a snapshot. You can also revert or
remove a snapshot with the same Ansible module. If you want to
remove a snapshot, you can also remove all the dependent snapshots
using the parameter remove_children. It’s a good practice to set the
name and description of the snapshot using the the snapshot_name
and description parameters. An advanced practice is to create the
memory dump of the virtual machines. Please note that memory
snapshots take time and resources will take a longer time to create. By
default, memory dumps are disabled but you can enable them using the
memory_dump parameter.
Links
community.vmware.vmware_guest_snapshot,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_snapshot_module.
xhtml
Code
Here’s how to take a snapshot named Ansible Managed Snapshot of the
virtual machine named myvm using an Ansible Playbook (see Figure 3-7
for before the execution and Figure 3-8 for after the execution). Let me
encourage you to set a name and description to easily ind it in your
VMware vCenter. The Ansible Playbook includes the ile vars.yml for
common variables for the VMware infrastructure and has one task for
powering one of the virtual machine with the speci ied name myvm.
Under the hood, Ansible interacts with the VMware API via Python
libraries to execute the operation and verify the successful startup of
the virtual machine.
vm_snapshot_create.yml
---
- name: vm snapshot demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: create a snapshot
vmware_guest_snapshot:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ vcenter_datacenter }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
state: present
snapshot_name: "Ansible Managed Snapshot"
folder: "{{ vm_folder }}"
description: "This snapshot is created by
Ansible Playbook"
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
vm_folder: "myvm"
localhost
Figure 3-7 Before taking a VMware virtual machine snapshot with Ansible
Figure 3-8 After taking a VMware virtual machine snapshot with Ansible
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
state string - present/absent/revert/remove_all
remove_children boolean: No/yes
snapshot_name string description string: Name/description of the
virtual machine to work with
The following parameters are useful in order to take a VMware
virtual machine snapshot using the module
vmware_guest_snapshot. First, you must establish the connection
with VMware vSphere or VMware vCenter using a plethora of self-
explanatory parameters: hostname, username, password,
datacenter, and validate_certs. Once the connection is
successfully established, you can specify the desired snapshot state, in
this case, absent to delete a snapshot. You can also manage a snapshot
with the same Ansible module. If you want to remove a snapshot, you
can also remove all the dependent snapshots using the parameter
remove_children. You need to specify the exact snapshot name that
you would like to remove in the snapshot_name parameter.
Links
community.vmware.vmware_guest_snapshot,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_snapshot_module.
xhtml
Code
I’m going to show you how to delete a snapshot named Ansible
Managed Snapshot of the virtual machine named myvm using an
Ansible Playbook (see Figure 3-9 for before the execution and Figure 3-
10 for after the execution). The Ansible Playbook includes the ile
vars.yml for common variables for the VMware infrastructure and
has one task for powering one of the virtual machine with the speci ied
name myvm. Under the hood, Ansible interacts with the VMware API via
Python libraries to execute the operation and verify the successful
startup of the virtual machine.
vm_snapshot_remove.yml
---
- name: vm snapshot demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: remove snapshot
vmware_guest_snapshot:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ vcenter_datacenter }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
folder: "{{ vm_folder }}"
snapshot_name: "Ansible Managed Snapshot"
state: absent
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
vm_folder: "myvm"
localhost
You can see the result of the delete operation for the VMware
snapshot in the VMware virtual machine in the VMware vSphere web
user interface in Figures 3-9 and 3-10.
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
datacenter string: The datacenter name to which the virtual machine
belongs to
scsi_controller/unit_number/scsi_type string: SCSI controller details
size/size_kb/size_mb/size_gb/size_tb string: Disk storage size
disk_mode string —
persistent/independent_persistent/independent_nonpersistent
The following parameters are useful in order to add a disk to
VMware virtual machine using the module vmware_guest_disk.
First, you must establish the connection with VMware vSphere or
VMware vCenter using a plethora of self-explanatory parameters:
hostname, username, password, datacenter, and
validate_certs.
Once the connection is successfully established, you can specify the
desired disk con iguration: in this case, it’s to add a new disk to the
virtual machine. The mandatory parameters are only datacenter and
unit_number.
The datacenter parameter speci ies which datacenter name the
virtual machine belongs to, for resource allocations.
The disk must be connected to a SCSI controller inside the virtual
machine, so you should specify all the small details like
scsi_controller, unit_number, and scsi_type.
According to SCSI standards, valid SCSI controller numbers are from
0 to 29, and unit numbers are from 0 to 15.
You may be interested in taking a deep dive into performance
analysis to properly adjust these parameters.
You can specify the disk size via various parameters according to
the needed size unit: kb, MB, GB, TB, etc.
One of the most important parameters is the disk_mode (defaults
to persistent mode). Other options are
independent_persistent and independent_nonpersistent.
Links
community.vmware.vmware_guest_disk,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_disk_module.xhtm
l
Code
I’m going to show you how to add a 1GB disk to a virtual machine
named myvm using an Ansible Playbook in the SCSI controller number 1
and unit number 1 (see Figure 3-11 for before the execution and Figure
3-12 for after the execution). The Ansible Playbook includes the ile
vars.yml for some common variables for the VMware infrastructure
and has one task for adding a disk to the virtual machine with the
speci ied name myvm. Under the hood, Ansible interacts with VMware
API via Python libraries to execute the operation and verify the
successful startup of the virtual machine.
vm_add_disk.yml
---
- name: vm disk demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: add disk to vm
vmware_guest_disk:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
datacenter: "{{ vcenter_datacenter }}"
name: "{{ vm_name }}"
disk:
- size_gb: "{{ vm_disk_gb }}"
type: "{{ vm_disk_type }}"
datastore: "{{ vm_disk_datastore }}"
state: present
scsi_controller: "{{
vm_disk_scsi_controller }}"
unit_number: "{{ vm_disk_scsi_unit }}"
scsi_type: "{{ vm_disk_scsi_type }}"
disk_mode: "{{ vm_disk_mode }}"
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
vm_disk_gb: 1
vm_disk_type: "thin"
vm_disk_datastore: "datastore"
vm_disk_scsi_controller: 1
vm_disk_scsi_unit: 1
vm_disk_scsi_type: 'paravirtual'
vm_disk_mode: 'persistent'
localhost
You can see the result of the addition of the virtual disk in the
VMware virtual machine in the VMware vSphere web user interface in
Figures 3-11 and 3-12.
Figure 3-11 Before adding a new hard disk to a VMware virtual machine
Figure 3-12 After adding a new hard disk to a VMware virtual machine
Expanding a Virtual Disk in a VMware Virtual Machine
You can automate the expansion of a hard disk to a VMware virtual
machine guest using an Ansible Playbook and the
vmware_guest_disk module. This is useful for managing storage on
a virtual machine, one of the tedious activities for a VMware
infrastructure administrator. You are probably familiar with the manual
way, which requires access to the vSphere client or web user interface
and operating with the forms. This manual operation is human
dependent so it is error prone. What happens if you extend the space to
the wrong virtual machine? VMware doesn’t allow you to shrink the
virtual disk, so the only option is to recover the virtual machine from a
backup (if you have one).
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
datacenter string: The datacenter name to which the virtual machine
belongs to
scsi_controller/unit_number/scsi_type string: SCSI controller details
size/size_kb/size_mb/size_gb/size_tb string: Disk storage size
disk_mode string —
persistent/independent_persistent/independent_nonpersistent
The following parameters are useful in order to expand a virtual
disk in a VMware virtual machine using the module
vmware_guest_disk. First, you must establish the connection with
VMware vSphere or VMware vCenter using a plethora of self-
explanatory parameters: hostname, username, password,
datacenter, and validate_certs. Once the connection is
successfully established, you can specify the desired disk con iguration.
In this expansion, a disk is connected to a virtual machine. The
mandatory parameters are only datacenter and unit_number. The
datacenter parameter speci ies which datacenter name the virtual
machine belongs to, for resource allocations. The disk must be
connected to a SCSI controller inside the virtual machine, so you should
specify all the small details like scsi_controller, unit_number,
and scsi_type. According to SCSI standards, valid SCSI controller
numbers are from 0 to 29, and unit numbers are from 0 to 15. You may
be interested in a deep dive into some performance analysis to properly
adjust these parameters. You can specify the disk size via various
parameters according to the needed size unit: kb, MB, GB, TB, etc. One
of the most important parameters is the disk_mode (defaults to
persistent mode). Other options are independent_persistent
and independent_nonpersistent.
Links
community.vmware.vmware_guest_disk,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_disk_module.xhtm
l
Code
I’m going to show you how to expand the size of an additional disk
connected to a virtual machine named myvm using an Ansible Playbook.
The disk is connected to SCSI controller number 1 and has unit number
1 (see Figure 3-13 for before the execution and Figure 3-14 for after the
execution). The virtual hard disk had a size of 1GB and you want to
expand it to 2GB. The Ansible Playbook includes the ile vars.yml for
common variables for the VMware infrastructure and has one task for
expanding the virtual hard disk of the virtual machine with the
speci ied name myvm. Under the hood, Ansible interacts with the
VMware API via Python libraries to execute the operation and verify the
successful startup of the virtual machine.
vm_disk_expand.yml
---
- name: vm disk demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: expand disk in vm
vmware_guest_disk:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
datacenter: "{{ vcenter_datacenter }}"
name: "{{ vm_name }}"
disk:
- size_gb: "{{ vm_disk_gb }}"
type: "{{ vm_disk_type }}"
datastore: "{{ vm_disk_datastore }}"
state: present
scsi_controller: "{{
vm_disk_scsi_controller }}"
unit_number: "{{ vm_disk_scsi_unit }}"
scsi_type: "{{ vm_disk_scsi_type }}"
disk_mode: "{{ vm_disk_mode }}"
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
vm_disk_gb: 2
vm_disk_type: "thin"
vm_disk_datastore: "datastore"
vm_disk_scsi_controller: 1
vm_disk_scsi_unit: 1
vm_disk_scsi_type: 'paravirtual'
vm_disk_mode: 'persistent'
localhost
You can see the result of the expansion of the virtual disk in the
VMware virtual machine in the VMware vSphere web user interface in
Figures 3-13 and 3-14.
Figure 3-13 Before expanding a virtual disk in a VMware virtual machine
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
cluster_name string: Name of the cluster to which the ESXi host
belongs
esxi_hostname string: ESXi hostname to gather information from.
The following parameters are useful in order to gather information
about all VMware ESX/ESXi hosts in the given cluster using the module
vmware_host_config_info. First, you must establish the
connection with VMware vSphere or VMware vCenter using a plethora
of self-explanatory parameters: hostname, port, username,
password, datacenter, and validate_certs.
Once the connection is successfully established, you can specify the
full esxi_hostname, the ESX/ESXi hostname, or list all the hostnames
in the current cluster cluster_name.
Links
community.vmware.vmware_host_config_info,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_cluster_info_module.xh
tml
Code
I’m going to show you how to gather con iguration information on all
the ESX/ESXi hosts in the current VMware production cluster using
an Ansible Playbook. The Ansible Playbook includes the ile vars.yml
for some common variables for the VMware infrastructure and has two
tasks. The irst task acquires information from the VMware
production cluster and saves the result in the cluster_info
Ansible variable. The second task prints onscreen the values of the
cluster_info Ansible variable. In a real-world scenario, you can also
perform operations based on the status of the cluster_info Ansible
variable. Under the hood, Ansible interacts with the VMware API via
Python libraries to execute the operation and verify the successful
startup of the virtual machine.
host_info_cluser.yml
---
- name: host in cluster info demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: Gather info about all ESXi Host in the
given Cluster
community.vmware.vmware_host_config_info:
hostname: '{{ vcenter_hostname }}'
username: '{{ vcenter_username }}'
password: '{{ vcenter_password }}'
validate_certs: "{{ vcenter_validate_certs
}}"
cluster_name: "{{ cluster_name }}"
register: cluster_info
- name: print cluster info
ansible.builtin.debug:
var: cluster_info
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
cluster_name: "production"
localhost
Links
community.vmware.vmware_guest_info,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_info_module.xhtm
l
Code
I’m going to show you how to gather information about a speci ic myvm
VMware virtual machine and select the UUID using an Ansible Playbook
(see Figure 3-15). The Ansible Playbook includes the ile vars.yml for
common variables for the VMware Infrastructure and has two tasks.
The irst task acquires information from the myvm VMware virtual
machine and saves the result in the detailed_vm_info Ansible
variable. The second task prints onscreen the values of the
detailed_vm_info Ansible variable. Speci ically, the UUID value is
stored inside the
detailed_vm_info.instance.hw_product_uuid parameter.
Under the hood, Ansible interacts with the VMware API via Python
libraries to execute the operation and verify the successful startup of
the virtual machine.
vm_uuid.yml
---
- name: vm UUID demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: Get VM UUID
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ vcenter_datacenter }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
register: detailed_vm_info
- name: print VM UUID
ansible.builtin.debug:
var:
detailed_vm_info.instance.hw_product_uuid
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
The Ansible inventory is only the localhost because you’re
executing the Ansible automation on the Ansible controller.
Inventory
localhost
You can see the result of gathering the UUID of a VMware virtual
machine in the VMware vSphere web user interface. You can ind this
information in the VMware vSphere web console under “Hosts and
Clusters” or “VMs and Templates.” The list view shows a lot of
information such as state, status, provisioned and used space, host CPU,
and memory. If the list doesn’t show the UUID columns, click the gray
area of one column and select Show/Hide Columns and enable UUID
from the pop-up list. See Figure 3-15.
Figure 3-15 vmware_guest_info after execution
Ansible vmware_vm_inventory
community.vmware.vmware_vm_inventory
The Ansible Inventory Plugin queries your VMware infrastructure
via the VMware APIs and returns to Ansible a list of virtual machines
that can be used as target nodes. The purpose is to get virtual machines
as inventory hosts from the VMware environment. In this way, you can
execute your Ansible automation to all your virtual machines, for
example. Please note that the inventory YAML con iguration ile MUST
end with vmware.yml, vmware.yaml,
vmware_vm_inventory.yml, or vmware_vm_inventory.yaml
ile names. The full name is
community.vmware.vmware_vm_inventory, which means that it
is part of the collection of modules that interact with VMware and is
community supported.
Python requirements
As with the community.vmware collection, this plugin requires
the pyVmomi Python library installed in your Ansible controller. For
advanced parameters such as the tag feature, you must install the
VMware vSphere Automation SDK for Python library.
Links
community.vmware.vmware_vm_inventory,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_vm_inventory_inventory
.xhtml
Code
In this example, you are going to list all the available virtual machines
and speci ically the myvm test machine created earlier in this book.
The irst step is to speci ically enable the vmware_vm_inventory
Ansible Inventory Plugin in your con iguration ile. You can enable it via
ansible.cfg in the current path or system-wide via
/etc/ansible/ansible.cfg. Simply add the
vmware_vm_inventory plugin name inside the key
enable_plugins in the inventory section.
ansible.cfg
[inventory]
enable_plugins = vmware_vm_inventory
The second step is to create the data source with your VMware
infrastructure connection parameters. The following is a simple YAML
data source to list all the virtual machines that connect to
vmware.example.com VMware vSphere with a given username and
password and to disable the SSL certi icate validation (for self-signed
certi icates). It enables group mapping of the results by VMware virtual
machines. It disables tags associated with the VMware virtual machines
(requires vSphere Automation SDK Python library).
inventory.vmware.yml
plugin: vmware_vm_inventory
strict: False
hostname: vmware.example.com
username: username@vsphere.local
password: MySecretPassword123
validate_certs: False
with_tags: False
groups:
VMs: True
The default view output shows all the available VMware properties
associated with the VMware virtual machine. Specifying the
properties parameter in the YAML data source, you can display only
the ones needed, such as name, config.cpuHotAddEnabled,
config.cpuHotRemoveEnabled, config.instanceUuid,
config.hardware.numCPU, config.template,
config.name, config.uuid, guest.hostName,
guest.ipAddress, guest.guestId, guest.guestState,
runtime.maxMemoryUsage, customValue,
summary.runtime.powerState, and config.guestId. Here is
an example of the properties parameter to display only the power
state and the name of the virtual machine:
properties:
- 'runtime.powerState'
- 'config.name'
Another useful parameter is filters, which allows you to search
only for virtual machines in a particular state. Here is an example of the
filters parameter to search only the virtual machine in a powered-
on state:
filters:
- runtime.powerState == "poweredOn"
filters:
- config.guestId == "rhel7_64Guest"
@all:
|--@VMs:
| |--myvm_42254893-3793-0e4f-9f61-7c37d244c2a8
|--@centos64Guest:
| |--myvm_42254893-3793-0e4f-9f61-7c37d244c2a8
|--@poweredOff:
| |--myvm_42254893-3793-0e4f-9f61-7c37d244c2a8
$ ansible-playbook -i inventory.vmware.yml
playbook.yml
Code
I’m going to show you how to gather information about the myvm
VMware virtual machine and select the running host using an Ansible
Playbook. The Ansible Playbook includes the ile vars.yml for some
common variables for the VMware infrastructure and has two tasks.
The irst task acquires information from the myvm VMware virtual
machine and saves the result in the detailed_vm_info Ansible
variable. The second task prints onscreen the values of the
detailed_vm_info Ansible variable. Speci ically, the running host
value is stored inside the
detailed_vm_info.instance.hw_esxi_host return value.
Under the hood, Ansible interacts with the VMware API via Python
libraries to execute the operation and verify the successful startup of
the virtual machine.
vm_running_host.yml
---
- name: vm running host demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: Get VM info
vmware_guest_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
datacenter: "{{ vcenter_datacenter }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
register: detailed_vm_info
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
localhost
Figure 3-16 Getting a VMware virtual machine running host via the VMware vSphere web UI
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
name string: Datastore name
The following parameters are useful in order to get the VMware
vSphere datastore status using the module
vmware_datastore_info. First, you must establish the connection
with VMware vSphere or VMware vCenter using a plethora of self-
explanatory parameters: hostname, port, username, password,
datacenter, and validate_certs. Once the connection is
successfully established, you can specify the datastore name to obtain
all information about it.
Links
community.vmware.vmware_datastore_info,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_datastore_info_module.
xhtml
Code
I’m going to show you how to gather information about a speci ic
VMware vSphere datastore using an Ansible Playbook (see Figure 3-
17). The Ansible Playbook includes the ile vars.yml for some
common variables for the VMware infrastructure and has two tasks.
The irst task acquires information from the Datastore VMware vSphere
datastore and saves the result in the datastore_info Ansible
variable. The second task prints onscreen the values of the
datastore_info Ansible variable. Under the hood, Ansible interacts
with the VMware API via Python libraries to execute the operation and
verify the successful startup of the virtual machine.
datastore_info.yml
---
- name: datastore info demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: datastore info
vmware_datastore_info:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
datacenter_name: "{{ vcenter_datacenter
}}"
name: "{{ vcenter_datastore }}"
register: datastore_info
- name: print datastore info
ansible.builtin.debug:
var: datastore_info
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vcenter_datastore: "Datastore"
localhost
You can see the result of the gathering of the VMware vSphere
datastore status and information in the VMware vSphere web user
interface in Figure 3-17. You can ind this information in the VMware
vSphere web console, in the “Storage” area.
Figure 3-17 Getting VMware datastore status in the VMware vSphere web UI
Uploading a File to the VMware Datastore
You can automate the uploading of a ile in the VMware vSphere
datastore using an Ansible Playbook and the vsphere_copy module
(see Figure 3-18 for before the execution and Figure 3-19 for after the
execution). The VMware datastore is the VMware storage area where
virtual machines and VMware resources are shared between VMware
hosts. The VMware infrastructure administrator uploads ISO image iles
before creating a new VMware virtual machine.
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
datastore string: Datastore name
src string: Source ile name
path string: Destination ile name
The following parameters are useful in order to copy a ile to a
VMware vSphere datastore status using the module vsphere_copy.
First, you must establish the connection with VMware vSphere or
VMware vCenter using a plethora of self-explanatory parameters:
hostname, port, username, password, datacenter, and
validate_certs. Once the connection is successfully established,
you can specify the source src ile in the Ansible controller ilesystem,
the target VMware datastore datastore, and the target path
datastore ilename.
Links
community.vmware.vsphere_copy,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vsphere_copy_module.xhtml
Code
I’m going to show you how to upload the ile ubuntu-22.04-live-
server-amd64.iso ISO image to the Datastore VMware vSphere
datastore using an Ansible Playbook. The source and destination paths
are speci ied as variables mysrc and mydest, and you can customize
them in the Ansible Playbook or use as extra variables via the command
line. The Ansible Playbook includes the ile vars.yml for some
common variables for the VMware infrastructure and has one task.
Under the hood, Ansible interacts with the VMware API via Python
libraries to execute the operation and verify the successful startup of
the virtual machine.
datastore_info.yml
---
- name: datastore copy demo
hosts: localhost
gather_facts: false
vars:
mysrc: "iso/ubuntu-22.04-live-server-
amd64.iso"
mydest: "ISO/ubuntu-22.04-live-server-
amd64.iso"
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: copy file to datastore
vsphere_copy:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
datacenter: "{{ vcenter_datacenter }}"
datastore: "{{ vcenter_datastore }}"
src: "{{ mysrc }}"
path: "{{ mydest }}"
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vcenter_datastore: "Datastore"
localhost
You can see the result of the uploading of the ile to the VMware
vSphere datastore in the VMware vSphere web user interface. You can
ind this information in the VMware vSphere web console, in the
“Storage” area. You can browse the datastore path via the “Files” area.
See Figure 3-18.
10 iles before upload are already present in the ISO folder of the
Datastore datastore.
Figure 3-18 Before uploading a ile to the VMware datastore
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
name string: Virtual machine name
The following parameters are useful in order to get the VMware
guest tools status using the module vmware_guest_tools_info.
First, you must establish the connection with VMware vSphere or
VMware vCenter using a plethora of self-explanatory parameters:
hostname, port, username, password, datacenter, and
validate_certs. Once the connection is successfully established,
you can specify the VMware virtual machine name to obtain all
information about the VMware guest tools on it.
Links
community.vmware.vmware_guest_tools_info,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_tools_info_modul
e.xhtml
Code
I’m going to show you how to gather information about a speci ic myvm
VMware virtual machine and select the running host using an Ansible
Playbook (see Figure 3-20). The Ansible Playbook includes the ile
vars.yml for some common variables for the VMware infrastructure
and has two tasks. The irst task acquires information from the myvm
VMware virtual machine and saves the result in the vmtools_info
Ansible variable. The second task prints onscreen the values of the
vmtools_info Ansible variable using the debug Ansible module.
Under the hood, Ansible interacts with the VMware API via Python
libraries to execute the operation and verify the successful startup of
the virtual machine.
vm_guest_tools_info.yml
---
- name: vmware guest tools info demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: guest tools info
vmware_guest:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
datacenter: "{{ vcenter_datacenter }}"
name: "{{ vm_name }}"
register: vmtools_info
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
localhost
In this case, the VMware virtual machine myvm VMware guest tools
status is
VMware guest tools installed ("vm_tools_version_status":
"toolsOk")
VMware guest tools running ("vm_tools_running_status":
"guestToolsRunning")
VMware guest tools type OpenVM
("vm_tools_install_type":
"guestToolsTypeOpenVMTools")
VMware guest tools upgrade policy manual
("vm_tools_upgrade_policy": "manual")
A successful execution output of virtual machine without VMware
guest tools output includes
Target host: localhost
Command result: ok=3 changed=0
Return value:
In this case, the VMware virtual machine myvm VMware guest tools
status is
VMware guest tools NOT installed
("vm_tools_version_status":
"guestToolsNotInstalled")
VMware guest tools NOT running
("vm_tools_running_status":
"guestToolsNotRunning")
VMware guest tools upgrade policy manual
("vm_tools_upgrade_policy": "manual")
You can see the result of the gathering of the status of the VMware
guest tools of a speci ic virtual machine in the VMware vSphere web
user interface in the “VMware Tools” ield on the Summary page. See
Figure 3-20.
Figure 3-20 VMware guest tools status in VMware vSphere web UI
Links
community.vmware.vmware_guest_tools_upgrade,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_guest_tools_upgrade_mo
dule.xhtml
Code
I’m going to show you how to upgrade guest tools for the myvm VMware
virtual machine. The Ansible Playbook includes the ile vars.yml for
common variables for the VMware infrastructure and has ive tasks.
The irst task ensures the myvm VMware virtual machine is powered on.
The second task acquires the UUID of the myvm VMware virtual
machine and saves the result in the detailed_vm_info Ansible
variable. The third task executes the VMware guest tools upgrade
consuming the
detailed_vm_info.instance.hw_product_uuid Ansible
variable (see “Getting a VMware Virtual Machine UUID” section). The
fourth task obtains the updated VMware guest tools information and
saves it in the vmtools_info Ansible variable. The last task prints
onscreen the values of the vmtools_info Ansible variable using the
debug Ansible module. Under the hood, Ansible interacts with the
VMware API via Python libraries to execute the operation and verify the
successful startup of the virtual machine.
vm_guest_tools_upgrade.yml
---
- name: vmware guest tools upgrade demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: VM powered-on
vmware_guest_powerstate:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
state: powered-on
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
localhost
You can see the result of the upgrade of the VMware virtual machine
guest tools of a speci ic virtual machine in the VMware vSphere Web
user interface in the “VMware Tools” ield on the Summary page. See
Figures 3-21 and 3-22.
Figure 3-21 Before the VMware guest tools upgrade in the VMware vSphere web UI
Figure 3-22 After the VMware guest tools upgrade in the VMware vSphere web UI
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
destination_host string: Destination VMware host
destination_datastore string: Destination VMware datastore
destination_datacenter string: Destination VMware datacenter
destination_cluster string: Destination VMware cluster
destination_resourcepool string: Destination VMware resource pool
destination_datastore_cluster string: Destination VMware datastore
cluster (storage pod)
The following parameters are useful in order to live migrate a
VMware virtual machine using vMotion using the module
vmware_vmotion. First, you must establish the connection with
VMware vSphere or VMware vCenter using a plethora of self-
explanatory parameters: hostname, port, username, password,
datacenter, and validate_certs.
Once the connection is successfully established, you can specify if
you want only to change the VMware host destination_host
(VMware host vMotion) or also change the storage with
destination_datastore (VMware storage vMotion). More
complex scenarios can be speci ied using
destination_datacenter, destination_cluster,
destination_resourcepool, and
destination_datastore_cluster.
Links
community.vmware.vmware_vmotion,
https://docs.ansible.com/ansible/latest/collectio
ns/community/vmware/vmware_vmotion_module.xhtml
Code
I’m going to show you how to move the VMware virtual machine myvm
from the host host1.vmware.example.com to the host
host2.vmware.example.com using an Ansible Playbook (see
Figure 3-23 for before the execution and Figure 3-24 for after the
execution). The Ansible Playbook includes the ile vars.yml for
common variables for the VMware Infrastructure and has two tasks.
The irst task performs the moving operation on the myvm VMware
virtual machine and saves the result in the vm_info Ansible variable.
The second task prints onscreen the values of the
vm_info.running_host Ansible variable. For more information,
refer to the section “Getting a VMware Virtual Machine Running Host”.
Under the hood, Ansible interacts with the VMware API via Python
libraries to execute the operation and verify the successful startup of
the virtual machine.
vm_vmotion.yml
---
- name: vm vmotion demo
hosts: localhost
gather_facts: false
vars:
destination_host: "host2.vmware.example.com"
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: VM vmotion
vmware_vmotion:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
vm_name: "{{ vm_name }}"
destination_host: "{{ destination_host }}"
register: vm_info
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
The Ansible inventory is only the localhost because you’re
executing the Ansible automation on the Ansible controller.
Inventory
localhost
After the execution of the code, you expect the following result in
your VMware vSphere client user interface in the “Host” ield on the
Summary page. See Figures 3-23 and 3-24.
Figure 3-23 Before moving the VMware virtual machine
Parameters
hostname string/port integer/username string/password
string/datacenter string/validate_certs boolean: Connection details
enter_bios_setup boolean: Enter in the BIOS setup
boot_order list: Boot devices order ( loppy, CD-ROM, Ethernet, disk)
The following parameters are useful in order to change the boot
devices order of a VMware virtual machine using the module
vmware_guest_boot_manager. First, you must establish the
connection with VMware vSphere or VMware vCenter using a plethora
of self-explanatory parameters: hostname, port, username,
password, datacenter, and validate_certs.
Once the connection is successfully established, you can enable
entering the BIOS setup using the enter_bios_setup boolean and
the boot devices order via the boot_order list, such as loppy, CD-
ROM, Ethernet, and disk. The system will try to boot from the order of
the speci ied devices.
Code
The Ansible Playbook includes the ile vars.yml for common
variables for the VMware Infrastructure and has one task. Under the
hood, Ansible interacts with the VMware API via Python libraries to
execute the operation and verify the successful startup of the virtual
machine.
vm_change_boot.yml
---
- name: vm change book demo
hosts: localhost
gather_facts: false
collections:
- community.vmware
pre_tasks:
- include_vars: vars.yml
tasks:
- name: VM change boot order
vmware_guest_boot_manager:
hostname: "{{ vcenter_hostname }}"
username: "{{ vcenter_username }}"
password: "{{ vcenter_password }}"
validate_certs: "{{ vcenter_validate_certs
}}"
name: "{{ vm_name }}"
enter_bios_setup: true
boot_order:
- cdrom
- disk
- ethernet
---
vcenter_hostname: "vmware.example.com"
vcenter_datacenter: "vmwaredatacenter"
vcenter_validate_certs: false
vcenter_username: "username@vsphere.local"
vcenter_password: "MySecretPassword123"
vm_name: "myvm"
localhost
Figure 3-26 After changing the boot order of the VMware virtual machine
Key Takeaways
This chapter moved deeply into VMware infrastructure automation and
providing some code nutshells and code sample snippets to use in your
day-to-day journey. It demysti ied the successful setup, installation, and
troubleshooting of Ansible for VMware.
Now you have a great overview of the powerful
community.vmware collection resources that you can use to
automate simple and complex VMware repetitive tasks that were
previously done manually via the VMware vSphere user interface.
In the next chapter, I thank you and recap how to move forward in
your Ansible automation journey.
© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2023
L. Berton, Ansible for VMware by Examples
https://doi.org/10.1007/978-1-4842-8879-5_4
4. Closing Remarks
Luca Berton1
Key Takeaways
This book is a cornerstone in your journey with the Ansible platform
for an information technology VMware infrastructure.
You now have a comprehensive overview of the state-of-the-art
Ansible platform, its strengths, and the programming language
constructs with some battle-tested code nutshells and command-line
command snippets.
The Ansible platform technology evolves every day, but the concepts
and main statements are stable and have long-lasting applications.
This knowledge will guide your journey to upskill yourself with
Ansible and implement VMware Infrastructure as Code (IaC) using
DevOps methodologies.
Index
A, B
Amazon Linux 2 (AWS EC2)
Ansible
agentless
application deployment
architecture
community driven
con iguration management
connect with managed nodes
declarative
DevOps
iles modules
handler
history
host in multiple groups
idempotent
infrastructure-as-Code
installation
create basic inventory
run ad-hoc commands with privilege escalation
run irst Ansible command
inventory
modules
modules and plugins
net tools modules
playbook
powerful IT automation solution
project
provisioning
Python
ranges of hosts
Red Hat
simple INI inventory
simple YAML inventory
six values
software package modules
system administrator tasks automation
system modules
variables
VMware errors
VMware infrastructure
Ansible Automation platform
Ansible Collection
Ansible community package
Ansible community.vmware VMware collection
code, inventory, and Playbook
community-supported collection
installing
modules and plugins
installing pyVmomi
Python pyVmomi library
Ansible conditional operations
ansible_facts
basic conditionals with “when
computers
Jinjia2 tests and ilters
loop
iterations
loop_with_items.y
with_* statement
Ansible controller
Ansible Controller Worker model
Ansible-core package
Ansible Core
Ansible dynamic inventory for VMware
code
community.vmware.vmware_vm_inventory
data source
plugin
Ansible Engine
Ansible Engine Software Collection (RHSCL)
Ansible execution environment
Ansible facts
facts_printall.yml execution
machine Ad-Hoc
machine Playbook
reference
Ansible fatal error
Ansible For VMware Playbook code
Ansible Galaxy
Ansible-inventory tool
Ansible Managed Snapshot
Ansible ping module
Ansible Playbook
Ansible role
Ansible Galaxy
Ansible Playbook development
collection
directory tree
playbook
Plugins
Ansible Tower
Ansible variables
array variables
array.yml execution
ilters and templates
group variables
host variables
not permitted variable names
registered variables
registeredvariables.yml execution
variableprint.yml
Ansible_version magic variable
Ansible VMware con iguration
failed to import the required Python library (pyVmomi)
Python virtual environment
unable to connect to vCenter
unknown error while connecting to vCenter
vmware.vmware_rest Ansible collection
Application deployment
Array variables
Array.yml Execution
C
CentOS 9 Stream
cluster_info Ansible variable
community.vmware collection
community.vmware.vmware_guest
Con iguration management
Control node
D
datastore_info Ansible variable
Datastores
Debian
Debian-like target system
detailed_vm_info Ansible variable
DevOps
Ansible
categories
toolchains
tools
E
Encryption
enter_bios_setup boolean
ESXi fatal error
F
facts_printall.yml execution
Fatal error message
Fedora 36
Filters and templates
G
Gathering VMware host information, cluster
Ansible Playbook
code
parameters
vmware_host_con ig_info module
Gathering VMware virtual machine UUID
Ansible Playbook
code
parameters
vmware_guest_info module
Getting VMware datastore status
Ansible Playbook
code
day-to-day operations
parameters
vmware_datastore_info module
Getting VMware virtual machine running host
Ansible inventory
Ansible playbook
detailed_vm_info Ansible variable
vars.yml ile stores
vmware_guest_info module
VMware vSphere web user interface
Group variables
Ansible inventory
inheriting variable values
localhost inventory
multiple inventory sources
H
helloworld_debug.yml
helloworld.yml
Host variables
Human-readable data serialization language
I, J, K
Idempotency
Infrastructure as Code (IaC)
Infrastructure automation tool
Install Ansible
Amazon Linux 2 (AWS EC2)
code
Extras Library
links
Ansible community vs. ansible-core packages
CentOS 9 Stream
AppStream repository
code
links
community.vmware collection via the requirements.yml File
Debian 11
APT
code
Fedora 36
code
links
macOS
code
PIP
code
OS-speci ic package manager
RHEL 9
demo
links
SUSE SLES 15 SP3
code
links
version of community.vmware
Windows
code
links
WSL
Inventory
Inventory_hostname magic variable
L
Localhost
Localhost Inventory
M, N
Machine Aad-Hhoc
Machine Playbook
macOS
Magic variables
Ansible_version
group_names
hostvars
internal variables, Ansible
Inventory_hostname magic
Memory_dump parameter
multipleplays.yml Playbook
myvm VMware guest tools status
myvm VMware virtual machine
O
Open source Infrastructure-as-Code (IaC)
OS-speci ic package manager
P, Q
Personal package archives (PPA)
pip tool
PIP package installer
PIP package manager
Playbook
Ansible Galaxy
Ansible modules
Ansible role
check option
debug day-to-day usage
helloworld.yml
idempotency
multipleplays.yml
order of execution
privilege_escalation.yml
YAML Syntax
playbook.yml
Plugins
privilege_escalation.yml
Provisioning
Python Package Manager (PIP)
Python SDK library
Python virtual environment
pyVmomi Python SDK library
R
Red Hat Enterprise Linux version 8 (RHEL)
code
RHSCL
Ubuntu 22.04 LTS
code, universe
PPA, code
YUM
Registered variables
Reporting
Requirements.txt ile
RHEL 9
Role-based access control (RBAC)
Role handlers
rollingupdate.yml ile
S, T
SCSI controller types
Self-explanatory parameters
Self-signed certi icate
Simple INI inventory
Simple YAML inventory
Software development kit (SDK)
SSL certi icate validation
SUSE Linux Enterprise Server (SLES) version 15 SP3
SUSE Package Hub repository
U
Ubuntu 22.04 LTS
Universally Unique Identi ier (UUID)
Upgrading VMware guest tools
Ansible Playbook
code
parameters
vmware_guest_tools_upgrade module
V
variableprint.yml
vars.yml iles
Vault
encrypted ile
create parameter
edit parameter
password change
view parameter
encryption
existing ile
decrypt parameter
encrypt parameter
vCenter infrastructure
vm_info.yml Ansible Playbook
vmtools_info Ansible variable
VMware Datastore, uploading ile
Ansible Playbook
code
parameters
vsphere_copy module
vmware.example.com VMware vSphere
VMware guest tools status gathering
code
parameters
vmware_guest_tools_info module
VMware infrastructure
VMware infrastructure automation
VMware vCenter
VMware vCenter server appliance (VCSA)
VMware Virtual Machine, adding hard disk
Ansible Playbook
code
guest myvm
operating systems
parameters
vmware_guest_disk module
VMware virtual machine, boot devices
Ansible Playbook
code
parameters
vmware_guest_boot_manager module
VMware virtual machine creation
Ansible Playbook
assigned resources
code
Ansible module vmware_guest
vSphere client
VMware virtual machine, deleting snapshot
Ansible Playbook
code
parameters
vmware_guest_snapshot module
vSphere client/web user interface
VMware virtual machine deployment
Ansible Playbook
code
Microsoft Windows operating system
template
vmware_guest module
Ansible module vmware_guest
VMware virtual machine, expanding virtual disk
Ansible Playbook
code
parameters
vmware_guest_disk module
vSphere client/web user interface
VMware virtual machine, live migration
Ansible Playbook
code
parameters
vmware_vmotion module
VMware virtual machine shutdown
Ansible Playbook
code
guest myvm
parameters
vmware_guest_powerstate module
vSphere client
VMware virtual machine startup
Ansible Playbook
code
infrastructure administrator
guest myvm
parameters
vmware_guest_powerstate module
VMware virtual machine, taking snapshots
Ansible Managed Snapshot
Ansible Playbook
code
parameters
vmware_guest_snapshot module
vmware_vm_inventory Ansible Inventory plugin
VMware vMotion
vmware.vmware_rest Ansible collection
alternative
Ansible VMware community
Ansible community.vmware
life cycle
pyVmomi
site documentation
VMware vSphere Automation SDK for Python library
VMware vSphere client
VMware vSphere datastore
VMware vSphere REST API interface
VMware vSphere web user interface
vsphere-automation-sdk-python library
W, X
Windows Subsystem for Linux (WSL)
Y, Z
YAML language
YAML syntax
YUM