Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
21 views25 pages

Ansible Notes

The document provides a comprehensive guide on Ansible, covering installation, configuration, and key concepts such as playbooks, inventory, and modules. It explains how Ansible operates in an agentless manner using SSH for secure communication, and highlights its use cases in configuration management, application deployment, and orchestration. Additionally, it discusses best practices, security measures, and the challenges faced by beginners in learning Ansible.

Uploaded by

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

Ansible Notes

The document provides a comprehensive guide on Ansible, covering installation, configuration, and key concepts such as playbooks, inventory, and modules. It explains how Ansible operates in an agentless manner using SSH for secure communication, and highlights its use cases in configuration management, application deployment, and orchestration. Additionally, it discusses best practices, security measures, and the challenges faced by beginners in learning Ansible.

Uploaded by

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

ANSIBLE NOTES BY

NEXTOPS

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Installation of Ansible:

1. sudo apt update


2. sudo apt upgrade
3. sudo apt install -y software-properties-common
4. sudo add-apt-repository --yes --update ppa:ansible/ansible
5. sudo apt install -y ansible

Configuration on server:

6. Generate the ssh-keys on ansible server


ssh-keygen -t rsa -b 4096 -C "[email protected]"
7. Login to client machines and configure the ip and hostnames using hostnamectl set-
hostname “new hostname”
8. On the clients reset root account password using passwd command
9. Edit /etc/ssh/sshd_config and uncomment following lines
a. PermitRootLogin yes
b. PasswordAuthentication yes
c. PublicKeyAuthenction yes
10. Copy the keys to remote machines for authentication during playbook execution
ssh-copy-id root@remote_host_ip
11. Edit the inventory file and add the client machines in the list
12. Run the ad-hoc commands to test connectivity.

Introduction to Ansible:

Definition: Ansible is an open-source automation tool that simplifies configuration


management, application deployment, and task automation.

Purpose: It aims to streamline IT tasks, reduce complexity, and enhance scalability by


automating repetitive tasks.

1. Key Concepts:

Playbooks:

Ansible uses playbooks written in YAML format.

Playbooks define a set of tasks, roles, and hosts to execute automation.

Inventory:

An inventory file lists the hosts on which Ansible will operate.

It can be static or dynamic, depending on the requirements.

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Modules:

Ansible modules are small programs that carry out tasks on managed hosts.

Modules can be executed directly from the command line or within playbooks.

Tasks:

Tasks define the individual steps to be performed on the hosts.

Playbooks consist of one or more tasks.

Roles:

Roles are a way to organize playbooks and share them with others.

They encapsulate the organization and structure of playbooks.

2. How Ansible Works:

Agentless:

Ansible operates in an agentless manner, meaning no agent needs to be installed on the


managed hosts.

It communicates with hosts through SSH, making it simple to set up and manage.

SSH Communication:

Ansible uses SSH for secure communication with managed hosts.

Hosts need SSH access, and Ansible uses this access to execute tasks remotely.

Idempotency:

Ansible ensures idempotency, meaning that running a playbook multiple times will have the
same result as running it once.

Parallel Execution:

Ansible can execute tasks on multiple hosts in parallel, making it efficient for large-scale
automation.

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
4. Ad-hoc Commands:

Ansible allows the execution of ad-hoc commands for quick tasks without creating a
playbook.

Example: ansible <hostname> -m <module> -a "<arguments>"

5. Dynamic Inventory:

Ansible supports dynamic inventories, allowing hosts to be defined dynamically.

This is useful for environments with frequently changing infrastructure.

6. Variables:

Ansible uses variables to store and reuse values.

Variables can be defined in playbooks, roles, or external files.

7. Ansible Galaxy:

Ansible Galaxy is a hub for sharing and finding reusable Ansible content, including roles,
playbooks, and collections.

8. Use Cases:

Configuration Management:

Automate and manage configurations across multiple servers.

Application Deployment:

Deploy and update applications consistently across different environments.

Orchestration:

Coordinate complex tasks and workflows involving multiple servers.

9. Ansible Tower:

Ansible Tower is a web-based interface and REST API for Ansible.

It provides a dashboard, role-based access control, job scheduling, and more.

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
10. Best Practices:

Modularity:

Organize playbooks into roles for better maintainability.

Documentation:

Clearly document playbooks, roles, and tasks for easier collaboration.

Testing:

Test playbooks in a non-production environment before deploying to production.

11. Security:

Secure Communication:

Ensure secure communication channels, especially SSH access.

Vault:

Ansible Vault allows the encryption of sensitive data in playbooks.

12. Challenges:

Learning Curve:

Beginners may find Ansible's syntax and concepts challenging initially.

Complexity for Small Environments:

For small setups, Ansible might seem like overkill compared to simpler tools.

13. Integration with Other Tools:

Ansible can integrate with tools like Jenkins, Docker, and various cloud platforms to enhance
automation capabilities.

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Ansible Ad-hoc Commands:
Ansible ad-hoc commands are one-liners used for quick tasks without the need to create a
playbook. These commands are executed directly from the command line and are helpful for
performing tasks such as gathering information, making quick configurations, or
troubleshooting. Ad-hoc commands are particularly useful for tasks that don't require the
complexity of a playbook.

Syntax:

ansible <target_host_pattern> -m <module_name> -a "<module_arguments>"

• <target_host_pattern>: Specifies the hosts or groups on which to run the command.

• <module_name>: Specifies the Ansible module to use for the task.

• <module_arguments>: Defines the arguments specific to the chosen module.

Examples of Ansible Ad-hoc Commands:

Ping Test:

Checks if hosts are reachable and can be managed by Ansible.

ansible all -m ping

Execute a Shell Command:

Runs a simple shell command on remote hosts.

ansible web_servers -m shell -a "uptime"

Install a Package:

Installs a package on remote hosts.

ansible app_servers -m apt -a "name=nginx state=present" # For Debian/Ubuntu systems

Copy Files:

Copies a file from the local machine to remote hosts.

ansible web_servers -m copy -a "src=/path/to/local/file.txt dest=/path/on/remote/"

Retrieve Facts:

Gathers system facts from remote hosts.

ansible db_servers -m setup

Create a User:

Creates a user on remote hosts.

ansible all -m user -a "name=john password=<encrypted_password>"

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Restart Service:

Restarts a service on remote hosts.

ansible web_servers -m service -a "name=nginx state=restarted"

Check Disk Space:

Checks available disk space on remote hosts.

ansible all -m command -a "df -h"

Execute a Python Script:

Executes a Python script on remote hosts.

ansible all -m script -a "/path/to/script.py arg1 arg2"

Create a Directory:

Creates a directory on remote hosts.

ansible app_servers -m file -a "path=/path/to/directory state=directory"

Ansible Playbooks:
Definition:

An Ansible playbook is a YAML file containing a set of tasks, roles, and other configurations
that define the automation workflow. Playbooks are used to orchestrate and describe the
steps that Ansible should take on remote hosts. They are a key component of Ansible for
defining automation tasks in a readable and reusable format.

Example Playbook:

Let's consider a simple example where we want to create a playbook to deploy a basic web
server on multiple hosts.

---

- name: Deploy Web Server

hosts: web_servers

become: yes # Run tasks with elevated privileges (sudo)

tasks:

- name: Update Package Cache

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
apt:

update_cache: yes

when: ansible_os_family == 'Debian' # Condition to execute the task on Debian-based


systems

- name: Install Apache Web Server

apt:

name: apache2

state: present

when: ansible_os_family == 'Debian'

- name: Start Apache Service

service:

name: apache2

state: started

when: ansible_os_family == 'Debian'

- name: Enable Apache Service on Boot

service:

name: apache2

enabled: yes

when: ansible_os_family == 'Debian'

Tasks Section:

Task 1: Update Package Cache

Uses the apt module to update the package cache on Debian-based systems.

Task 2: Install Apache Web Server

Uses the apt module to install the Apache2 package.

Task 3: Start Apache Service

Uses the service module to start the Apache2 service.

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Task 4: Enable Apache Service on Boot

Uses the service module to enable the Apache2 service to start on boot.

Conditions (when):

Each task includes a condition (when) to check the operating system family. This ensures
that tasks are only executed on Debian-based systems.

Ansible Tasks:

In Ansible, a task is the smallest unit of work in a playbook. Tasks define a set of actions to be
performed on remote hosts, and they are executed sequentially. Each task corresponds to a
specific module, and Ansible modules are responsible for carrying out the actual work on the
target hosts. Tasks are defined in YAML format within a playbook.

Key Components of a Task:

1. Name:

• A descriptive name for the task, making playbooks more readable and
facilitating documentation.

2. Module:

• Specifies the Ansible module to be used for the task. Modules are small,
reusable components that perform specific actions on managed hosts.

3. Arguments:

• Defines the arguments required by the module to carry out the task. These
arguments are specific to the chosen module.

4. Conditionals:

• Allows tasks to be executed based on specific conditions. The when keyword is


commonly used for conditional execution.

5. Loops:

• Enables the repetition of tasks using loops. This is achieved using the loop
keyword, and it allows tasks to be executed multiple times with different
parameters.

6. Handlers:

• Handlers are special tasks that are only executed if triggered by other tasks.
They are defined separately in the playbook and are often used for restarting
services or performing similar actions.

Example of an Ansible Task:

---

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
- name: Install and Start Apache

hosts: web_servers

tasks:

- name: Update Package Cache

apt:

update_cache: yes

when: ansible_os_family == 'Debian'

- name: Install Apache

apt:

name: apache2

state: present

when: ansible_os_family == 'Debian'

- name: Start Apache Service

service:

name: apache2

state: started

when: ansible_os_family == 'Debian'

In this example:

• The playbook is named "Install and Start Apache" and targets hosts in the
"web_servers" group.

• Three tasks are defined sequentially:

1. Update the package cache (only for Debian-based systems).

2. Install the Apache package (only for Debian-based systems).

3. Start the Apache service (only for Debian-based systems).

Each task uses the apt and service modules, and conditions (when) ensure that tasks are
executed only on the appropriate operating systems.

Conditional Execution with "when":

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
---

- name: Ensure a Directory Exists

hosts: all

tasks:

- name: Create Directory on Linux

ansible.builtin.file:

path: /my/directory

state: directory

when: "ansible_system == 'Linux'"

- name: Create Directory on Windows

ansible.windows.win_file:

path: C:\my\directory

state: directory

when: "ansible_system == 'Windows'"

In this example, the playbook creates a directory based on the operating system. The when
keyword ensures that each task is executed only if the specified condition is met.

Using Loops:

---

- name: Ensure Multiple Users Exist

hosts: all

tasks:

- name: Create Users

ansible.builtin.user:

name: "{{ item }}"

state: present

loop:

- alice

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
- bob

- Charlie

This example uses a loop to create multiple users. The ansible.builtin.user module is
executed for each item in the loop, creating three users: Alice, Bob, and Charlie.

Ansible Modules:
Ansible modules are standalone scripts that Ansible uses to perform tasks on remote
systems. They are the building blocks of playbooks and are responsible for carrying out
various actions, such as installing packages, copying files, managing services, and more.
Modules are executed on the target hosts and are designed to be idempotent, meaning they
can be run multiple times without changing the system's state if the desired state is already
achieved.

Key Characteristics of Ansible Modules:

Idempotency:

Modules are designed to ensure idempotency, meaning the result of executing a module is
the same regardless of how many times it is run.

Parametrized:

Modules are parametrized, accepting arguments that define the desired state or action to
be taken on the target system.

Task Execution:

Modules are used within Ansible tasks in playbooks to define the specific actions to be
performed on the managed hosts.

Platform Independence:

Modules abstract underlying system differences, making playbooks portable across different
operating systems.

Extensibility:

Ansible allows users to develop custom modules to extend functionality beyond the built-in
modules.

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Variables in Ansible Playbooks
Variables in Ansible playbooks are used to store and reference data that can be reused
throughout the playbook. They provide a way to make playbooks more flexible, reusable, and
adaptable to different scenarios. Variables can be defined at various levels in Ansible, such
as playbook level, role level, or even in external files. They can store simple values like
strings and numbers, as well as more complex structures like lists and dictionaries.

Types of Variables:

Playbook Variables:

Variables defined at the playbook level using the vars keyword.

Host Variables:

Variables specific to a particular host or group of hosts. They are defined in the inventory file
or in separate host-specific variable files.

Fact Variables:

Automatically collected information about the target system, such as OS details, IP


addresses, and hardware information.

Registered Variables:

Variables that store the output of a task for later use in the playbook.

Handlers in Ansible:
Handlers in Ansible are special tasks that are only executed when notified by other tasks.
They are used to respond to changes in the system, such as restarting a service or taking
other actions, only when necessary. Handlers provide a way to orchestrate specific actions in
response to events triggered during playbook execution.

Key Characteristics of Handlers:

1. Definition:

• Handlers are defined separately from tasks in the playbook and are placed in a
dedicated handlers section.

2. Name:

• Each handler has a name, similar to tasks. The name is used when notifying
the handler from other tasks.

3. Triggers:

• Handlers are triggered by tasks using the notify keyword. When a task changes
the system state and notifies a handler, the handler is queued for execution.

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
4. Execution:

• Handlers are executed at the end of a playbook run, after all tasks have been
processed. This ensures that actions requiring coordination, such as
restarting a service, are only performed once.

5. Idempotency:

• Like tasks, handlers are designed to be idempotent. They are executed only if
notified and only once, even if multiple tasks notify the same handler.

6. Syntax:

• Handlers are defined in the handlers section of the playbook, typically at the
end of the file.

handlers:

- name: Restart Apache

service:

name: apache2

state: restarted

Example of Using Handlers:

Consider a playbook that installs and configures an Apache web server. If the Apache
configuration is modified, you want to ensure that the Apache service is restarted. Handlers
are perfect for this scenario.

---

- name: Install and Configure Apache

hosts: web_servers

tasks:

- name: Install Apache

apt:

name: apache2

state: present

- name: Configure Apache

template:

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
src: templates/apache.conf.j2

dest: /etc/apache2/apache2.conf

notify: Restart Apache # Notifying the handler

handlers:

- name: Restart Apache

service:

name: apache2

state: restarted

In this example:

• The Configure Apache task uses a template module to update the Apache
configuration file.
• The notify: Restart Apache line notifies the Restart Apache handler when the
configuration is updated.
• The Restart Apache handler, defined in the handlers section, restarts the Apache
service.

The key benefit of using handlers is that the restart of the Apache service only occurs if the
configuration has changed, reducing unnecessary service restarts.

Triggering Handlers:

Handlers are triggered using the notify keyword in tasks. For example:

---

- name: Trigger Handler

hosts: web_servers

tasks:

- name: Update Configuration

template:

src: templates/config.j2

dest: /etc/myapp/config.conf

notify: Reload My App # Notify the handler

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
handlers:

- name: Reload My App

command: /usr/bin/myappctl reload

In this example, the Update Configuration task notifies the Reload My App handler, which
executes the command to reload the application.

Roles in Ansible Playbooks:


Roles in Ansible provide a way to organize and structure playbooks, making them more
modular, reusable, and easier to maintain. A role is essentially a collection of playbooks,
variables, tasks, and other files organized in a specific directory structure. Roles help in
promoting best practices such as separation of concerns and code reuse. They are
particularly useful when dealing with complex infrastructure configurations.

Key Components of an Ansible Role:

Directory Structure:

Ansible expects roles to follow a specific directory structure. A minimal role structure looks
like this:
my_role/

├── tasks/

│ └── main.yml

├── handlers/

│ └── main.yml

├── templates/

├── files/

├── vars/

│ └── main.yml

├── defaults/

│ └── main.yml

├── meta/

│ └── main.yml

└── README.md

tasks/main.yml:

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
This file contains the main list of tasks that the role will perform. It's the heart of the
role.

handlers/main.yml:
Handlers are special tasks that get triggered by other tasks and are defined in this
file.

templates/:
This directory contains Jinja2 template files that can be used with the template
module.

files/:
Static files that can be copied to the managed hosts.

vars/main.yml:
Variable definitions specific to the role.

defaults/main.yml:
Default variable values for the role. These can be overridden by users.

meta/main.yml:
Metadata about the role, including dependencies.

README.md:
Documentation for the role, providing information on usage, variables, and other
relevant details.

Creating and Using Roles:


Creating a Role:

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Ansible provides a command-line tool to create a new role. For example:
ansible-galaxy init my_role
Using a Role in a Playbook:
Once a role is created, it can be included in a playbook like this:
---
- name: Example Playbook with Role
hosts: web_servers
roles:
- my_role
Role Dependencies:
Roles can depend on other roles. Dependencies are specified in the meta/main.yml
file.
---
dependencies:
- { role: another_role }
Variables and Overrides:
Role variables are defined in the vars/main.yml file and can be overridden in the
playbook.
Executing Playbook with Roles:
Playbooks with roles can be executed using the ansible-playbook command.
ansible-playbook -i inventory.ini my_playbook.yml

In Ansible, a vault refers to a secure way of storing sensitive information such as


passwords, secret keys, and other confidential data. Ansible Vault is a feature that
allows you to encrypt and decrypt files containing sensitive data, ensuring that the
information is protected during storage and transmission.

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Key Features of Ansible Vault:
Encryption:
Ansible Vault encrypts sensitive data files using strong encryption algorithms,
securing them from unauthorized access.
Decryption:
Ansible Vault provides commands to decrypt the encrypted files when needed,
making the data readable for authorized users.
File Format:
Encrypted files are typically saved in YAML format, just like regular Ansible files, but
with the encrypted content.
Integration with Playbooks:
Encrypted files can be seamlessly integrated into Ansible playbooks. Ansible
automatically decrypts these files during playbook execution if the necessary
credentials are provided.

Using Ansible Vault:


Steps to follow to test ansible vault with following example
Install pip3 package
apt install pip3

Install passlib library to support encryption with latest python version


pip3 install passlib

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Method1: Encrypting entire playbook with vault
create a playbook with following code as create_user1.yaml

---
- name: Create users
hosts: testservers
remote_user: root
vars:
secret: Passw0rd123

tasks:
- name: creating a user account
user:
name: user1
password: "{{ secret | password_hash('sha512') }}"
state: present

Encrypt the entire playbook using following command


ansible-vault encrypt create_user1.yaml

Run the playbook using following command


ansible-playbook create_user1.yaml --ask-vault-pass

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Method2: Encrypting only sensitive data in separate file and using it in main
playbook
Create a new playbook named create_user2.yaml

---
- name: Create users
hosts: testservers
remote_user: root
vars_files:
- secret.yml

tasks:
- name: creating a user account
user:
name: user2
password: "{{ secret | password_hash('sha512') }}"
state: present

Create another file named secret.yaml and store your password in that as follows

secret: Secure*123

Now encrypt the secret.yaml with ansible-vault command


ansible-vault encrypt secret.yaml
Enter the password and note down this password somewhere.

When running this play book, use the following command


ansible-playbook create_user2.yaml --ask-vault-pass

Method3: Storing vault password in a file approach


Create a plain text file named vault_pass.txt and write your preferred password in it
vaultPass@123

When executing the playbook use following command, so you won’t be prompted for
password.
ansible-playbook create_user2.yaml --vault-password-file vault_pass.txt

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
Other vault commands
ansible-vault create <file_name>
ansible-vault encrypt <file_name>
ansible-vault decrypt <file_name>
ansible-vault edit <file_name>
ansible-vault view <file_name>
ansible-vault rekey <file_name>

Advantages of Ansible Vault:


Security: Protects sensitive information by encrypting it before storing or
transmitting it.
Integration: Seamlessly integrates with Ansible playbooks and variables.
Flexibility: Allows you to use various methods for providing the vault password,
depending on your security and convenience requirements.

Ansible Inventory File:


In Ansible, the inventory file is a crucial component that defines the hosts and
groups of hosts on which Ansible will operate. The inventory file is used to specify the
target machines for playbook execution and ad-hoc commands. It is a simple text
file, usually named inventory or hosts, and can be customized to organize hosts into
groups, define variables, and set additional parameters.
Basic Structure:
[web_servers]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11

[database_servers]
db1 ansible_host=192.168.1.20

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
db2 ansible_host=192.168.1.21

[load_balancers]
lb1 ansible_host=192.168.1.30
In this example:
• [web_servers], [database_servers], and [load_balancers] are group names.
• web1, web2, db1, db2, and lb1 are hostnames.
• ansible_host is an inventory variable specifying the IP address of each host.
Common Inventory Patterns:
1. Host Aliases:
[web_servers]
web1 ansible_host=192.168.1.10 ansible_user=ubuntu

[database_servers]
db1 ansible_host=192.168.1.20 ansible_user=centos
2. Group Variables:
[web_servers]
web1 ansible_host=192.168.1.10
web2 ansible_host=192.168.1.11

[database_servers]
db1 ansible_host=192.168.1.20
db2 ansible_host=192.168.1.21

[all:vars]
ansible_user=admin
3. Nested Groups:

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
[web_servers]
web1 ansible_host=192.168.1.10

[database_servers]
db1 ansible_host=192.168.1.20

[production:children]
web_servers
database_servers
4. Inventory Ranges

[web_servers]

web[1:3] ansible_host=192.168.1.[10:12]

Inventory Variables:

• Variables can be assigned to hosts or groups within the inventory file.


• Variables are defined using the key-value syntax.
• Common variables include ansible_user, ansible_ssh_pass,
ansible_ssh_private_key_file, etc.
Dynamic Inventories:
• Ansible supports dynamic inventories generated by scripts, allowing for more
flexibility in large or dynamic environments.
• Dynamic inventories can retrieve information from various sources like cloud
providers, CMDBs, or custom databases.
Specifying the Inventory in Playbooks:
• The inventory file is specified when running Ansible playbooks or ad-hoc
commands using the -i option.
ansible-playbook -i inventory.ini my_playbook.yml
Default Locations:

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]
• Ansible looks for the inventory file in default locations, including
/etc/ansible/hosts and ./hosts. The default location can be overridden using
the -i option.
Using Patterns:
• Ansible allows using patterns to select hosts based on certain criteria. For
example:
ansible web_servers -m ping # Run on hosts in the 'web_servers' group
ansible production -m ping # Run on hosts in the 'production' group

Website: https://www.nextops.in, YouTube: https://www.youtube.com/c/nextopsvideos


WhatsApp: +91 73309 77091, Email: [email protected]

You might also like