0% found this document useful (0 votes)
26 views18 pages

Comprehensive Guide To Ansible

Uploaded by

kanthu256
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)
26 views18 pages

Comprehensive Guide To Ansible

Uploaded by

kanthu256
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/ 18

DevOps Shack

Comprehensive Guide to Ansible


Click Here To Enrol To Batch-6 | DevOps & Cloud DevOps

Introduction to Ansible
What is Ansible?

Ansible is an open-source automation tool used for configuration management,


application deployment, task automation, and IT orchestration. It enables IT
professionals to automate repetitive tasks, manage large-scale environments
efficiently, and ensure consistent configurations across multiple servers.

Key Features of Ansible

1. Agentless Architecture: Ansible does not require any software or agent to be


installed on the nodes it manages. It uses SSH for communication, which simplifies
setup and reduces overhead.
2. Declarative Language: Ansible uses a simple, human-readable language called YAML
(YAML Ain't Markup Language) to define automation tasks. This makes it easy for
users to write and understand playbooks.
3. Idempotency: Ansible ensures that a task achieves the same result regardless of the
number of times it is run. This means you can apply a playbook repeatedly without
changing the outcome after the initial application.
4. Extensible: Ansible supports a wide range of modules for various tasks and allows
users to create custom modules and plugins as needed.
Use Cases of Ansible

1. Configuration Management: Automate the configuration of systems and ensure


consistency across environments.
2. Application Deployment: Streamline the deployment of applications and services,
reducing manual effort and minimizing errors.
3. Orchestration: Coordinate complex multi-tier deployments and manage
dependencies between systems.
4. Provisioning: Automate the setup of infrastructure resources such as virtual
machines, containers, and cloud services.

Benefits of Using Ansible

1. Simplicity and Ease of Use: Ansible is designed to be simple and easy to use, with a
minimal learning curve. Its straightforward syntax and clear structure make it
accessible to beginners and experienced users alike.
2. Powerful Automation Capabilities: Ansible can automate a wide range of tasks,
from basic system configuration to complex application deployments and
orchestration.
3. Scalability: Ansible can scale to manage thousands of nodes, making it suitable for
both small and large-scale environments.
4. Community and Ecosystem: Ansible has a large and active community that
contributes to its development and provides support. The extensive ecosystem of
modules, roles, and plugins enhances its capabilities and adaptability.

Setting Up Ansible
Installing Ansible

Ansible can be installed on various operating systems, including Linux, macOS, and
Windows. The following sections provide instructions for installing Ansible on
different platforms.

Installing Ansible on Linux

For most Linux distributions, Ansible can be installed using the package manager.
Below are the steps for installing Ansible on some popular Linux distributions.

Ubuntu/Debian:

sudo apt update


sudo apt install ansible
CentOS/RHEL:

sudo yum install epel-release


sudo yum install ansible

Installing Ansible on macOS

On macOS, Ansible can be installed using Homebrew:

brew install ansible

Installing Ansible on Windows

On Windows, Ansible can be installed using the Windows Subsystem for Linux (WSL).
Here are the steps:

1. Enable WSL: Open PowerShell as Administrator and run:

wsl --install

2. Install a Linux distribution: For example, Ubuntu.


3. Install Ansible on WSL: Open the WSL terminal and run:
4. sudo apt update
sudo apt install ansible

Verifying the Installation

To verify that Ansible is installed correctly, run:

ansible --version
This command should display the installed version of Ansible and other related
information.

Ansible Basics
Ansible Inventory

Ansible inventory is a file that lists the hosts and groups of hosts that Ansible will
manage. By default, Ansible looks for the inventory file at /etc/ansible/hosts, but
you can specify a different inventory file using the -i option.

Example of an Inventory File:

# /etc/ansible/hosts
[webservers]
web1.example.com
web2.example.com

[dbservers]
db1.example.com
db2.example.com
Ansible Modules

Ansible modules are the building blocks of Ansible playbooks. They are reusable
scripts that perform specific tasks such as installing packages, copying files, and
managing services.

Example of Using a Module:

ansible all -m ping -i inventory.ini


This command uses the ping module to check the connectivity of all hosts listed in
the inventory.ini file.

Ansible Ad-Hoc Commands

Ad-hoc commands allow you to run a single task on one or more hosts without
writing a playbook. They are useful for quick tasks or troubleshooting.

Example of an Ad-Hoc Command:

ansible webservers -m yum -a "name=httpd state=present" -i inventory.ini


This command installs the httpd package on all hosts in the webservers group.

Ansible Configuration File

Ansible's behavior can be customized using a configuration file (ansible.cfg). This


file allows you to set various options, such as the default inventory location, SSH
connection settings, and module configuration.

Example of an Ansible Configuration File:

[defaults]
inventory = ./inventory
remote_user = ansible
private_key_file = ~/.ssh/id_rsa
host_key_checking = False
retry_files_enabled = False

Managing Ansible Inventory with Dynamic Inventory Scripts

Ansible supports dynamic inventory scripts, which allow you to generate inventory
data dynamically from external sources such as cloud providers, CMDBs, and
monitoring systems.

Example of Using a Dynamic Inventory Script:

ansible-playbook -i dynamic_inventory.py playbook.yml


Ansible Playbooks
Ansible playbooks are YAML files that define a series of tasks to be executed on
specified hosts. Playbooks are more powerful and flexible than ad-hoc commands,
allowing you to define complex automation workflows.

Structure of a Playbook

A playbook consists of one or more plays. Each play specifies a set of tasks to be
executed on a group of hosts.

Example of a Simple Playbook:

---
- name: Install and start Apache
hosts: webservers
become: yes

tasks:
- name: Install Apache
yum:
name: httpd
state: present

- name: Start Apache service


service:
name: httpd
state: started

Variables in Playbooks

Variables allow you to parameterize your playbooks, making them more flexible and
reusable.

Example of Using Variables:

---
- name: Install and start Apache
hosts: webservers
become: yes

vars:
httpd_package: httpd
httpd_service: httpd

tasks:
- name: Install Apache
yum:
name: "{{ httpd_package }}"
state: present

- name: Start Apache service


service:
name: "{{ httpd_service }}"
state: started

Handlers

Handlers are tasks that are triggered by other tasks. They are typically used to restart
services when a configuration file changes.

Example of Using Handlers:

---
- name: Install and configure Apache
hosts: webservers
become: yes

tasks:
- name: Install Apache
yum:
name: httpd
state: present

- name: Copy Apache config file


copy:
src: /path/to/httpd.conf
dest: /etc/httpd/conf/httpd.conf
notify: Restart Apache

handlers:
- name: Restart Apache
service:
name: httpd
state: restarted

Conditionals

Conditionals allow you to run tasks only when certain conditions are met.

Example of Using Conditionals:

---
- name: Install Apache on CentOS
hosts: webservers
become: yes

tasks:
- name: Install Apache
yum:
name: httpd
state: present
when: ansible_os_family == "RedHat"

Loops

Loops allow you to run a task multiple times with different parameters.
Example of Using Loops:

---
- name: Install multiple packages
hosts: webservers
become: yes

tasks:
- name: Install packages
yum:
name: "{{ item }}"
state: present
loop:
- httpd
- mysql-server
- php

Delegation

Delegation allows you to execute tasks on a different host than the one defined in
the playbook.

Example of Using Delegation:

---
- name: Gather facts from web servers
hosts: webservers
become: yes
gather_facts: no

tasks:
- name: Gather facts from all web servers
setup:
delegate_to: localhost

Notifications and Handlers

Handlers are special tasks that run when triggered by other tasks. They are typically
used to restart services when a configuration file changes.

Example of Using Handlers:

---
- name: Configure web server
hosts: webservers
become: yes

tasks:
- name: Install Nginx
yum:
name: nginx
state: present
- name: Deploy Nginx configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: Restart Nginx

handlers:
- name: Restart Nginx
service:
name: nginx
state: restarted

Roles

Roles allow you to organize your playbooks into reusable components. Each role has
a standard directory structure and can include tasks, handlers, variables, templates,
and files.

Example of a Role Directory Structure:

roles/
common/
tasks/
main.yml
handlers/
main.yml
templates/
...
files/
...
vars/
main.yml
defaults/
main.yml
meta/
main.yml
Example of Using a Role in a Playbook:

---
- name: Setup web servers
hosts: webservers
roles:
- common
- web

Ansible Galaxy

Ansible Galaxy is a repository for Ansible roles. It allows you to download and share
roles with the community.

Example of Installing a Role from Ansible Galaxy:

ansible-galaxy install username.role_name


Ansible Vault

Ansible Vault is a feature that allows you to encrypt sensitive data such as passwords
and API keys. This ensures that sensitive information is not exposed in your
playbooks.

Example of Creating an Encrypted File:

ansible-vault create secrets.yml


Example of Encrypting an Existing File:

ansible-vault encrypt secrets.yml


Example of Using Encrypted Variables in a Playbook:

---
- name: Deploy application
hosts: webservers
become: yes

vars_files:
- secrets.yml

tasks:
- name: Print the secret message
debug:
msg: "{{ secret_message }}"

Ansible Tower

Ansible Tower is an enterprise version of Ansible that provides a web-based user


interface, REST API, and other features for managing and scaling Ansible automation.

Key Features of Ansible Tower:

1. Role-Based Access Control: Control who can run specific playbooks and access
certain resources.
2. Job Scheduling: Schedule playbook runs at specific times.
3. Graphical Inventory Management: Manage your inventory through a web interface.
4. Real-Time Job Output: View the output of playbook runs in real time.

Dynamic Inventory

Dynamic inventory allows you to generate inventory data dynamically from external
sources such as cloud providers, CMDBs, and monitoring systems.

Example of Using a Dynamic Inventory Script:

ansible-playbook -i dynamic_inventory.py playbook.yml


Best Practices for Ansible
Organizing Playbooks

1. Use Roles: Organize your playbooks into roles to promote reuse and maintainability.
2. Separate Variables: Keep variables in separate files and use vars_files to load
them.
3. Use Handlers: Use handlers to manage service restarts and other actions triggered
by changes.
4. Use Templates: Use Jinja2 templates for configuration files to make them dynamic
and reusable.

Writing Idempotent Playbooks

1. Check for Changes: Always check if a change is necessary before making it. Many
Ansible modules have a state parameter to ensure idempotency.
2. Use changed_when and failed_when: Customize task results with these directives to
handle edge cases.
3. Test Playbooks: Regularly test your playbooks in different environments to ensure
they work as expected.

Security Practices

1. Use Ansible Vault: Encrypt sensitive data such as passwords and API keys.
2. Limit Privilege Escalation: Use become and become_user judiciously to limit the
scope of privilege escalation.
3. Use Secure Connections: Ensure that all connections to managed nodes are
encrypted using SSH or other secure protocols.

Performance Optimization

1. Limit Parallelism: Use the -f option to limit the number of parallel connections to
prevent overwhelming your infrastructure.
2. Use Fact Caching: Cache facts to avoid gathering them repeatedly, which can save
time on large inventories.
3. Optimize Playbook Structure: Group tasks logically and minimize redundant
operations.

Troubleshooting Ansible

1. Use Verbose Mode: Increase verbosity with the -v, -vv, or -vvv options to get more
detailed output.
2. Check Logs: Review logs for errors and warnings that can provide insights into issues.
3. Test Connectivity: Use the ping module to verify connectivity to managed nodes.
4. Validate Syntax: Use ansible-playbook --syntax-check to validate the syntax of
your playbooks.

Example Playbook with Best Practices


---
- name: Deploy web application
hosts: webservers
become: yes

vars_files:
- vars/main.yml

roles:
- common
- web

tasks:
- name: Ensure Apache is installed
yum:
name: httpd
state: present

- name: Deploy application files


template:
src: app.conf.j2
dest: /etc/httpd/conf.d/app.conf
notify: Restart Apache

handlers:
- name: Restart Apache
service:
name: httpd
state: restarted

Ansible Modules in Depth


Ansible modules are the core components that Ansible uses to perform tasks. They
are reusable, standalone scripts that can be executed by Ansible on your managed
nodes. Here, we will delve into some of the most commonly used Ansible modules
and their functionalities.

Command and Shell Modules

These modules allow you to run commands on remote hosts.

Example of Using the Command Module:

- name: Run a command


hosts: all
tasks:
- name: Run the uptime command
command: uptime
Example of Using the Shell Module:

- name: Run a shell command


hosts: all
tasks:
- name: Run a shell script
shell: /usr/bin/myscript.sh

File Module

The file module is used to manage file properties.

Example of Using the File Module:

- name: Manage files and directories


hosts: all
tasks:
- name: Create a directory
file:
path: /etc/myapp
state: directory
mode: '0755'

- name: Create an empty file


file:
path: /etc/myapp/config.txt
state: touch

Copy Module

The copy module is used to copy files from the control machine to remote hosts.

Example of Using the Copy Module:

- name: Copy files to remote hosts


hosts: all
tasks:
- name: Copy configuration file
copy:
src: /local/path/to/config.txt
dest: /remote/path/to/config.txt

Template Module

The template module is used to deploy configuration files using Jinja2 templates.

Example of Using the Template Module:

- name: Deploy configuration files


hosts: all
tasks:
- name: Deploy Nginx configuration
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf

Service Module

The service module is used to manage services.

Example of Using the Service Module:

- name: Manage services


hosts: all
tasks:
- name: Ensure Nginx is started
service:
name: nginx
state: started

User Module

The user module is used to manage user accounts.

Example of Using the User Module:

- name: Manage user accounts


hosts: all
tasks:
- name: Create a user
user:
name: johndoe
state: present
groups: sudo

Package Module

The package module is used to manage software packages.

Example of Using the Package Module:

- name: Install packages


hosts: all
tasks:
- name: Ensure Git is installed
package:
name: git
state: present

Git Module

The git module is used to manage Git repositories.


Example of Using the Git Module:

- name: Manage Git repositories


hosts: all
tasks:
- name: Clone a Git repository
git:
repo: 'https://github.com/ansible/ansible-examples.git'
dest: /opt/ansible-examples

Debug Module

The debug module is used to print messages and variables during playbook
execution.

Example of Using the Debug Module:

- name: Print debug messages


hosts: all
tasks:
- name: Print a message
debug:
msg: "This is a debug message"

- name: Print a variable


debug:
var: ansible_facts['os_family']

Ansible and the Cloud


Ansible can be used to automate the provisioning and management of cloud
resources. Below are some examples of using Ansible with different cloud

providers.

AWS

Example of Using Ansible with AWS:

- name: Provision EC2 instances


hosts: localhost
gather_facts: no
tasks:
- name: Launch EC2 instance
ec2:
key_name: mykey
instance_type: t2.micro
image: ami-0c55b159cbfafe1f0
wait: yes
count: 1
region: us-west-2
vpc_subnet_id: subnet-123456
group: default
instance_tags:
Name: AnsibleEC2

Azure

Example of Using Ansible with Azure:

- name: Create a virtual machine in Azure


hosts: localhost
tasks:
- name: Create VM
azure_rm_virtualmachine:
resource_group: myResourceGroup
name: myVM
vm_size: Standard_DS1_v2
admin_username: myadmin
admin_password: mypassword
image:
offer: UbuntuServer
publisher: Canonical
sku: '18.04-LTS'
version: latest

Google Cloud Platform

Example of Using Ansible with GCP:

- name: Create an instance in GCP


hosts: localhost
tasks:
- name: Create an instance
gcp_compute_instance:
name: my-instance
machine_type: n1-standard-1
zone: us-central1-a
disks:
- auto_delete: true
boot: true
initialize_params:
source_image: projects/debian-
cloud/global/images/family/debian-9
network_interfaces:
- network: default
access_configs:
- name: External NAT
type: ONE_TO_ONE_NAT

Ansible Galaxy Roles and Collections


Creating and Using Roles

Ansible roles allow you to organize your playbooks and share them with others.
Roles are structured in a specific way to promote reuse and simplify complex
playbooks.
Example of a Role Directory Structure:

roles/
myrole/
tasks/
main.yml
handlers/
main.yml
templates/
...
files/
...
vars/
main.yml
defaults/
main.yml
meta/
main.yml
Example of Using a Role in a Playbook:

---
- name: Apply myrole
hosts: all
roles:
- myrole

Publishing Roles to Ansible Galaxy

Ansible Galaxy is a community hub for sharing Ansible roles. You can publish your
roles to Ansible Galaxy and use roles shared by others.

Example of Publishing a Role:

1. Create a Galaxy Account: Sign up at Ansible Galaxy.


2. Prepare Role Metadata: Ensure your role has a meta/main.yml file with the
necessary metadata.
3. Publish Role: Use the ansible-galaxy command to publish the role.

ansible-galaxy import username myrole

Using Collections

Ansible collections are a distribution format for Ansible content that can include
roles, modules, and plugins.

Example of Using a Collection:

---
- name: Use a collection
hosts: all
collections:
- community.general
tasks:
- name: Install a package using a collection module
package:
name: vim
state: present

Ansible Best Practices and Tips


Version Control

1. Use Git: Version control your playbooks, roles, and inventory files using Git.
2. Branching Strategy: Use branches for development, testing, and production
environments.

Testing and Validation

1. Linting: Use tools like ansible-lint to check your playbooks for best practices and
syntax errors.
2. CI/CD: Integrate Ansible with CI/CD pipelines to automate testing and deployment.

Documentation

1. Inline Comments: Add comments to your playbooks and roles to explain the
purpose of tasks and variables.
2. Documentation Files: Create README files for your roles and collections to provide
usage instructions and examples.

Community Involvement

1. Contribute: Contribute to Ansible projects on GitHub and share your roles on


Ansible Galaxy.
2. Stay Updated: Follow Ansible's official blog and join community forums to stay
updated with the latest features and best practices.

Conclusion
Ansible is a powerful automation tool that simplifies the management of complex IT
environments. This comprehensive guide has covered the basics of Ansible, advanced
concepts, best practices, and examples of using Ansible with various cloud providers.
By following these guidelines and exploring the extensive features of Ansible, you
can automate tasks, ensure consistent configurations, and improve the efficiency of
your operations.
Remember, the key to mastering Ansible is practice. Start with simple playbooks and
gradually explore more advanced features as you gain confidence. The Ansible
community is vast and supportive, so don't hesitate to seek help and share your
knowledge. Happy automating!

You might also like