0% found this document useful (0 votes)
25 views46 pages

Ansible Kodekloud

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views46 pages

Ansible Kodekloud

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 46

Ansible kodekloud

Introduction to Ansible: A Powerful Tool for IT Automation


The Challenge of Repetitive IT Tasks

As a systems engineer, IT administrator, or anyone working in IT, you're likely no stranger to repetitive tasks.
These can range from:

 Provisioning: Sizing and creating new hosts or virtual machines.


 Configuration Management: Applying configurations, patching servers, and handling migrations.
 Application Deployment: Deploying and configuring applications across your infrastructure.
 Security & Compliance: Performing regular security and compliance audits.

These tasks often involve executing numerous commands across numerous servers, all while maintaining a
specific sequence and managing reboots.

Traditional Solutions and Their Limitations

While scripting can automate these tasks, it presents challenges:

 Coding Skills: Requires proficiency in scripting languages.


 Maintenance: Scripts need regular updates and debugging.
 Time-Consuming: Developing complex scripts is a lengthy process.

Introducing Ansible: Simplifying IT Automation

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.

Ansible in Action: Use Cases

1. Orchestrated Server Restarts

Imagine needing to restart multiple web and database servers in a specific order. Ansible can:

 Power down web servers.


 Power down database servers.
 Power up database servers.
 Power up web servers.

This entire process can be defined in an Ansible playbook and executed with a single command.

2. Complex Infrastructure Setup

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.

Getting Started with Ansible

The official Ansible documentation (docs.ansible.com) provides comprehensive information and numerous
playbook examples to get you started.

Key Takeaways

 Ansible offers a simple yet powerful approach to automating repetitive IT tasks.


 It eliminates the complexity of traditional scripting while providing flexibility and scalability.
 With extensive documentation and a vibrant community, Ansible empowers IT professionals to
streamline their workflows and increase efficiency.

Ansible Cheat Sheet


1. What is Ansible?

Ansible is a powerful, open-source IT automation tool. It simplifies the management and configuration of
infrastructure and applications.

2. What are some common IT challenges that Ansible addresses?

 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.

3. Why choose Ansible over traditional scripting?

 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.

4. Provide some examples of Ansible use cases.

Use Case 1: Orchestrated Server Restarts

 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.

Use Case 2: Complex Infrastructure Setup

 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.

5. How does Ansible work with different environments?

 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.

6. Where can I find resources to learn more about Ansible?

 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/).

7. What are the key components of Ansible?

 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).

Setting up an Ansible Lab Environment


1. Introduction

This demo focuses on building a lab environment for experimenting with Ansible. The environment consists of:

 Virtualization: Oracle VirtualBox (compatible with Windows, Linux, and OSX)


 Guest OS: CentOS
 Machines:
o Ansible Control Machine
o Multiple Ansible Target Machines

2. Installing Oracle VirtualBox

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.

3. Downloading CentOS Image

1. OS Boxes Website: Navigate to https://www.osboxes.org/ to download a pre-configured CentOS


image.
2. Select Image: Choose the CentOS VirtualBox image for your desired version (e.g., CentOS 7 64-bit).
3. Extraction: The downloaded file will be in .7z format. Use a suitable extraction tool (e.g., 7-Zip,
WinZip) to extract the contents.
4. Locate VDI: Inside the extracted folder, locate the .vdi (Virtual Disk Image) file, which will be used to
create the virtual machine.

4. Creating CentOS Template VM

1. Open VirtualBox: Launch the Oracle VM VirtualBox interface.


2. New VM:
o Click "New" to create a new virtual machine.
o Name: CentOS-Template
o Type: Linux
o Version: Other Linux (64-bit) (Ensure virtualization is enabled in your BIOS settings if you
don't see 64-bit options)
3. Memory: Allocate at least 2GB of RAM to the VM.
4. Hard Disk:
o Select "Use an existing virtual hard disk file".
o Click "Browse" and choose the extracted .vdi file.
5. Settings: Before starting the VM, adjust the following settings:
o System > Processor: Increase CPU cores to 2.
o Network: Set to "Bridged Adapter" to allow internet access for the VM.
6. Power On: Start the virtual machine.

5. Configuring CentOS Template

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.

7. Setting Up Ansible Controller

1. Power On: Start the Ansible-Controller VM.


2. SSH Connection: Establish an SSH connection to the Ansible Controller using its IP address, username
(osboxes), and password (osboxes.org).
3. Rename Host:
o Edit /etc/hostname and replace the content with ansible-controller.
o Edit /etc/hosts and replace the hostname entry with ansible-controller.
o Restart the VM for the changes to take effect.
4. Install Ansible:
o Run sudo yum install ansible -y.
5. Verify Installation: Run ansible --version to confirm Ansible is installed and check its version.

8. Setting Up Ansible Target

1. Power On: Start the Ansible-Target1 VM.


2. SSH Connection: Establish an SSH connection to the Ansible Target using its IP address, username
(osboxes), and password (osboxes.org).
3. Rename Host:
o Edit /etc/hostname and replace the content with ansible-target1.
o Edit /etc/hosts and replace the hostname entry with ansible-target1.
o Restart the VM.

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

content_copyUse code with caution.

5. Run Ping Test:


o Execute the command: ansible target1 -m ping -i inventory.txt
o A successful ping test will return a "pong" message, confirming connectivity between the
Ansible Controller and Target.

10. Adding More Targets (Target 2)


1. Clone Target: Clone the CentOS-Template VM and name it Ansible-Target2. Remember to reinitialize
the MAC address and choose "Linked clone".
2. Configure Target: Follow the same steps as in Section 8 to set up the hostname and establish an SSH
connection to Ansible-Target2.
3. Update Inventory: Add the Ansible-Target2 details to the inventory.txt file:
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

content_copyUse code with caution.

7. Addressing SSH Key Issues:


o Option 1 (Recommended): Manually SSH from the Ansible Controller to Ansible-Target2 and
accept the SSH key fingerprint.
o Option 2 (Not Recommended for Production): Edit /etc/ansible/ansible.cfg on the Ansible
Controller and uncomment the line host_key_checking = False to disable host key checking. Use
this option with caution as it poses security risks.

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.

Ansible Lab Setup Cheat Sheet


This cheat sheet summarizes the key steps involved in setting up a basic Ansible lab environment.

Q1: What is the purpose of this demo?

A: This demo guides you through setting up a lab environment on your local machine to experiment with
Ansible.

Q2: What are the main components of this lab environment?

A:

 Virtualization Software: Oracle VirtualBox (compatible with Windows, Linux, OSX)


 Guest Operating System: CentOS
 Virtual Machines:
o 1 Ansible Control Machine
o 2+ Ansible Target Machines

Q3: How do I set up Oracle VirtualBox?

A:

1. Download: Go to https://www.virtualbox.org/ and download the appropriate VirtualBox installer for


your operating system.
2. Install: Run the downloaded installer and follow the on-screen instructions.
3. Verify: Open the Oracle VM VirtualBox interface to confirm successful installation.

Q4: How do I get a CentOS image for the virtual machines?

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.

Q5: How do I create the CentOS Template virtual machine?

A:

1. Open VirtualBox: Launch the Oracle VM VirtualBox interface.


2. New VM:
o Click "New" to create a new virtual machine.
o Name: CentOS-Template
o Type: Linux
o Version: Other Linux (64-bit) (Make sure Virtualization Technology is enabled in your BIOS
settings if you don't see 64-bit options. You can usually find this setting under "Advanced BIOS
Features" or a similar section).
3. Memory: Allocate at least 2GB of RAM for the VM.
4. Hard Disk:
o Select "Use an existing virtual hard disk file".
o Click "Browse" and choose the extracted .vdi file.
5. Settings: Before starting, adjust:
o System > Processor: Set CPU cores to 2 (or more if your system supports it).
o Network: Choose "Bridged Adapter" for internet access within the VM.
6. Start VM: Power on the virtual machine.

Q6: How do I initially configure the CentOS Template?

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.

Q7: How do I create the Ansible Controller and Target VMs?

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.

Q8: What configuration is needed for the Ansible Controller?

A:

1. Power On: Start the Ansible-Controller VM.


2. SSH: Establish an SSH connection to the Ansible Controller using its IP address (find it using ifconfig
inside the VM), username (osboxes), and password (osboxes.org).
3. Rename Host:
o Edit /etc/hostname and replace its contents with ansible-controller.
o Edit /etc/hosts and change the hostname entry to ansible-controller.
o Restart: Reboot the VM for the name change to fully take effect.
4. Install Ansible:
o Run: sudo yum install ansible -y
5. Verify: Check Ansible's installation and version: ansible --version

Q9: How do I set up the Ansible Target VM?

A:

1. Power On: Start the Ansible-Target1 VM.


2. SSH: Connect to the Ansible Target via SSH (get its IP address using ifconfig inside the VM). Use the
default username (osboxes) and password (osboxes.org).
3. Rename Host:
o Modify /etc/hostname to contain ansible-target1.
o Edit /etc/hosts and change the corresponding entry to ansible-target1.
o Restart: Reboot the VM.

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

content_copyUse code with caution.

3. Ping Test:
o Run: ansible target1 -m ping -i inventory.txt
o You should see a "pong" message, indicating successful communication.

Q11: How do I add a second Ansible Target (Target 2)?

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

content_copyUse code with caution.


Q12: I'm having trouble with SSH key errors when adding the second target. What should I do?

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.

Introduction to YAML for Ansible Playbooks


This section provides an overview of YAML and its importance in writing Ansible playbooks.

What is YAML?

 YAML stands for "YAML Ain't Markup Language".


 It's a human-readable data serialization language used for configuration files and data exchange.
 Ansible playbooks, which define automation tasks, are written in YAML.

Why Learn 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.

Comparing Data Formats: XML, JSON, and YAML

The table below illustrates how the same data about servers is represented in three different formats:

YAML JSON XML Feature

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"}}

servers: \n - name: {"servers": [{"name":


Server1 "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

 The basic building block of YAML is the key-value pair.


 Keys and values are separated by a colon (:) followed by a space.

fruit: apple
vegetable: carrot
liquid: water
meat: chicken

content_copyUse code with caution.Yaml

Lists (Arrays)

 Lists are denoted by a dash and space (- ) before each item.


 Used to represent a sequence of items.

fruits:
- apple
- banana
- orange
vegetables:
- carrot
- spinach
- broccoli

content_copyUse code with caution.Yaml

Dictionaries (Hashes)

 Dictionaries group key-value pairs under a single key.


 Use indentation (two spaces) to define the structure.

apple:
calories: 95
fat: 0.3
carbs: 25
banana:
calories: 105
fat: 0.4
carbs: 27

content_copyUse code with caution.Yaml

Importance of Indentation

 YAML uses indentation to define the hierarchy and structure of data.


 Incorrect indentation will lead to errors.
 Consistent indentation is crucial for valid YAML files.

Example:

# Correct Indentation
banana:
calories: 105
fat: 0.4
carbs: 27

# Incorrect Indentation - Will cause an error


banana:
calories: 105
fat: 0.4 # This will be interpreted as a property of "calories"
carbs: 27 # This will also be under "calories"

content_copyUse code with caution.Yaml

Understanding Data Structures: Lists vs. Dictionaries


Choosing the right data structure is essential for representing data effectively in YAML.

When to Use a Dictionary?

 Use a dictionary to represent properties of a single object.


 Each key-value pair describes an attribute of the object.

Example: Representing a Car

car:
color: red
model:
name: Accord
year: 2023
transmission: automatic
price: 25000

content_copyUse code with caution.Yaml

When to Use a List?

 Use a list to store multiple items of the same type.

Example: List of Car Names

car_names:
- red Accord
- blue Camry
- silver Civic
- black Corolla
- white Elantra
- gray Malibu

content_copyUse code with caution.Yaml

Lists of Dictionaries

 Combines lists and dictionaries to represent multiple objects with their properties.

Example: List of Cars with Details

cars:
- color: red
model:
name: Accord
year: 2023
transmission: automatic
price: 25000
- color: blue
model:
name: Camry
year: 2022
transmission: automatic
price: 23000

content_copyUse code with caution.Yaml

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.

YAML Cheat Sheet for Ansible


Q: What is YAML?

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.

Q: What is an Ansible Playbook?

A: Ansible playbooks are text files (configuration files) written in YAML that define a series of automated
tasks for managing and configuring systems.

Q: What are the basic building blocks of YAML?

A:

 Key-Value Pairs: Represent data with a key and its corresponding value. Separated by a colon and a
space.
 fruit: apple

content_copyUse code with caution.Yaml

 Lists (Arrays): Represent an ordered sequence of items, each starting with a dash and a space.
 fruits:
 - apple
 - banana
 - orange

content_copyUse code with caution.Yaml

 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

content_copyUse code with caution.Yaml

Q: Why is indentation important in YAML?

A: Indentation defines the structure and hierarchy of the data. Inconsistent indentation leads to syntax errors.

Q: How do I choose between using a list and a dictionary in YAML?

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

content_copyUse code with caution.Yaml

 List: Use to store multiple items of the same type.


 car_colors:
 - red
 - blue
 - green

content_copyUse code with caution.Yaml

 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

content_copyUse code with caution.Yaml

Q: Are dictionaries and lists in YAML ordered or unordered?

A:

 Dictionaries: Unordered. The order of key-value pairs doesn't affect the data.
 Lists: Ordered. The order of items matters.

Q: How do you add comments in YAML?

A: Use the hash symbol (#) for comments. Anything after # on a line is ignored.

# This is a comment
fruit: apple # This fruit is red

content_copyUse code with caution.Yaml

Example Data Comparison (XML, JSON, YAML):


Let's say you want to represent data about a server:

 XML:
 <server>
 <name>Server1</name>
 <ip>192.168.1.100</ip>
 </server>

content_copyUse code with caution.Xml

 JSON:
 {
 "server": {
 "name": "Server1",
 "ip": "192.168.1.100"
 }
 }

content_copyUse code with caution.Json

 YAML:
 server:
 name: Server1
 ip: 192.168.1.100

content_copyUse code with caution.Yaml

YAML is generally preferred for its readability and conciseness, making it ideal for Ansible playbooks.

Configuring Ansible Inventory


This section details how Ansible manages connections to multiple systems for orchestration tasks.

Ansible Architecture: Agentless Advantage

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:

 Simplified Deployment: No need to install or manage agents on each target system.


 Reduced Overhead: No agent-related resource consumption on target machines.

Inventory Files: Mapping Your Infrastructure

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

content_copyUse code with caution.Ini

Inventory Parameters

Each server entry in the inventory file can have various parameters associated with it, providing Ansible with
connection details. Key parameters include:

Default Description Parameter

N/A FQDN or IP address of the server ansible_host

ssh Connection type (ssh, winrm, local) ansible_connection

22 (SSH) Port used for connection ansible_port

root (Linux) Username used for remote connection ansible_user

N/A SSH password for the user (not recommended for production) ansible_ssh_pass

Example Inventory with Parameters:

[webservers]
web01 ansible_host=192.168.1.10 ansible_user=ubuntu
web02 ansible_host=192.168.1.11 ansible_user=ubuntu

content_copyUse code with caution.Ini

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 Cheat Sheet - Inventory Configuration


1. How does Ansible connect to multiple systems?
Ansible uses SSH (for Linux) or PowerShell Remoting (for Windows) to establish connectivity with target
servers, eliminating the need for agents.

2. What is the advantage of Ansible's agentless architecture?

 Simplified deployment: No agent installation or management on target machines.


 Reduced overhead: No additional resource consumption due to agents.

3. What is an Ansible Inventory file and what is it used for?

Ansible inventory files contain information about the target systems (hosts) Ansible manages. They define
which servers Ansible can connect to and control.

4. Where is the default Ansible inventory file located?

The default inventory file is located at /etc/ansible/hosts.

5. What is the format of an Ansible inventory file?

Inventory files use an INI-like format, similar to configuration files.

6. How are servers grouped in an inventory file?

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

content_copyUse code with caution.Ini

7. What is 'ansible_host' and what is it used for?

ansible_host is an inventory parameter that specifies the FQDN (Fully Qualified Domain Name) or IP address
of a target server.

8. List some other important Ansible inventory parameters:

 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

content_copyUse code with caution.Ini

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".

Introduction to Ansible Playbooks


This document provides a comprehensive overview of Ansible playbooks, the cornerstone of Ansible's
automation capabilities.

What are Playbooks?

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.

Playbook Structure: YAML Format

Playbooks are written in YAML (Yet Another Markup Language), a human-readable data serialization format.
Understanding YAML is crucial for working with playbooks.

Key YAML Concepts:

 Dictionaries: Key-value pairs, denoted by colons (e.g., name: Play One).


 Lists: Ordered collections of items, denoted by dashes (e.g., - command: uptime).
 Indentation: Crucial for defining hierarchy and structure within the playbook.

Playbook Components:

A playbook comprises one or more plays, each targeting a specific host or group of hosts.

1. Plays:

 Defined by a dash (-).


 Contains a set of properties:
o name: Descriptive name for the play.
o hosts: Target host(s) or group(s) for the play (retrieved from Ansible inventory).
o tasks: List of actions to perform on the defined hosts.

2. Tasks:

 Individual actions executed on target hosts.


 Defined as a list under the tasks property within a play.
 Examples of tasks:
o Executing commands or scripts.
o Installing packages.
o Managing services (starting, stopping, restarting).

3. Modules:

 The building blocks of tasks, defining specific actions.


 Ansible provides numerous modules for various functionalities (e.g., command, yum, service).
 Modules are invoked within tasks (e.g., - name: Start web server, service: name=httpd state=started).

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

content_copyUse code with caution.Yaml

Running a Playbook:

 Use the ansible-playbook command:


 ansible-playbook <playbook_name.yml>

content_copyUse code with caution.Bash

Additional Resources:

 Ansible Documentation: Comprehensive information on playbooks, modules, and more.


 Ansible Galaxy: A hub for sharing and downloading community-contributed playbooks and roles.

Conclusion:

This introduction provides a foundational understanding of Ansible playbooks. Mastering these concepts is
essential for effectively automating system administration and configuration management tasks.

Ansible Playbooks: Cheat Sheet


1. What are Ansible Playbooks?
Answer: Playbooks are the core of Ansible automation. They are essentially YAML files containing a set of
instructions (plays) that Ansible uses to automate tasks on target machines. Think of them as recipes for
Ansible to follow.

2. What is the purpose of a Playbook?

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.

3. What format are Playbooks written in?

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.

4. What are the key components of a Playbook?

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.).

5. Can you provide an example of a simple Playbook structure?

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

- name: Install Apache web server


apt:
name: apache2
state: present

- name: Start Apache


service:
name: apache2
state: started

content_copyUse code with caution.Yaml

6. How do you define the target hosts for a Play?

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.

7. What is the significance of the 'tasks' section in a Play?

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.

9. How do you run an Ansible Playbook?

Answer: You use the ansible-playbook command followed by the name of the playbook file:

ansible-playbook my_playbook.yml

content_copyUse code with caution.Bash

10. Where can I find more information about Ansible Playbooks and Modules?

Answer:

 Ansible Documentation: https://docs.ansible.com/ (The official documentation is the best resource)


 Ansible Galaxy: https://galaxy.ansible.com/ (Find community-contributed roles and playbooks)

Introduction to Ansible Modules


This section provides a comprehensive overview of Ansible modules, their categorization, and detailed
explanations of specific module examples.

What are Ansible Modules?

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

For a complete list and detailed documentation, visit docs.ansible.com.

Deep Dive into Specific Modules


Let's explore some commonly used Ansible modules in detail:

1. The command Module

This module executes commands on remote nodes.

Parameters:

 free form: Accepts the command to be executed as a string.


 chdir: Changes the working directory before executing the command.
 creates: Executes the command only if the specified file or directory doesn't exist.

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

content_copyUse code with caution.Yaml

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.

2. The script Module

This module transfers and executes local scripts on remote nodes.

Parameters:

 path to script: Specifies the local path to the script file.


 arguments: Passes arguments to the script.
Example Playbook:

---
- hosts: target_hosts
tasks:
- name: Execute a script on remote hosts
script: /path/to/local/script.sh --arg1 value1

content_copyUse code with caution.Yaml

Key Points:

 Simplifies script execution on multiple servers.


 Automates script transfer and execution.

3. The service Module

This module manages services on remote systems.

Parameters:

 name: Specifies the service name.


 state: Defines the desired state of the service (started, stopped, restarted).

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

content_copyUse code with caution.Yaml

Key Points:

 The service module requires a key-value pair input format.


 Uses idempotent actions like started, stopped, and restarted to ensure the desired state.
 Idempotency means running the playbook multiple times will result in the same state without
unintended side effects.

4. The lineinfile Module

This module manages lines within a file.

Parameters:

 path: Specifies the file to modify.


 line: The content to be added or modified.
Example Playbook:

---
- hosts: target_hosts
tasks:
- name: Add a DNS server to resolv.conf
lineinfile:
path: /etc/resolv.conf
line: "nameserver 8.8.8.8"

content_copyUse code with caution.Yaml

Key Points:

 Ensures the specified line is present in the file.


 If the line exists, no action is taken (idempotency).
 Useful for configuration file management.

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.

Ansible Modules Cheat Sheet


Q: What are Ansible modules?

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.

Q: How are Ansible modules categorized?

A: Ansible modules are categorized by functionality. Some key categories include:

 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).

Q: Where can I find a comprehensive list of Ansible modules?

A: Visit the official Ansible documentation at docs.ansible.com for a complete list and detailed information on
each module.

Q: Explain the command module and its key parameters.

A: The command module executes commands on remote nodes. Key parameters include:

 free form: Takes the command directly as a string.


o Example: command: date
 chdir: Changes the working directory before execution.
o Example: command: chdir=/etc cmd=ls -l
 creates: Executes the command only if the specified file or directory doesn't exist.
o Example: command: creates=/path/to/file touch /path/to/file

Q: What is the difference between free-form and parameterized module input?

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.

Q: What is the purpose of the script module?

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.

Q: How does the lineinfile module demonstrate idempotency?

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.

Q: Provide an example of using the lineinfile module.

A: To add a DNS server to /etc/resolv.conf:

- name: Add DNS server


lineinfile:
path: /etc/resolv.conf
line: "nameserver 8.8.8.8"

content_copyUse code with caution.Yaml

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.

1. What are Variables?

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:

 Hostname: server1.example.com, server2.example.com, ...


 Username: admin1, user2, ...
 Password: passwordA, passwordB, ...

2. Defining Variables

Ansible offers various ways to define variables:

2.1 Inventory File

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

content_copyUse code with caution.Yaml

Here, ansible_connection, ansible_ssh_user, and ansible_ssh_pass are all variables defining connection
parameters for the web.example.com host.

2.2 Playbook Variables

Variables can be defined directly within a playbook using the vars directive:

---
- hosts: webservers
vars:
dns_server: "192.168.1.1"
tasks:
# ... playbook tasks ...

content_copyUse code with caution.Yaml

2.3 Separate Variable Files

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.

2.4 Host Variable Files

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:

firewall_rule1: "allow tcp port 80"


firewall_rule2: "allow tcp port 443"

content_copyUse code with caution.Yaml

These variables become accessible within playbooks targeting web.example.com.

3. Using Variables (Jinja2 Templating)

Defining variables is only half the story; we need to use them within playbooks. Ansible leverages Jinja2
templating for this purpose.

3.1 Basic Usage

To access a variable's value, enclose its name within double curly braces {{ }}:

- name: Add DNS entry


lineinfile:
path: /etc/resolv.conf
line: "nameserver {{ dns_server }}"

content_copyUse code with caution.Yaml

When executed, Ansible replaces {{ dns_server }} with the value defined for the dns_server variable.

3.2 Example: Firewall Configuration

Consider a playbook configuring firewall rules:

- name: Configure firewall


hosts: webservers
tasks:
- name: Add rule 1
firewalld:
rule: "{{ firewall_rule1 }}"
permanent: yes
state: enabled

- name: Add rule 2


firewalld:
rule: "{{ firewall_rule2 }}"
permanent: yes
state: enabled

content_copyUse code with caution.Yaml

This playbook utilizes the firewall_rule1 and firewall_rule2 variables defined in the host variable file.

3.3 Quotation Marks

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.

Ansible Variables Cheat Sheet


Q1: What are variables in Ansible?

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.

Q2: Why are variables useful?

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.

Q3: Where can you define variables in Ansible?

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

content_copyUse code with caution.Yaml

 Playbook: Using the vars directive.


 ---
 - hosts: webservers
 vars:
 dns_server: "192.168.1.1"
 tasks:
 # ... playbook tasks ...

content_copyUse code with caution.Yaml

 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.

Q4: How do you use a variable in a playbook?

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 }}"
```

content_copyUse code with caution.

Q5: Do I need quotes when using variables in Jinja2 templates?


A5:

 Yes, if the variable starts the assignment: "{{ variable_name }}"


 No, if the variable is within a string: This is my {{ variable_name }}.

Q6: What is a good practice for organizing variables?

A6: Use host variable files to keep variables specific to a host separate and organized. This improves
readability and maintainability.

Q7: Where can I learn more about Jinja2 templating?

A7: Check out the "Jinja2 Templating for Absolute Beginners" course on CodeCloud.

Mastering Conditional Statements in Ansible


This section delves into the powerful world of conditional statements in Ansible, allowing you to craft dynamic
and versatile playbooks.

The Need for Conditionals

Imagine a scenario where you need to install Nginx on a variety of servers. Different operating systems rely on
different package managers:

 Debian-based systems utilize apt.


 Red Hat-based systems utilize yum.

Maintaining separate playbooks for each OS flavor can be cumbersome. Conditionals empower you to create a
single, unified playbook adaptable to different environments.

Introducing the when Statement

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:

- name: Task Description


<module_name>: ...
when: <condition>

content_copyUse code with caution.Yaml

Example: OS-Specific Package Installation

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"

- name: Install Nginx on Red Hat-based systems


yum:
name: nginx
state: present
when: ansible_os_family == "RedHat"

content_copyUse code with caution.Yaml

Explanation:

 We use the built-in ansible_os_family variable to determine the OS flavor.


 The == operator checks for equality.
 Each task is executed only if its corresponding when condition is met.

Logical Operators: or and and

Ansible provides logical operators to combine conditions for more complex scenarios:

 or: The task runs if at least one of the conditions is true.


 when: (ansible_os_family == "RedHat") or (ansible_os_family == "SUSE")

content_copyUse code with caution.Yaml

 and: The task runs only if all specified conditions are true.
 when: (ansible_os_family == "Debian") and (ansible_version == "16.04")

content_copyUse code with caution.Yaml

Conditionals within Loops

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

content_copyUse code with caution.Yaml

Explanation:

 We define a list of packages, each with a name and a required flag.


 The loop iterates over each package.
 The when statement ensures only packages marked as required: true are installed.
Leveraging Task Output in Conditions

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

- name: Send email if service is down


mail:
... # Email configuration
when: result.stdout.find("down") != -1

content_copyUse code with caution.Yaml

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.

Ansible Conditionals: Your Cheat Sheet


1. Why use conditionals in Ansible?

 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.

2. How do I use conditionals in Ansible?

 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>

content_copyUse code with caution.Yaml

3. Example: OS-specific package installation

 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"

content_copyUse code with caution.Yaml

4. What are common conditional operators?

 ==: Checks for equality (e.g., ansible_os_family == "Debian").


 !=: Checks for inequality (e.g., variable != "some_value").
 or: Task runs if at least one condition is true.
 and: Task runs only if all conditions are true.

5. How do I use conditionals within loops?

 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

content_copyUse code with caution.Yaml

6. How do I use the output of a previous task in a conditional?

 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

content_copyUse code with caution.Yaml

 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.

Mastering Loops in Ansible


This guide provides a comprehensive overview of loops in Ansible, including their use cases, syntax, and
different implementation methods.

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.

Basic Looping with loop

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.

Example: Creating Multiple Users

Let's consider creating multiple users on a system. Using the user module without a loop would involve
repetitive code:

- name: Create user Joe


user:
name: Joe
state: present

- name: Create user George


user:
name: George
state: present

# ... more user creation tasks ...

content_copyUse code with caution.Yaml

The loop directive simplifies this process:

- name: Create multiple users


user:
name: "{{ item }}"
state: present
loop:
- Joe
- George
- Ravi
# ... more usernames ...

content_copyUse code with caution.Yaml


Understanding item

Within the loop, each item from the list is accessible through the item variable. Visualizing this process can aid
understanding:

Module Execution item Value Task

user: name=Joe state=present Joe Task 1

user: name=George state=present George Task 2

user: name=Ravi state=present Ravi Task 3

... ... ...

Looping with Dictionaries

Loops are not limited to strings. You can iterate over a list of dictionaries, allowing for more complex data
structures.

- 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

content_copyUse code with caution.Yaml

Module Execution item Value Task

user: name=Joe uid=1001 state=present {'name': 'Joe', 'uid': 1001} Task 1

user: name=George uid=1002 state=present {'name': 'George', 'uid': 1002} Task 2

user: name=Ravi uid=1003 state=present {'name': 'Ravi', 'uid': 1003} Task 3

... ... ...

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}
]

content_copyUse code with caution.Json

Advanced Looping with with_ Directives


While loop handles basic iterations, Ansible provides more specialized looping mechanisms using with_
directives. These leverage lookup plugins to access and process data from various sources.

with_items

The with_items directive is functionally similar to loop and is often found in older playbooks.

Beyond with_items

Ansible offers a variety of with_ directives for specific tasks:

 with_files: Iterates over multiple files.


 with_url: Connects to multiple URLs.
 with_mongodb: Connects to multiple MongoDB databases.

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.

Ansible Loops Cheat Sheet


Q: Why use loops in Ansible playbooks?

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.

Q: How does the loop directive work?

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

content_copyUse code with caution.Yaml


 item variable: Inside the loop, each list item is accessible through the item variable.

Q: How can I visualize the loop process?

A: Imagine the loop breaking down into individual tasks:

Module Execution item Value Task

user: name=Joe state=present Joe Task 1

user: name=George state=present George Task 2

user: name=Ravi state=present Ravi Task 3

Q: How can I loop through a list of dictionaries?

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

content_copyUse code with caution.Yaml

 Access values: Use item.key (e.g., item.name, item.uid) to access specific values within each
dictionary.

Q: What is the difference between loop and with_items?

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.

Q: What are lookup plugins?

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.

Roles in Ansible: A Deep Dive


Introduction

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

The Need for 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.

Think of configuring a MySQL database server. The steps include:

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.

Benefits of Using Roles

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.

Working with Roles

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:

ansible-galaxy init my_mysql_role

content_copyUse code with caution.Bash

2. Using a Role in a Playbook

 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

content_copyUse code with caution.Yaml

3. Role Parameters

 Passing Variables: Provide custom values to role variables.


 ---
 - hosts: my_servers
 roles:
 - role: my_mysql_role
 mysql_user_name: custom_user

content_copyUse code with caution.Yaml

 Become Directive: Control privilege escalation for tasks within the role.
 ---
 - hosts: my_servers
 roles:
 - role: my_mysql_role
 become: true

content_copyUse code with caution.Yaml

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

content_copyUse code with caution.Bash

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

content_copyUse code with caution.Bash

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.

Ansible Roles: Your Cheat Sheet


Q: What are roles in Ansible?

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.

Q: Why use roles instead of just writing playbooks?

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.

Q: What's the structure of an Ansible role?

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

content_copyUse code with caution.

Q: How do I create a role?

A:

1. Manual: Create the directory structure yourself.


2. Ansible Galaxy init: Use ansible-galaxy init <role_name> for a basic template.

Q: How do I use a role in my playbook?

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

content_copyUse code with caution.Yaml

Q: Where can I find pre-built Ansible roles?

A: Ansible Galaxy (https://galaxy.ansible.com/) is a community hub for sharing roles.

Q: How do I use roles from Ansible Galaxy?

A:

1. Search: ansible-galaxy search <search_term>


2. Install: ansible-galaxy install <role_name> (installs to the default roles path)
3. Use in Playbook: Reference the role by name, like a locally created role.

Q: Can I customize role behavior?

A: Yes!

 Pass Variables: Provide specific values during role invocation.


 Use become Directive: Control privilege escalation for tasks within the role.

Example:

- hosts: my_servers
roles:
- role: my_mysql_role
become: true
mysql_user: 'custom_admin'

content_copyUse code with caution.Yaml

Key Commands to Remember:

 ansible-galaxy init <role_name>: Create a role skeleton.


 ansible-galaxy search <search_term>: Find roles on Ansible Galaxy.
 ansible-galaxy install <role_name>: Download a role from Ansible Galaxy.
 ansible-config dump --only roles_path: View the default roles installation path.
 ansible-galaxy list: List installed roles.

Ansible: Advanced Topics and Next Steps


Welcome to the Advanced Topics section! While this beginners course primarily focuses on foundational
concepts, this section provides a glimpse into Ansible's broader capabilities. We'll briefly cover several
advanced topics, outlining their significance and potential use cases. For detailed information and practical
implementation, refer to the official Ansible documentation.
I. Managing Windows with Ansible

Although Ansible's control machine requires Linux, it can effectively manage Windows targets, incorporating
them into your automation workflows.

Connecting to Windows Targets

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.

Setting Up WinRM on Windows

1. Install pywinrm Module: On your Ansible control machine (Linux), install the pywinrm module using
pip:
2. pip install "pywinrm==0.2.2"

content_copyUse code with caution.Bash

3. Configure WinRM on Windows Server: Ansible provides a PowerShell script,


ConfigureRemotingForAnsible.ps1, to simplify this process.
o Download the script from the Ansible documentation (Windows Support section).
o Run the script on the target Windows Server. This configures WinRM, allowing Ansible to
connect.

Authentication Modes

Ansible supports various authentication methods for WinRM, including:

 Basic Authentication
 Certificate-Based Authentication
 Kerberos
 NTLM

Refer to the Ansible documentation for detailed instructions on configuring each authentication mode.

II. Exploring Ansible Galaxy

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.

Benefits of Using Ansible Galaxy:

 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.

Using Roles from Ansible Galaxy:

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:

Description Example Pattern Type

Runs the playbook on multiple hosts specified explicitly. host1,host2,host3 Comma-Separated

Targets a specific group and an additional host. group1:children:webservers,host1 Groups & Hosts

Selects all hosts starting with "host". host* Wildcards

Matches all hosts with the ".company.com" domain


*.company.com Domain Suffix
suffix.

Refer to the Ansible documentation for a comprehensive list of pattern options and examples.

IV. Implementing Dynamic Inventory

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

content_copyUse code with caution.Bash

3. Dynamic Inventory Script: This script interacts with external systems (e.g., cloud providers, CMDBs)
to gather and return inventory data to Ansible.

Advantages:

 Automated Inventory Management: Eliminates manual updates to inventory files.


 Integration with External Systems: Seamlessly integrates with cloud platforms, configuration
management databases, and other inventory sources.

Available Scripts:

Ansible offers pre-built dynamic inventory scripts for various platforms, including:

 Cobbler
 HWS (Hardware State Manager)
 OpenStack

V. Developing Custom Modules

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:

1. Language: Custom modules are primarily written in Python.


2. Module Structure: Adhere to Ansible's module structure, including input parameters, execution logic,
and output formatting.
3. Placement: Place your custom module in the library directory within your Ansible project.

Resources for Module Development:

 Ansible Documentation: The official documentation provides a comprehensive guide on developing


modules, including templates and examples.
 "Building a Simple Module" Section: Within the Ansible Developer Guide, this section provides a
step-by-step walkthrough of creating a basic module.

Advantages of Custom Modules:

 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.

VI. Conclusion and Next Steps


Congratulations on completing the "Ansible for Absolute Beginners" course! You've gained a solid
understanding of Ansible's core concepts, empowering you to automate your infrastructure and application
deployments.

Continue your Ansible journey:

 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.

VII. Ansible Certification Course

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.

Ansible Cheat Sheet: Advanced Topics


1. How can Ansible manage Windows Servers?
Ansible, primarily run on a Linux control machine, can manage Windows servers as targets. It uses WinRM
(Windows Remote Management) to connect to Windows instead of SSH.

2. What is the process of setting up Ansible to manage a Windows Server?

 Install pywinrm: On the Ansible control machine (Linux), use:


 pip install "pywinrm==0.2.2"

content_copyUse code with caution.Bash

 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.

3. What is Ansible Galaxy?

Ansible Galaxy (https://galaxy.ansible.com/) is a free online hub for finding, sharing, and rating community-
developed Ansible roles.

4. How do you use Ansible Galaxy in your projects?

 Browse Roles: Explore the website to find relevant roles.


 Download Roles: Use the ansible-galaxy command-line tool to download roles into your project.
 Incorporate Roles: Include the downloaded roles in your Ansible playbooks.

5. What are Ansible Patterns and how are they useful?

Ansible patterns provide flexible ways to select target hosts for tasks, going beyond basic hostnames or groups.

Examples:

 Comma-Separated: host1,host2,host3 (Multiple hosts)


 Groups & Hosts: group1:children:webservers,host1 (Specific group and an additional host)
 Wildcards: host* (All hosts starting with "host")
 Domain Suffix: *.company.com (Hosts with ".company.com" domain)

6. What is Dynamic Inventory in Ansible?

Dynamic inventory enables Ansible to fetch inventory information from external sources instead of relying
solely on static inventory files.

7. How do you use dynamic inventory?

 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

content_copyUse code with caution.Bash

 Script's Role: The script interacts with external systems like cloud providers or CMDBs, gathers
inventory data, and provides it to Ansible.

8. Can you create custom Ansible modules?

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?

 Language: Use Python.


 Structure: Follow Ansible's module structure guidelines (input parameters, execution logic, output
format).
 Location: Place your custom module in the library directory within your Ansible project.

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.

Ansible for Absolute Beginners: A Professional Summary


This comprehensive course equips IT professionals with the essential knowledge and practical skills to
automate infrastructure management using Ansible.

Starting with the fundamentals, the course covers:

 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.

By the end of this course, participants will be able to:

 Automate routine system administration tasks.


 Deploy and configure applications consistently across multiple servers.
 Manage complex infrastructure deployments spanning cloud and on-premises environments.
 Leverage Ansible Galaxy to accelerate automation projects and collaborate with the community.
 Confidently apply Ansible's advanced features to tackle sophisticated automation challenges.

This course is ideal for:

 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.

Ansible KodeKloud Course: Professional Summary of Commands


This document provides a professional summary of essential commands covered in the Ansible KodeKloud
course, categorized for easy reference.

1. Setting Up Your Ansible Environment

 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

2. Working with Ansible Inventory

 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.

3. Essential Ansible Commands


 Running Playbooks: ansible-playbook <playbook_name.yml>
 Testing Connectivity: ansible <hostname> -m ping -i <inventory_file>
 Gathering Facts: ansible <hostname> -m setup -i <inventory_file>
 Managing Packages:
o Installation: ansible <hostname> -m yum -a "name=<package_name> state=present" -i
<inventory_file> (adjust package manager for different OS)
o Removal: ansible <hostname> -m yum -a "name=<package_name> state=absent" -i
<inventory_file>
 Managing Services:
o Starting/Stopping: ansible <hostname> -m service -a "name=<service_name>
state=started/stopped" -i <inventory_file>
 Managing Files:
o Copying: ansible <hostname> -m copy -a "src=<source_file> dest=<destination_path>" -i
<inventory_file>
o Creating Directories: ansible <hostname> -m file -a "path=<directory_path> state=directory
mode=0755" -i <inventory_file>

4. Ansible Galaxy

 Searching for Roles: ansible-galaxy search <search_term>


 Installing Roles: ansible-galaxy install <role_name>
 Listing Installed Roles: ansible-galaxy list
 Role Installation Path: ansible-config dump --only roles_path

5. Advanced Ansible Commands

 Dynamic Inventory: ansible-playbook -i <inventory_script.py> <playbook_name.yml>


 Managing Windows Hosts:
o Install pywinrm (control machine): pip install "pywinrm==0.2.2"
o Configure WinRM (target Windows Server): Use ConfigureRemotingForAnsible.ps1 script.

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.

You might also like