Ansible Kodekloud
Ansible Kodekloud
As a systems engineer, IT administrator, or anyone working in IT, you're likely no stranger to repetitive tasks.
These can range from:
These tasks often involve executing numerous commands across numerous servers, all while maintaining a
specific sequence and managing reboots.
Ansible offers a powerful and accessible solution for IT automation. Here's why it stands out:
Easy to Learn: Ansible's simplicity makes it approachable for anyone in IT.
Powerful & Flexible: Capable of automating even the most complex deployments.
Efficient: Transforms complex scripting tasks into concise Ansible playbooks.
Imagine needing to restart multiple web and database servers in a specific order. Ansible can:
This entire process can be defined in an Ansible playbook and executed with a single command.
Consider deploying a complex infrastructure across public and private clouds. Ansible can:
Provision VMs: Create virtual machines on platforms like AWS and VMware.
Configure Applications: Set up and configure applications on provisioned VMs.
Manage Network Communication: Configure firewalls and network settings for seamless
communication.
Ansible's built-in modules streamline these operations, and its integration capabilities allow you to:
Fetch Data from CMDB: Dynamically target VMs based on information from your CMDB.
Trigger Automations: Integrate with tools like ServiceNow to initiate workflows upon approval.
The official Ansible documentation (docs.ansible.com) provides comprehensive information and numerous
playbook examples to get you started.
Key Takeaways
Ansible is a powerful, open-source IT automation tool. It simplifies the management and configuration of
infrastructure and applications.
Repetitive tasks: Ansible automates tasks like provisioning VMs, configuring servers, patching
systems, and deploying applications.
Scripting complexity: Ansible uses a simple, human-readable language (YAML) to define automation
tasks, eliminating the need for complex scripting.
Consistency and scalability: Ansible ensures consistent configurations across environments and scales
to manage thousands of machines.
Easier to learn and use: Ansible's syntax is more straightforward than traditional scripting languages.
Agentless architecture: Ansible doesn't require installing agents on managed nodes, simplifying
deployment.
Idempotent operations: Ansible tasks are idempotent, meaning they can be run multiple times without
causing unintended side effects.
Problem: You need to restart multiple web servers and database servers in a specific order to avoid
application downtime.
Solution: An Ansible playbook can define the sequence of actions:
1. Power down web servers.
2. Power down database servers.
3. Power up database servers.
4. Power up web servers.
Problem: You're deploying a multi-tier application across public and private clouds, involving
numerous VMs and configurations.
Solution: Ansible can:
o Provision VMs on AWS, VMware, or other platforms.
o Configure applications, install software, and manage dependencies.
o Set up networking, firewalls, and load balancers.
o Integrate with other tools like CMDBs and ServiceNow for automated workflows.
Agentless: Ansible manages remote machines over SSH, eliminating the need for agents.
Cloud integration: Ansible has modules to interact with major cloud providers (AWS, Azure, GCP) for
cloud resource management.
On-premises and hybrid: Ansible works seamlessly with on-premises servers, virtual machines, and
cloud instances.
Ansible Documentation: The official documentation at docs.ansible.com is the best place to start.
Ansible Galaxy: A community hub for finding pre-built Ansible roles and playbooks
(https://galaxy.ansible.com/).
Control Node: The machine where you run Ansible commands and store playbooks.
Managed Nodes: The target servers, devices, or network equipment you want to automate.
Inventory: A file listing the managed nodes and their groupings.
Playbooks: YAML files that define the automation tasks to be executed.
Modules: Reusable units of code that perform specific actions (e.g., installing software, managing
files).
This demo focuses on building a lab environment for experimenting with Ansible. The environment consists of:
1. Download: Visit https://www.virtualbox.org/ and download the appropriate VirtualBox installer for
your operating system.
2. Installation: Run the installer and follow the on-screen instructions.
3. Verification: Open the Oracle VM VirtualBox interface to ensure successful installation.
1. Login:
o Default Username: osboxes
o Default Password: osboxes.org
2. Verify Network: Open a terminal and run ifconfig to confirm the VM has an IP address and network
connectivity.
3. Shutdown: Power off the CentOS Template VM.
6. Cloning VMs
1. Clone Template:
o Right-click on the CentOS-Template VM and select "Clone".
o Name: Ansible-Controller
o Check "Reinitialize the MAC address".
o Select "Linked clone" to save disk space.
o Click "Clone".
2. Clone Target: Repeat the cloning process to create another VM named Ansible-Target1.
9. Testing Connectivity
1. Manual SSH: From the Ansible Controller, SSH into the Ansible Target to establish initial trust and
accept the SSH key fingerprint.
2. Create Ansible Inventory:
o Create a directory: mkdir test-project
o Create an inventory file: vi test-project/inventory.txt
o Add the following content to the inventory file:
3. [targets]
4. target1 ansible_host=<target1_ip_address> ansible_ssh_pass=osboxes.org
Conclusion
You have successfully set up a basic Ansible lab environment with a Controller and two Target machines. You
can now start exploring and experimenting with Ansible playbooks and modules to automate configuration
management tasks on your target systems.
A: This demo guides you through setting up a lab environment on your local machine to experiment with
Ansible.
A:
A:
A:
1. Download Pre-configured Image: Visit https://www.osboxes.org/ and download the VirtualBox image
for the CentOS version you need (e.g., CentOS 7 64-bit).
2. Extract Image: The downloaded file will be compressed (e.g., .7z). Use an extraction tool like 7-Zip or
WinZip to extract its contents.
3. Locate VDI: Inside the extracted folder, find the .vdi (Virtual Disk Image) file. This file represents the
virtual hard drive for your CentOS VM.
A:
A:
1. Login:
o Default Username: osboxes
o Default Password: osboxes.org
2. Network Check: Open a terminal inside the CentOS Template and run ifconfig to verify the VM has a
valid IP address and can access the network.
3. Shutdown: Power off the CentOS Template VM.
A:
1. Clone Controller:
o Right-click the CentOS-Template VM and select "Clone".
o Name: Ansible-Controller
o Important: Check "Reinitialize the MAC address" to avoid network conflicts.
o Space-Saving: Select "Linked clone" (uses less disk space).
o Click "Clone".
2. Clone Target: Repeat the cloning process to create another VM named Ansible-Target1.
A:
A:
Q10: How do I test the connection between the Ansible Controller and Target?
A:
1. Initial Trust (Important): From the Ansible Controller, SSH directly into the Ansible Target (ssh
osboxes@<target1_ip_address>) and accept the SSH key fingerprint when prompted. This establishes
initial trust.
2. Ansible Inventory:
o Create Directory: mkdir test-project
o Inventory File: vi test-project/inventory.txt
o Add Content:
o [targets]
o target1 ansible_host=<target1_ip_address> ansible_ssh_pass=osboxes.org
3. Ping Test:
o Run: ansible target1 -m ping -i inventory.txt
o You should see a "pong" message, indicating successful communication.
A:
1. Clone: Clone the CentOS-Template once more, naming the new VM Ansible-Target2. Make sure to
reinitialize the MAC address and select the "Linked clone" option.
2. Configure: Follow the same hostname configuration and SSH setup steps as you did for Ansible-
Target1.
3. Update Inventory: Add Ansible-Target2 to inventory.txt:
4. [targets]
5. target1 ansible_host=<target1_ip_address> ansible_ssh_pass=osboxes.org
6. target2 ansible_host=<target2_ip_address> ansible_ssh_pass=osboxes.org
A:
Recommended: Manually SSH from the Ansible Controller to Ansible-Target2 and accept the SSH key
fingerprint. This is the most secure way to establish trust.
Less Secure (Not for Production): Edit /etc/ansible/ansible.cfg on the Ansible Controller and
uncomment host_key_checking = False. This disables host key checking but makes your setup less
secure.
Final Note: This cheat sheet gets you a basic Ansible lab environment up and running. Remember that using
SSH keys for authentication in a production setting is highly recommended for security reasons.
What is YAML?
Essential for Ansible: Understanding YAML is crucial for working with Ansible, as all playbooks are
written in this format.
Easy to Learn: YAML is designed for readability and simplicity, making it easy to understand and
write.
The table below illustrates how the same data about servers is represented in three different formats:
Uses indentation, colons, Uses curly braces, colons, Uses tags and attributes within angled
Syntax
and dashes and commas brackets
{"server": {"name":
server: \n name: Server1 <server><name>Server1</name></server> Example
"Server1"}}
Most human-readable
More concise than XML Can be verbose and complex Readability
and concise
As evident, YAML provides a cleaner and more intuitive structure for representing the same information.
YAML Syntax Basics
This section covers the fundamental syntax rules of YAML.
Key-Value Pairs
fruit: apple
vegetable: carrot
liquid: water
meat: chicken
Lists (Arrays)
fruits:
- apple
- banana
- orange
vegetables:
- carrot
- spinach
- broccoli
Dictionaries (Hashes)
apple:
calories: 95
fat: 0.3
carbs: 25
banana:
calories: 105
fat: 0.4
carbs: 27
Importance of Indentation
Example:
# Correct Indentation
banana:
calories: 105
fat: 0.4
carbs: 27
car:
color: red
model:
name: Accord
year: 2023
transmission: automatic
price: 25000
car_names:
- red Accord
- blue Camry
- silver Civic
- black Corolla
- white Elantra
- gray Malibu
Lists of Dictionaries
Combines lists and dictionaries to represent multiple objects with their properties.
cars:
- color: red
model:
name: Accord
year: 2023
transmission: automatic
price: 25000
- color: blue
model:
name: Camry
year: 2022
transmission: automatic
price: 23000
Key Points
Ordered vs. Unordered:
o Dictionaries are unordered, meaning the order of key-value pairs doesn't matter.
o Lists are ordered, and the sequence of items is significant.
Comments: Use # to add comments in YAML. Anything after # on a line is ignored.
Conclusion
This structured breakdown of YAML syntax, along with practical examples and comparisons, provides a solid
foundation for understanding and writing Ansible playbooks. As you progress through the course, refer back to
this document for quick refreshers and clarifications.
A: YAML (YAML Ain't Markup Language) is a human-readable data serialization language used for
configuration files and data exchange. It's the language used to write Ansible playbooks.
A: Ansible playbooks are text files (configuration files) written in YAML that define a series of automated
tasks for managing and configuring systems.
A:
Key-Value Pairs: Represent data with a key and its corresponding value. Separated by a colon and a
space.
fruit: apple
Lists (Arrays): Represent an ordered sequence of items, each starting with a dash and a space.
fruits:
- apple
- banana
- orange
Dictionaries (Hashes): Used to group key-value pairs under a single key. Use indentation (two spaces)
to define the hierarchy.
apple:
calories: 95
fat: 0.3
carbs: 25
A: Indentation defines the structure and hierarchy of the data. Inconsistent indentation leads to syntax errors.
A:
Dictionary: Use to represent the properties of a single object. Each key-value pair describes an attribute
of that object.
car:
color: red
model: Civic
year: 2023
List of Dictionaries: Use to represent multiple objects, each with its own set of properties.
cars:
- color: red
model: Civic
year: 2023
- color: blue
model: Accord
year: 2022
A:
Dictionaries: Unordered. The order of key-value pairs doesn't affect the data.
Lists: Ordered. The order of items matters.
A: Use the hash symbol (#) for comments. Anything after # on a line is ignored.
# This is a comment
fruit: apple # This fruit is red
XML:
<server>
<name>Server1</name>
<ip>192.168.1.100</ip>
</server>
JSON:
{
"server": {
"name": "Server1",
"ip": "192.168.1.100"
}
}
YAML:
server:
name: Server1
ip: 192.168.1.100
YAML is generally preferred for its readability and conciseness, making it ideal for Ansible playbooks.
Unlike many orchestration tools, Ansible operates without requiring agent software on target machines. This
"agentless" approach relies on standard SSH (for Linux) or PowerShell Remoting (for Windows) for
connectivity.
Advantages of Agentless:
Ansible uses inventory files to store information about the target systems it manages.
Default Inventory: If no custom inventory is specified, Ansible uses the default inventory file located
at /etc/ansible/hosts.
Custom Inventories: You can create custom inventory files to organize your systems.
Inventory File Structure
Inventory files follow an INI-like format with sections defining groups of servers:
[webservers]
web01.example.com
web02.example.com
[databaseservers]
db01.example.com
db02.example.com
Inventory Parameters
Each server entry in the inventory file can have various parameters associated with it, providing Ansible with
connection details. Key parameters include:
N/A SSH password for the user (not recommended for production) ansible_ssh_pass
[webservers]
web01 ansible_host=192.168.1.10 ansible_user=ubuntu
web02 ansible_host=192.168.1.11 ansible_user=ubuntu
Note: Storing passwords in plain text within inventory files is a security risk. For production environments,
utilize SSH key-based authentication for secure, passwordless connections.
Best Practices
SSH Keys: Prioritize SSH key-based authentication over password-based authentication for enhanced
security.
Group Organization: Utilize groups within your inventory files to logically categorize and manage
your servers.
Parameterization: Leverage inventory parameters to store and manage connection details efficiently.
By mastering Ansible inventory configuration, you gain a powerful tool for organizing and managing your
infrastructure for automation tasks.
Ansible inventory files contain information about the target systems (hosts) Ansible manages. They define
which servers Ansible can connect to and control.
Servers are grouped by enclosing the group name in square brackets [group_name] followed by a list of hosts
belonging to that group.
Example:
[webservers]
web01.example.com
web02.example.com
[databaseservers]
db01.example.com
db02.example.com
ansible_host is an inventory parameter that specifies the FQDN (Fully Qualified Domain Name) or IP address
of a target server.
ansible_connection: Defines the connection type (default: ssh). Use winrm for Windows or local for the
Ansible control node itself.
ansible_port: Specifies the connection port (default: 22 for SSH).
ansible_user: Defines the remote user account used for connections (default: root for Linux).
ansible_ssh_pass: (Not recommended for production!) Sets the SSH password for the connecting
user.
9. What is the recommended way to authenticate with target servers in a production environment?
Use SSH key-based authentication for secure, passwordless connections in production environments. Avoid
storing passwords in plain text within inventory files.
10. Provide an example of an inventory file with aliases and parameters:
[webservers]
web01 ansible_host=192.168.1.10 ansible_user=ubuntu
web02 ansible_host=192.168.1.11 ansible_user=ubuntu
This example defines a group "webservers" with two hosts, "web01" and "web02". Each host has its IP address
defined using ansible_host and the connecting user set to "ubuntu".
Playbooks are the heart of Ansible's orchestration engine. They serve as blueprints, defining a series of
instructions that Ansible executes to achieve a desired state on target systems.
Imagine a play as a set of directions, and tasks as individual steps within those directions. Playbooks can range
in complexity from simple tasks like restarting a service to complex deployments spanning multiple servers.
Playbook Examples:
Simple: Running a sequence of commands on multiple servers, restarting services in a specific order.
Complex: Deploying numerous virtual machines across cloud infrastructures, provisioning storage,
configuring networks, setting up applications, and establishing monitoring and backup systems.
Playbooks are written in YAML (Yet Another Markup Language), a human-readable data serialization format.
Understanding YAML is crucial for working with playbooks.
Playbook Components:
A playbook comprises one or more plays, each targeting a specific host or group of hosts.
1. Plays:
2. Tasks:
3. Modules:
Sample Playbook:
---
- name: Play One
hosts: localhost
tasks:
- name: Print date
command: date
- name: Install Apache
yum: name=httpd state=present
- name: Play Two
hosts: localhost
tasks:
- name: Start Apache
service: name=httpd state=started
Running a Playbook:
Additional Resources:
Conclusion:
This introduction provides a foundational understanding of Ansible playbooks. Mastering these concepts is
essential for effectively automating system administration and configuration management tasks.
Answer: Playbooks define what you want Ansible to do, ranging from simple tasks like running commands on
a server to complex deployments like setting up cloud infrastructure and applications. They provide a structured
and repeatable way to manage your systems.
Answer: Playbooks are written in YAML (Yet Another Markup Language) format. YAML is human-readable
and well-suited for configuration management due to its simple syntax.
Answer:
Plays: The building blocks of a playbook. Each play defines a set of tasks to execute on a specific host
or group of hosts.
Tasks: Individual units of work within a play. A task might be running a command, installing software,
or managing a service.
Modules: The actual commands or actions that tasks use. Ansible has numerous built-in modules for
various tasks (e.g., command, yum, service, etc.).
Answer:
---
- name: My First Playbook
hosts: webservers # Target a group of hosts defined in your inventory
tasks:
- name: Update the system
apt:
update_cache: yes
Answer: The hosts parameter within a play specifies the target machines. You can use hostnames, IP addresses,
or groups defined in your Ansible inventory file.
Answer: The tasks section lists the actions (in order) that Ansible will perform on the target hosts. Each task is
defined with a module and its parameters.
8. What are Ansible Modules and why are they important?
Answer: Modules are reusable units of code that provide specific functionalities. They abstract away the
complexity of tasks. For example, the yum module handles package management on RedHat-based systems,
while the apt module handles it on Debian-based systems.
Answer: You use the ansible-playbook command followed by the name of the playbook file:
ansible-playbook my_playbook.yml
10. Where can I find more information about Ansible Playbooks and Modules?
Answer:
Ansible modules are standalone, reusable units of code that automate specific tasks on managed nodes. They
are the building blocks of Ansible playbooks and define the desired state of your infrastructure.
Module Categories
Ansible modules are categorized based on their functionalities. Some common categories include:
System Modules:
o Manage users and groups
o Configure firewalls (e.g., iptables)
o Work with logical volumes
o Handle service manipulation (start, stop, restart)
Commands Modules:
o Execute commands on remote hosts (command, shell, script)
o Respond to prompts during command execution (expect)
File Modules:
o Manage file permissions (acl)
o Compress and decompress files (archive, unarchive)
o Modify file contents (find, lineinfile, replace)
Database Modules:
o Work with databases like MongoDB, MySQL, MSSQL, PostgreSQL
o Manage database configurations and operations
Cloud Modules:
oInterface with cloud providers (AWS, Azure, Docker, Google Cloud, OpenStack, VMware)
oManage instances, networking, security, containers, and more
Windows Modules:
o Tailored for Windows environments
o Copy files (win_copy), execute commands (win_command)
o Manage files, IIS websites, MSI installations, registry, services, and users
Parameters:
Example Playbook:
---
- hosts: target_hosts
tasks:
- name: Execute commands on remote hosts
command:
- date
- cat /etc/resolv.conf
- name: Execute command after changing directory
command:
chdir: /etc
cmd: cat resolv.conf
- name: Create a directory if it doesn't exist
command:
creates: /path/to/directory
cmd: mkdir /path/to/directory
Key Points:
The command module uses a free-form input style, meaning the command is passed directly as a string,
not as key-value pairs.
Not all modules support free-form input. For instance, the copy module requires specific parameters like
src and dest.
Parameters:
---
- hosts: target_hosts
tasks:
- name: Execute a script on remote hosts
script: /path/to/local/script.sh --arg1 value1
Key Points:
Parameters:
Example Playbook:
---
- hosts: target_hosts
tasks:
- name: Start the PostgreSQL service
service:
name: postgresql
state: started
- name: Start the HTTPD service
service:
name: httpd
state: started
- name: Start the internet service
service:
name: network
state: restarted
Key Points:
Parameters:
---
- hosts: target_hosts
tasks:
- name: Add a DNS server to resolv.conf
lineinfile:
path: /etc/resolv.conf
line: "nameserver 8.8.8.8"
Key Points:
Conclusion
This document has provided a foundational understanding of Ansible modules, their categories, and detailed
examples of specific modules. You can further explore the vast world of Ansible modules and their capabilities
by referring to the official Ansible documentation.
A: Ansible modules are reusable, standalone units of code that automate specific tasks on managed nodes. They
define the desired state of your infrastructure and are the building blocks of Ansible playbooks.
System Modules: Manage system-level tasks like user/group management, firewall configuration,
logical volumes, and service manipulation.
Commands Modules: Execute commands or scripts on remote hosts (e.g., command, shell, script,
expect).
File Modules: Work with files and directories (e.g., acl, archive, unarchive, find, lineinfile, replace).
Database Modules: Manage databases like MongoDB, MySQL, MSSQL, PostgreSQL.
Cloud Modules: Interact with cloud providers like AWS, Azure, Docker, Google Cloud, OpenStack,
and VMware for tasks like instance management, networking, and security.
Windows Modules: Designed specifically for Windows environments (e.g., win_copy, win_command,
registry management).
A: Visit the official Ansible documentation at docs.ansible.com for a complete list and detailed information on
each module.
A: The command module executes commands on remote nodes. Key parameters include:
A:
Free-form: Takes the command or input as a single string without key-value pairs. Example: command:
uptime
Parameterized: Requires specific key-value pairs for input. Example: copy: src=/https/www.scribd.com/local/file
dest=/remote/file
Not all modules support both input types. The command module uses free-form, while copy requires
parameterized input.
A: The script module efficiently executes local scripts on remote nodes. It automatically transfers the script to
the remote system and then executes it, simplifying administration tasks.
Q: Explain the concept of idempotency in Ansible and provide an example using the service module.
A:
Idempotency: Means that running a task multiple times has the same effect as running it once. Ansible
strives for idempotency to ensure desired states without unintended side effects.
Example: The service module uses idempotent states like started, stopped, restarted:
o service: name=httpd state=started will only start the httpd service if it's not already running.
Running this task again won't restart the service, ensuring the desired "started" state.
A: The lineinfile module ensures a specific line exists in a file. If the line is already present, no action is taken.
This ensures the file has the desired content without duplicate lines, even with multiple playbook runs.
This ensures the line nameserver 8.8.8.8 is present in the file. If it already exists, no change occurs.
Variables in Ansible
This document explains the concept of variables in Ansible and demonstrates how to define and use them
effectively.
Just like in any programming or scripting language, variables in Ansible are used to store values that can
change based on the target system. This allows for reusable playbooks that can be applied across diverse
environments.
Example:
Imagine applying software patches to 100 servers. Instead of creating 100 different playbooks, a single
playbook can be used with variables storing specific information for each server:
2. Defining Variables
We've already encountered variables when working with inventory files. For example:
[webservers]
web.example.com ansible_connection=ssh ansible_ssh_user=ubuntu ansible_ssh_pass=password
Here, ansible_connection, ansible_ssh_user, and ansible_ssh_pass are all variables defining connection
parameters for the web.example.com host.
Variables can be defined directly within a playbook using the vars directive:
---
- hosts: webservers
vars:
dns_server: "192.168.1.1"
tasks:
# ... playbook tasks ...
For better organization, especially in larger projects, variables can reside in dedicated YAML files. We'll
explore this further in sections about includes and roles.
Variables specific to a single host can be placed in a YAML file named after the host, residing in the same
directory as the inventory file.
For instance, a file named web.example.com.yaml containing:
Defining variables is only half the story; we need to use them within playbooks. Ansible leverages Jinja2
templating for this purpose.
To access a variable's value, enclose its name within double curly braces {{ }}:
When executed, Ansible replaces {{ dns_server }} with the value defined for the dns_server variable.
This playbook utilizes the firewall_rule1 and firewall_rule2 variables defined in the host variable file.
Remember:
Enclose variable usage within quotes (" or ') if the assignment starts with the variable.
Quotes are not mandatory if the variable is part of a larger string.
4. Additional Notes
Jinja2 Templating: Explore the dedicated CodeCloud course for an in-depth understanding of Jinja2's
capabilities.
Exercises: Practice using variables in various scenarios to solidify your understanding.
A1: Variables in Ansible, just like in any programming language, are used to store values that can change. This
makes your playbooks more flexible and reusable.
A2: They allow you to write a single playbook that can work on multiple servers with different configurations.
Imagine patching 100 servers. Instead of 100 playbooks, you need one with variables for hostname, username,
password, etc., specific to each server.
A3:
Inventory File: Directly within the inventory file for host-specific variables.
[webservers]
web.example.com ansible_connection=ssh ansible_ssh_user=ubuntu
ansible_ssh_pass=password
Separate Variable Files: For better organization, store variables in dedicated YAML files (more on
this in includes and roles).
Host Variable Files: Create YAML files named after the host (e.g., web.example.com.yaml) in the
inventory directory for host-specific variables.
A4: Use Jinja2 templating. Enclose the variable name within double curly braces: {{ variable_name }}.
```yaml
- name: Add DNS entry
lineinfile:
path: /etc/resolv.conf
line: "nameserver {{ dns_server }}"
```
A6: Use host variable files to keep variables specific to a host separate and organized. This improves
readability and maintainability.
A7: Check out the "Jinja2 Templating for Absolute Beginners" course on CodeCloud.
Imagine a scenario where you need to install Nginx on a variety of servers. Different operating systems rely on
different package managers:
Maintaining separate playbooks for each OS flavor can be cumbersome. Conditionals empower you to create a
single, unified playbook adaptable to different environments.
The when statement is your gateway to conditional execution in Ansible. It dictates that a task should only run
if the specified condition evaluates to true.
Syntax:
Let's construct a playbook that installs Nginx using the appropriate package manager based on the OS:
---
- hosts: all
tasks:
- name: Install Nginx on Debian-based systems
apt:
name: nginx
state: present
when: ansible_os_family == "Debian"
Explanation:
Ansible provides logical operators to combine conditions for more complex scenarios:
and: The task runs only if all specified conditions are true.
when: (ansible_os_family == "Debian") and (ansible_version == "16.04")
You can seamlessly integrate conditionals within loops to control the execution of tasks on individual items:
- hosts: all
vars:
packages:
- name: httpd
required: true
- name: postgresql
required: false
- name: nginx
required: true
tasks:
- name: Install packages based on 'required' status
yum:
name: "{{ item.name }}"
state: present
loop: "{{ packages }}"
when: item.required == true
Explanation:
Ansible enables you to make decisions based on the output of previous tasks using the register directive:
- hosts: all
tasks:
- name: Check service status
command: systemctl status nginx
register: result
Explanation:
The register directive stores the output of the "Check service status" task in the result variable.
We use the find method to search for the string "down" within result.stdout.
If "down" is found (indicating the service is down), the email task is executed.
Conclusion
Conditional statements are indispensable tools in your Ansible arsenal. They introduce flexibility, allowing
your playbooks to adapt intelligently to different environments and scenarios. Experiment with the when
statement, logical operators, and task output integration to unlock the full potential of conditional logic in your
automation workflows.
Problem: Different operating systems often require different commands or configurations. Using
separate playbooks for each OS is inefficient.
Solution: Conditionals let you create a single playbook that adapts to different environments.
The when statement: Use the when statement to specify a condition for a task. The task only runs if the
condition is true.
- name: Task Description
<module_name>: ...
when: <condition>
Goal: Install Nginx using apt on Debian and yum on Red Hat.
Solution:
---
- hosts: all
tasks:
- name: Install Nginx on Debian
apt:
name: nginx
state: present
when: ansible_os_family == "Debian"
- name: Install Nginx on Red Hat
yum:
name: nginx
state: present
when: ansible_os_family == "RedHat"
Goal: Install packages from a list, only if the package is marked as "required."
Solution:
- hosts: all
vars:
packages:
- name: httpd
required: true
- name: postgresql
required: false
tasks:
- name: Install required packages
yum:
name: "{{ item.name }}"
state: present
loop: "{{ packages }}"
when: item.required == true
Goal: Check service status and send an email if the service is down.
Solution:
- hosts: all
tasks:
- name: Check service status
command: systemctl status nginx
register: result
- name: Send email if service is down
mail:
... # Email configuration
when: result.stdout.find("down") != -1
Explanation:
o The register directive stores the output of a task in a variable (e.g., result).
o Use result.stdout to access the standard output of the command.
o find("down") != -1 checks if the word "down" exists in the output.
Key Takeaway: Conditionals make your Ansible playbooks more dynamic and reusable by allowing you to
tailor execution based on specific conditions.
Introduction to Loops
Loops are essential for automating repetitive tasks in Ansible. Instead of duplicating code for each item you
want to process, loops allow you to iterate over a collection of data and perform the same actions. This
significantly improves playbook readability, maintainability, and efficiency.
The loop directive is the simplest way to implement loops in Ansible. It iterates over a list of items and
executes the defined tasks for each item.
Let's consider creating multiple users on a system. Using the user module without a loop would involve
repetitive code:
Within the loop, each item from the list is accessible through the item variable. Visualizing this process can aid
understanding:
Loops are not limited to strings. You can iterate over a list of dictionaries, allowing for more complex data
structures.
JSON Representation
The array of dictionaries used in the loop can also be represented in JSON format:
[
{"name": "Joe", "uid": 1001},
{"name": "George", "uid": 1002},
{"name": "Ravi", "uid": 1003}
]
with_items
The with_items directive is functionally similar to loop and is often found in older playbooks.
Beyond with_items
Lookup Plugins
The key to the versatility of with_ directives lies in lookup plugins. These are essentially custom scripts capable
of performing specific tasks:
Reading files
Connecting to URLs, databases, or other systems like Kubernetes and OpenShift
Conclusion
Understanding loops is crucial for writing efficient and maintainable Ansible playbooks. By leveraging the loop
directive and exploring the power of with_ directives and lookup plugins, you can significantly enhance your
automation capabilities. Remember to visualize complex loops to better grasp their execution flow.
A: Loops prevent code duplication when performing the same task on multiple items. This makes playbooks:
More concise: Instead of writing the same task repeatedly, you write it once and iterate over a list of
items.
Easier to maintain: Changes only need to be made in one place within the loop.
More efficient: Reduces redundancy and improves readability.
A: The loop directive iterates over a list and executes the defined task for each item in the list.
Example:
- name: Create multiple users
user:
name: "{{ item }}"
state: present
loop:
- Joe
- George
- Ravi
A: Use the same loop structure, but access dictionary values using dot notation within the task:
Example:
- name: Create users with IDs
user:
name: "{{ item.name }}"
uid: "{{ item.uid }}"
state: present
loop:
- name: Joe
uid: 1001
- name: George
uid: 1002
- name: Ravi
uid: 1003
Access values: Use item.key (e.g., item.name, item.uid) to access specific values within each
dictionary.
A: loop is the newer, preferred syntax for simple loops. with_items achieves the same result but is found in
older playbooks.
Q: What are with_ directives and how do they differ from loop?
A: with_ directives are used for more specialized looping scenarios, often interacting with external sources.
They leverage lookup plugins to access data.
Examples:
o with_files: Iterates over multiple files.
o with_url: Connects to multiple URLs.
o with_mongodb: Connects to multiple MongoDB databases.
A: Think of them as custom scripts extending Ansible's functionality. They perform specific tasks like:
Reading files
Connecting to URLs, databases, or other systems (Kubernetes, OpenShift)
Key Takeaway: Choose loop for basic iterations and explore with_ directives and lookup plugins for more
advanced use cases.
This document provides a comprehensive overview of roles in Ansible, exploring their purpose, structure,
usage, and benefits. We will delve into how roles enhance code organization, reusability, and sharing within the
Ansible ecosystem.
Understanding Roles
Imagine assigning real-world roles like doctors or engineers. The process involves specific education, training,
and licensing. Similarly, in Ansible, roles transform blank servers into specialized entities like database servers
or web servers.
1. Installing prerequisites.
2. Installing MySQL packages.
3. Configuring the MySQL service.
4. Setting up databases and users.
Traditionally, this might involve lengthy Ansible playbooks. Roles simplify this process by packaging these
tasks into reusable units.
1. Reusability: Once a role is created (e.g., for installing and configuring MySQL), it can be shared and
reused by anyone, eliminating the need for repetitive code.
2. Organization: Roles enforce a standardized structure:
o tasks: Contains tasks to be executed.
o vars: Holds variables used by the tasks.
o defaults: Stores default values for variables.
o handlers: Houses handlers for event-driven actions.
o templates: Contains Jinja2 templates used by the playbooks.
3. Sharing: Ansible Galaxy, a community-driven platform, hosts a vast collection of roles for various
purposes, fostering collaboration and knowledge sharing.
1. Creating a Role
Manual Creation: Create the directory structure for the role and populate it with the necessary files.
Ansible Galaxy Initialization: Utilize the ansible-galaxy init <role_name> command to generate a
basic role skeleton.
Example:
Roles Directory: Place the role directory within a designated "roles" directory within your playbook's
directory or specify a common roles directory in your Ansible configuration file (ansible.cfg).
Playbook Integration: Invoke the role within your playbook using the roles directive:
---
- hosts: my_servers
roles:
- my_mysql_role
3. Role Parameters
Become Directive: Control privilege escalation for tasks within the role.
---
- hosts: my_servers
roles:
- role: my_mysql_role
become: true
Ansible Galaxy
Role Repository: Ansible Galaxy acts as a central hub for sharing and downloading roles.
Searching for Roles: Use the Ansible Galaxy UI or the ansible-galaxy search <search_term>
command.
Installing Roles: Install roles using the ansible-galaxy install <role_name> command. Roles are
typically downloaded to the default roles path (/etc/ansible/roles).
Example:
ansible-galaxy install geerlingguy.mysql
Managing Roles
Listing Installed Roles: Use the ansible-galaxy list command to view installed roles.
Role Installation Path: Determine the role installation directory using ansible-config dump --only
roles_path.
Custom Installation Directory: Install roles in a specific directory using the -p option during
installation.
ansible-galaxy install -p ./roles geerlingguy.mysql
Summary
Roles streamline Ansible automation by promoting code organization, reusability, and community sharing. This
document has provided a structured guide to understanding and leveraging the power of roles in your Ansible
workflows.
A: Think of roles like job titles in the real world (doctor, engineer). In Ansible, they prepare servers for specific
functions (database, web server, etc.). Just like a doctor needs education and training, a database server needs
specific software, configurations, and settings. Roles package all these steps for easy reuse.
A:
1. Reusability: Write once, use many times. Share with your team or the Ansible community.
2. Organization: Roles enforce a structured layout, making your code cleaner and easier to understand.
3. Efficiency: No need to reinvent the wheel. Leverage existing roles to save time and effort.
A:
role_name/
├── tasks/ # Tasks to execute (e.g., install software, configure
settings)
│ └── main.yml
├── handlers/ # Event-driven actions (e.g., restart service after config
change)
│ └── main.yml
├── defaults/ # Default values for role variables
│ └── main.yml
├── vars/ # Variables used by the role's tasks
│ └── main.yml
└── templates/ # Jinja2 templates for dynamic configurations
└── my_template.j2
A:
A:
1. Placement: Put roles in a roles/ directory next to your playbook or in a common roles path configured
in ansible.cfg.
2. Invocation: Use the roles directive in your playbook:
3. - hosts: my_servers
4. roles:
5. - my_mysql_role
A:
A: Yes!
Example:
- hosts: my_servers
roles:
- role: my_mysql_role
become: true
mysql_user: 'custom_admin'
Although Ansible's control machine requires Linux, it can effectively manage Windows targets, incorporating
them into your automation workflows.
Unlike Linux machines where SSH facilitates connections, Ansible leverages WinRM (Windows Remote
Management) to communicate with Windows machines. However, WinRM is not enabled by default and
requires some initial setup.
1. Install pywinrm Module: On your Ansible control machine (Linux), install the pywinrm module using
pip:
2. pip install "pywinrm==0.2.2"
Authentication Modes
Basic Authentication
Certificate-Based Authentication
Kerberos
NTLM
Refer to the Ansible documentation for detailed instructions on configuring each authentication mode.
Ansible Galaxy (https://galaxy.ansible.com/) serves as a central hub for discovering, sharing, and rating
community-developed Ansible roles. It significantly streamlines automation projects by providing pre-built
roles for common tasks and configurations.
Jumpstart Projects: Leverage existing roles to avoid reinventing the wheel, saving development time.
Community Collaboration: Benefit from the collective knowledge and experience of the Ansible
community.
Reusable and Shareable Roles: Promote code reusability and share your custom roles with others.
1. Browse Roles: Explore the available roles on the Ansible Galaxy website.
2. Download Roles: Use the ansible-galaxy command-line tool to download desired roles into your
project.
3. Incorporate Roles: Include the downloaded roles in your playbooks, assigning them to the relevant
hosts.
III. Understanding Ansible Patterns
Ansible patterns provide a flexible and powerful mechanism for selecting target hosts to run tasks against,
extending beyond simple hostnames or group names.
Pattern Options:
Targets a specific group and an additional host. group1:children:webservers,host1 Groups & Hosts
Refer to the Ansible documentation for a comprehensive list of pattern options and examples.
Static inventory files can be limiting, especially in dynamic environments. Ansible supports dynamic inventory,
enabling you to fetch inventory information from external sources.
How it Works:
1. Specify a Script: Instead of a static file, provide a script (typically Python) as the inventory source
using the -i parameter.
2. ansible-playbook -i inventory.py playbook.yml
3. Dynamic Inventory Script: This script interacts with external systems (e.g., cloud providers, CMDBs)
to gather and return inventory data to Ansible.
Advantages:
Available Scripts:
Ansible offers pre-built dynamic inventory scripts for various platforms, including:
Cobbler
HWS (Hardware State Manager)
OpenStack
While Ansible provides numerous built-in modules, you might need to develop custom modules for specific
tasks or integrations not covered by the default modules.
Creating a Custom Module:
Extending Functionality: Tailor Ansible to your unique needs by adding support for new platforms,
services, or actions.
Code Reusability: Package your custom logic into reusable modules for use across multiple playbooks
and projects.
Practice Regularly: Reinforce your knowledge by building and executing playbooks for real-world
scenarios.
Explore Advanced Topics: Delve deeper into the areas covered in this section to expand your Ansible
skillset.
Consider Ansible Certification: Validate your expertise and boost your career prospects by pursuing
Ansible certification.
For those seeking comprehensive Ansible mastery and certification preparation, consider our "Ansible
Certification Course."
Key Features:
Real-World Labs: Gain practical experience through interactive, browser-based labs, eliminating the
need for local setup.
Instant Feedback: Receive immediate validation and guidance through the integrated quiz portal,
facilitating rapid learning.
Mock Exams: Prepare for the certification exam with realistic mock exams that simulate the exam
environment and time constraints.
Thank you for choosing this course! We wish you the best in your automation endeavors.
Configure WinRM: On the Windows server, download and run Ansible's PowerShell script:
ConfigureRemotingForAnsible.ps1.
Authentication: Configure WinRM authentication (Basic, Certificate-based, Kerberos, NTLM, etc.) as
needed. Refer to Ansible documentation for details.
Ansible Galaxy (https://galaxy.ansible.com/) is a free online hub for finding, sharing, and rating community-
developed Ansible roles.
Ansible patterns provide flexible ways to select target hosts for tasks, going beyond basic hostnames or groups.
Examples:
Dynamic inventory enables Ansible to fetch inventory information from external sources instead of relying
solely on static inventory files.
Specify a Script: Instead of a static file, use the -i parameter to point to a script (often Python) as the
inventory source:
ansible-playbook -i inventory.py playbook.yml
Script's Role: The script interacts with external systems like cloud providers or CMDBs, gathers
inventory data, and provides it to Ansible.
Yes, you can create custom modules using Python to extend Ansible's functionality for your specific needs.
9. How do you create a custom module?
10. Where can you find more information about Ansible Module Development?
The Ansible documentation offers comprehensive guides and examples. Look for the "Building a Simple
Module" section within the Ansible Developer Guide.
The challenges of manual IT tasks: Emphasizes the need for automation to replace repetitive, error-
prone processes.
Introduction to Ansible: Explains its agentless architecture, simplicity, and power in automating
complex deployments.
YAML syntax: Provides a solid foundation in YAML, the language for writing Ansible playbooks.
Inventory configuration: Details how Ansible manages connections to target systems for orchestration.
Playbook creation: Introduces playbooks as blueprints for automation, covering their structure,
components, and execution.
Ansible modules: Explores the building blocks of tasks, demonstrating their use through practical
examples.
Variables and loops: Explains how to use variables for dynamic playbooks and loops for iterative
tasks.
Conditional statements: Enables the creation of adaptive playbooks that respond to different
environments and scenarios.
Roles for organization and reusability: Introduces roles as a way to package and reuse Ansible code,
promoting efficiency and collaboration.
Beyond the basics, the course also delves into advanced Ansible topics:
Managing Windows with Ansible: Explains how to incorporate Windows systems into your
automation workflows using WinRM.
Exploring Ansible Galaxy: Introduces the community hub for discovering, sharing, and leveraging
pre-built Ansible roles.
Understanding Ansible Patterns: Explores pattern matching techniques for flexible target host
selection.
Implementing Dynamic Inventory: Explains how to automate inventory management by integrating
with external sources.
Developing Custom Modules: Provides insights into extending Ansible's capabilities by creating your
own modules.
System administrators
DevOps engineers
IT professionals seeking to streamline their workflows and enhance their skillset with in-demand
automation expertise.
Upon completion, participants will possess a strong foundation in Ansible, enabling them to effectively
automate infrastructure management and embark on a path towards greater efficiency and productivity.
Virtualization:
o Download and Install VirtualBox: https://www.virtualbox.org/
CentOS Image:
o Download from OS Boxes: https://www.osboxes.org/
o Extract Image: Use 7-Zip, WinZip, or similar tools.
Virtual Machine Configuration:
o Network Settings: Use Bridged Adapter for internet access.
o Resource Allocation: Allocate at least 2GB RAM, 2 CPU cores.
Connecting to VMs:
o SSH: ssh username@ip_address (default: osboxes/osboxes.org)
Hostname Configuration:
o Edit /etc/hostname and /etc/hosts to set desired hostnames.
Ansible Installation:
o CentOS: sudo yum install ansible -y
o Verify Installation: ansible --version
Inventory File:
o Default Location: /etc/ansible/hosts
o Custom Location: Specify with -i <inventory_file>
Inventory Structure:
o Groups: Define groups within square brackets [group_name]
o Hosts: List hosts under group or define individually.
o Host Parameters:
ansible_host: FQDN or IP address.
ansible_connection: Connection type (ssh, winrm, local).
ansible_port: Connection port.
ansible_user: Remote username.
Important: Use SSH keys for secure authentication in production.
4. Ansible Galaxy
Note: This is not an exhaustive list of all commands covered in the course. Refer to Ansible's official
documentation for detailed information on specific modules, directives, and advanced features.