The document provides an overview of Ansible, an IT automation tool. It discusses key Ansible concepts like playbooks, tasks, handlers, roles, modules, and vaults. It also summarizes how to install and use Ansible for tasks like configuration management, deploying applications, managing packages and services, copying files, and retrieving facts about managed nodes. Example ad-hoc commands are provided to demonstrate managing files, packages, users, and services on remote hosts. The benefits of using playbooks over ad-hoc commands are highlighted.
What is Asible?
Whatis Configuration Management?
How Ansible Works?
Ansible Concepts
Controller Node SetUp
Managing Managed Node Via Inventory
Topics
Learn.sandipdas.in
Executing Single Tasks via Ad-hoc
commands
Ansible Playbook
Ansible Modules
Ansible Vault
Ansible Galaxy
3.
What is Ansible?
Ansibledelivers simple IT automation that ends repetitive
tasks and frees up DevOps teams for more strategic work.
It automates configuration management, cloud provisioning,
application deployment, intra-service orchestration, and many
other IT needs.
When Ansible is used as a configuration management tool, it
is used to store the current state of our systems and help us
to maintain that state, it make changes and deployments
faster, removing the potential for human error while making
system management predictable and scalable.
4.
What is ConfigurationManagement?
Configuration management is a process for maintaining
computer systems, servers, and software in a desired,
consistent state.
It’s a way to make sure that a system performs as it’s
expected to as changes are made over time.
Learn.sandipdas.in
5.
How Ansible Works?
Ansibledoes not use any agent. yes, you heard it right!
Ansible also does not use any additional custom security
infrastructure, which makes it very flexible and it can run on
anything.
It manages entities/servers via SSH(Secure Shell)
Ansible works by connecting to our nodes/servers and
pushing out small programs via ssh, called "Ansible Modules"
to them. These programs are written to be resource models
of the desired state of the system. Ansible then executes
these modules (over SSH by default), and removes them
when finished.
Ansible modules can be written in any language that can return JSON (Ruby, Python,
bash, etc)
There's also various Python APIs for extending Ansible’s connection types (SSH is not
the only transport possible)
Ansible Architecture
Learn.sandipdas.in
6.
Ansible Concepts
Collections
Tasks
Managed nodes
Inventory
Modules
ControlNode
Any machine with Ansible installed. We can run Ansible
commands and playbooks by invoking the ansible or ansible-
playbook command from any control node. We can use any
computer that has a Python installation as a control node -
laptops, shared desktops, and servers can all run Ansible.
However, We cannot use a Windows machine as a control node.
We can have multiple control nodes as well.
The network devices (and/or servers) we manage with Ansible.
Managed nodes are also sometimes called “hosts”. Ansible is not
installed on managed nodes.
A list of managed nodes. An inventory file is also sometimes called
a “hostfile”. Our inventory can specify information like IP address
for each managed node. An inventory can also organize managed
nodes, creating and nesting groups for easier scaling.
typically located at /etc/ansible/hosts, provide a custom inventory
path using the -i parameter when running commands & playbooks
Collections are a distribution format for Ansible content that can
include playbooks, roles, modules, and plugins. We can install and
use collections through Ansible Galaxy
Playbooks
The units of action in Ansible. We can execute a single task once
with an ad hoc command.
Ordered lists of tasks, saved so we can run those tasks in
that order repeatedly. Playbooks can include variables as
well as tasks. Playbooks are written in YAML and are easy to
read, write, share and understand
The units of code Ansible executes. Each module has a
particular use, from administering users on a specific type
of database to managing VLAN interfaces on a specific type
of network device. We can invoke a single module with a
task, or invoke several different modules in a playbook.
Learn.sandipdas.in
7.
How to InstallAnsible?
There are multiple ways to install Ansible, here showing Ubuntu
Example:
$ sudo apt update
$ sudo apt install software-properties-common
$ sudo add-apt-repository --yes --update ppa:ansible/ansible
$ sudo apt install ansible
Controller Node
SetUp
A system where the Ansible is
installed and configured to
connect and execute commands
on nodes.
Check Ansible version
ansible –version
Testing Connectivity With Managed Nodes
Using a Custom SSH Key, checking remote connections
ansible all -m ping --private-key=~/.ssh/my_custom_key
For PLaybook:
ansible-playbook myplaybook.yml --private-
key=~/.ssh/my_custom_key
Using password:
ansible all -m ping --ask-pass
ansible-playbook myplaybook.yml --ask-pass
Generating Custom SSH Keys
Setting up ssh:
sudo apt-get install openssh-server
Generating new ssh keys:
ssh-keygen
ssh-copy-id hostname (if it's a password-
based)
ssh-copy-id -i ~/.ssh/my_custom_key user@host
Time to check SSH Connection
ssh -i ~/.ssh/my_custom_key user@host
Learn.sandipdas.in
8.
Invetory file examplewith various parameters
File path: /etc/ansible/hosts (or custom location by: -i /path/to/file)
#un-grouped
192.0.2.40
192.0.3.56
aserver.example.org
bserver.example.org
#by group called appservers
[appservers]
sample1.example.com ansible_host = 10.0.0.3 #ssh to 10.0.0.3
sample2.example.com ansible_ssh_user = xyz #ssh as user xyz
#host (DNS will resolve automatically)
[dbservers]
one.example.com
two.example.com
three.example.com
#dev_servers1 is a group containing other groups
[dev_servers1:children]
appservers
dbservers
Managing Managed
Node Via Inventory
Managed node is a server (node)
controlled by Ansible Controller Node
Targetting hosts and groups by patterns
All hosts: all (or *)
10.0.0.* : All host with IP starting from 10.0.0.*
ungrouped: all hosts that's not within any group
One host: host1
Multiple hosts: host1:host2 (or host1,host2)
One group: appservers
Multiple groups: appservers:dbservers
Excluding groups: appservers:!dbservers
The intersection of groups: appservers:&dbservers
What is a managed node?
What is Inventory?
It's a file that contains information about the servers
Ansible controls, typically located at /etc/ansible/hosts ,
using the -i parameter we can
provide custom inventory path
Example targeting hosts
ansible appservers -m ping
ansible appservers -m service -a "name=httpd state=restarted"
Note: Ansible supports inventory scripts for building dynamic inventory files, this is useful when host
changes very often. To know more read documentation here
e.g. ansible all -m ping -i get_inventory.py Learn.sandipdas.in
9.
Useful Modules basedon use cases
ping – Try to connect to host, verify a usable python and return
pong on success
reboot – Reboot a machine
get_url – Downloads files from HTTP, HTTPS, or FTP to node
git – Deploy software (or files) from git checkouts
copy – Copy files to remote locations
file – Manage files and file properties
command – Execute commands on targets
shell – Execute shell commands on targets
script – Runs a local script on a remote node after transferring it
service – Manage services
user – Manage user accounts
cron – Manage cron.d and crontab entries
apt – Manages apt-packages
yum – Manages packages with the yum package manager
add_host – Add a host (and alternatively a group) to the ansible-
playbook in-memory inventory
template – Template a file out to a target host
include_role – Load and execute a role
include_tasks – Dynamically include a task list
include_vars – Load variables from files, dynamically within a
task
debug – Print statements during execution
Ansible Modules
A module is a reusable,
standalone script that Ansible
runs on our behalf, either locally
or remotely
Learn.sandipdas.in
Where to use modules?
Each module can be used by the Ansible API, or by
the ansible or ansible-playbook programs.
A module provides a defined interface, accepts
arguments, and returns information to Ansible by
printing a JSON string to stdout before exiting.
Click here to know more about Build In Modules
10.
Ad-hoc commands example
Managingfiles (Copy and moving file)
#copy file
ansible appservers -m ansible.builtin.copy -a "src=/etc/hosts dest=/tmp/hosts"
#changing permissions
ansible appservers -m ansible.builtin.file -a "dest=/srv/foo/a.txt mode=600"
ansible appservers -m ansible.builtin.file -a "dest=/srv/foo/b.txt mode=600 owner=sandip group=sandip"
#create directores
ansible appservers -m ansible.builtin.file -a "dest=/path/to/c mode=755 owner=sandip group=sandip
state=directory"
#Remove Directory/File
ansible appservers -m ansible.builtin.file -a "dest=/path/to/c state=absent"
Managing packages (Install, update and remove packages)
#using yum package manager to install and uninstall packages
ansible appservers -m ansible.builtin.yum -a "name=acme state=present"
ansible appservers -m ansible.builtin.yum -a "name=acme-1.5 state=present"
ansible appservers -m ansible.builtin.yum -a "name=acme state=latest"
ansible appservers -m ansible.builtin.yum -a "name=acme state=absent"
#using apt package manager to install and uninstall packages
ansible appservers -m apt -a "name=acme state=latest"
ansible appservers -m apt -a "name=acme-1.5 state=present"
Managing users and groups (adding , removing users and/or groups )
ansible all -m ansible.builtin.user -a "name=foo password=<crypted password here>"
ansible all -m ansible.builtin.user -a "name=foo state=absent"
Managing services (Start, Stop, Restart Services)
ansible appservers -m ansible.builtin.service -a "name=httpd state=started"
ansible appservers -m ansible.builtin.service -a "name=httpd state=restarted"
ansible appservers -m ansible.builtin.service -a "name=httpd state=stopped"
Deploying From Source Control
ansible appservers -m git -a "repo=https://foo.example.org/repo.git dest=/src/myapp version=HEAD"
Gathering facts
ansible all -m ansible.builtin.setup
Executing Single Tasks
via Ad-hoc commands
What is Task?
The units of action in Ansible. We can execute a single task once
with an ad hoc command.
What is ad-hoc commands?
Ad-Hoc commands are an easy way to run quick commands to
perform the actions, and it will not be saved for later.
It uses the /usr/bin/ansible command-line tool to automate a single
task on one or more managed nodes.
Why use ad-hoc commands and use cases?
ad hoc commands are great for tasks we repeat rarely. Below are the use cases:
Syntax : Command hostgroup module/options[arguments]
Specify command : -a parameter | Specify Module: -m parameter
Rebooting servers
#reboot all servers in appservers group
ansible appservers -a "/sbin/reboot"
#reboot the appservers hosts with 10 parallel forks
ansible appservers -a "/sbin/reboot" -f 10
#to run To run /usr/bin/ansible from a differet user account (not root)
ansible appservers -a "/sbin/reboot" -f 10 -u username
#run commands through privilege escalation
ansible appservers -a "/sbin/reboot" -f 10 -u username --become [--ask-become-
pass] Click here to know more about Build In Modules Learn.sandipdas.in
11.
Ansible Playbook Components
String
List
Dictionary
hosts:Use hosts keyword to target hosts/servers by hostname, group
name, or any pattern
Variables: The Variables are the way for Ansible to pass custom values in
tasks. We can define these variables in our playbooks, in our inventory, in
re-usable files or roles, or at the command line.
Ansible variable is defined in group_vars, host_vars, role vars, CLI vars and
is called in Jinja Templating way: {{ my_variable }}. You can call variables
everywhere in Ansible (tasks, variables, template, ...)
You can have 3 types of variables:
Example:
Key-Value
Ansible-playbook release.yml --extra-vars "version=1.23.45
other_variable=foo"
Json:
ansible-playbook release.yml --extra-vars
'{"version":"1.23.45","other_variable":"foo"}'
ansible-playbook arcade.yml --extra-vars '{"pacman":"mrs","ghosts":
["inky","pinky","clyde","sue"]}'
From File:
ansible-playbook release.yml --extra-vars "@some_file.json"
Ansible Playbook
Ansible Playbook is ordered lists of tasks, saved so
we can run those tasks in that order repeatedly.
Playbooks in Ansible are written in YAML format ad
easy to read. YAML means "Yet Another Markup
Language". Every YAML file starts with ---. Playbooks
usually stored in source code control e.g. git
Learn.sandipdas.in
12.
What is AnsiblePlaybook Task?
Execute tasks with elevated privileges or as a different user
with become
Repeat a task once for each item in a list with loops
Execute tasks on a different machine with delegation
Run tasks only when certain conditions apply with
conditionals and evaluating conditions with tests
Group a set of tasks together with blocks
Run tasks only when something has changed with handlers
The Tasks are the actions launched on remote Hosts. Tasks are
written in YAML langage in a descriptive structure way making
the read and write uniform through any tasks.
We can:
Want to learn more about tasks?
Check Official Documentation here
Learn.sandipdas.in
Ansible Playbook Tasks
13.
What is AnsiblePlaybook Handlers?
Ansible Handlers are action triggers called from tasks and run at the end
of a play. A Handler is a task(s) defined by its name and called with its
name.
We can:
Ansible Playbook Handlers
Learn.sandipdas.in
Trigger Multiple Handlers Use Variables in Handlers
“listen” to generic topics, and tasks can notify those topics
Re-use tasks in Handlers
14.
What is AnsiblePlaybook Roles?
The Roles are the tidy way to write playbooks. It permits to store a group
of actions with the same purpose and to call them in playbooks in a single
line.
Roles let you automatically load related vars, files, tasks, handlers, and
other Ansible artifacts based on a known file structure. After we group
your content in roles, we can easily reuse them and share them with other
users.
Ansible Playbook Roles
Learn.sandipdas.in
call a role with a fully qualified path
The classic (original) way to use
roles is with the roles option
Pass other keywords to the roles option:
include a role
conditionally include a role
tasks/main.yml - the main list of tasks that the role executes.
handlers/main.yml - handlers, which may be used within or outside this role.
library/my_module.py - modules, which may be used within this role (see
Embedding modules and plugins in roles for more information).
defaults/main.yml - default variables for the role. These variables have the
lowest priority of any variables available and can be easily overridden by any
other variable, including inventory variables.
vars/main.yml - other variables for the role
files/main.yml - files that the role deploys.
templates/main.yml - templates that the role deploys.
meta/main.yml - metadata for the role, including role dependencies.
To know more about the roles Click Here
15.
Running Playbook
# Runon all hosts defined
ansible-playbook <YAML>
# Run 10 hosts parallel
ansible-playbook <YAML> -f 10
# Verbose on successful tasks
ansible-playbook <YAML> --verbose
# Test run
ansible-playbook <YAML> -C
# Dry run
ansible-playbook <YAML> -C -D
# Run on single host using -l or -limit ( -l stands for limit )
ansible-playbook <YAML> -l <host>
e.g. ansible-playbook new_playbook.yml
Run Ansible Playbook
Verifying playbooks
Get Infos:
ansible-playbook <YAML> --list-hosts
ansible-playbook <YAML> --list-tasks
Syntax Check
ansible-playbook --syntax-check <YAML>
We can also use ansible-lint for detailed, Ansible-specific feedback on your
playbooks before you execute them. Click here for the documentation
Learn.sandipdas.in
16.
Working With AnsibleVault
Creating a New Encrypted File
ansible-vault create credentials.yml
Encrypting an Existing Ansible File
ansible-vault encrypt credentials.yml
View encrypted file
ansible-vault view credentials.yml
Edit encrypted file
ansible-vault edit credentials.yml
Permanently Decrypt a file
ansible-vault decrypt credentials.yml
Using Multiple Vault Passwords for multiple environments
We can have dedicated vault passwords for different environments, such as
development, testing, and production environments
ansible-vault create --vault-id dev@prompt credentials_dev.yml
ansible-vault create --vault-id prod@prompt credentials_prod.yml
To Edit/edit have to provide the same id
ansible-vault edit credentials_dev.yml --vault-id dev@prompt
Using a Password File
ansible-vault create --vault-password-file path/to/passfile credentials_dev.yml
ansible-vault create --vault-id dev@path/to/passfile credentials_dev.yml
What is Ansible Vault?
If our Ansible playbooks deal with sensitive data like
passwords, API keys, and credentials, it is important to
keep that data safe by using an encryption mechanism.
Ansible provides ansible-vault to encrypt files and
variables.
After encrypting a file with this tool, we will only be able
to execute, edit or view its contents by providing the
relevant password defined when we first encrypted the
file.
Ansible Vault
Learn.sandipdas.in
Running Playbook with Vault
ansible-playbook myplaybook.yml --ask-vault-pass
ansible-playbook myplaybook.yml --vault-password-file
path/to/passfile
ansible-playbook myplaybook.yml --vault-id
dev@prompt
ansible-playbook myplaybook.yml --vault-id
dev@path/to/passfile
17.
How to UseAnsible Galaxy?
Create a role template suitable for submission to Ansible Galaxy.
ansible-galaxy init
display a list of installed roles, with version numbers
ansible-galaxy list
Remove an installed role.
ansible-galaxy remove <role>
Get a variety of information about Ansible Galaxy
ansible-galaxy info <role>
Install role from galaxy
ansible-galaxy install <role-name> -p <directory>
Search for a role
ansible-galaxy search ‘install git’ --platform el
or
Visit here galaxy.ansible.com
What is Ansible Galaxy?
Ansible Galaxy is a repository for Ansible Roles that are
available to drop directly into your Playbooks to
streamline your automation projects.
Ansible Galaxy
Learn.sandipdas.in