100% found this document useful (1 vote)
457 views18 pages

Ansible Full Course: For Beginners

Ansible uses SSH to connect to managed nodes and push small programs called modules to automate configuration management and deployment tasks. An inventory file lists the managed nodes and optionally specifies host variables. The controller node runs tasks on the managed nodes defined in the inventory. Playbooks define ordered lists of tasks that can be repeatedly run on the managed nodes to maintain a consistent state.

Uploaded by

arm_max78
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
100% found this document useful (1 vote)
457 views18 pages

Ansible Full Course: For Beginners

Ansible uses SSH to connect to managed nodes and push small programs called modules to automate configuration management and deployment tasks. An inventory file lists the managed nodes and optionally specifies host variables. The controller node runs tasks on the managed nodes defined in the inventory. Playbooks define ordered lists of tasks that can be repeatedly run on the managed nodes to maintain a consistent state.

Uploaded by

arm_max78
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

Ansible Full Course

For Beginners
IT Automation Simplified
Learn.sandipdas.in

What is Asible?

What is Configuration Management?

Topics How Ansible Works?

Ansible Concepts

Controller Node SetUp

Managing Managed Node Via Inventory

Ansible Modules

Executing Single Tasks via Ad-hoc


commands

Ansible Playbook

Ansible Vault

Ansible Galaxy
What is Ansible?
Ansible delivers 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.
Learn.sandipdas.in

What is Configuration Management?


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

How Ansible Works?


Ansible does not use any agent. yes, you heard it right! Ansible Architecture

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)
Learn.sandipdas.in

Ansible Concepts
Control Node Managed nodes
Any machine with Ansible installed. We can run Ansible
The network devices (and/or servers) we manage with Ansible.
commands and playbooks by invoking the ansible or ansible-
Managed nodes are also sometimes called “hosts”. Ansible is not
playbook command from any control node. We can use any
installed on managed nodes.
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. Inventory
We can have multiple control nodes as well. 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
Collections
nodes, creating and nesting groups for easier scaling.
Collections are a distribution format for Ansible content that can
typically located at /etc/ansible/hosts, provide a custom inventory
include playbooks, roles, modules, and plugins. We can install and
path using the -i parameter when running commands & playbooks
use collections through Ansible Galaxy

Tasks Modules
The units of action in Ansible. We can execute a single task once
with an ad hoc command. The units of code Ansible executes. Each module has a
particular use, from administering users on a specific type
Playbooks of database to managing VLAN interfaces on a specific type
Ordered lists of tasks, saved so we can run those tasks in of network device. We can invoke a single module with a
that order repeatedly. Playbooks can include variables as task, or invoke several different modules in a playbook.
well as tasks. Playbooks are written in YAML and are easy to
read, write, share and understand
Learn.sandipdas.in

Controller Node How to Install Ansible?

SetUp There are multiple ways to install Ansible, here showing Ubuntu
Example:
$ sudo apt update
A system where the Ansible is
$ sudo apt install software-properties-common
installed and configured to $ sudo add-apt-repository --yes --update ppa:ansible/ansible
connect and execute commands $ sudo apt install ansible
on nodes.
Check Ansible version
Generating Custom SSH Keys
Setting up ssh: ansible –version
sudo apt-get install openssh-server
Testing Connectivity With Managed Nodes
Generating new ssh keys:
Using a Custom SSH Key, checking remote connections
ssh-keygen
ansible all -m ping --private-key=~/.ssh/my_custom_key
For PLaybook:
ssh-copy-id hostname (if it's a password-
ansible-playbook myplaybook.yml --private-
based)
key=~/.ssh/my_custom_key
ssh-copy-id -i ~/.ssh/my_custom_key user@host
Using password:
ansible all -m ping --ask-pass
Time to check SSH Connection
ansible-playbook myplaybook.yml --ask-pass
ssh -i ~/.ssh/my_custom_key user@host
Managing Managed Invetory file example with various parameters

Node Via Inventory File path: /etc/ansible/hosts (or custom location by: -i /path/to/file)
#un-grouped
192.0.2.40
What is a managed node? 192.0.3.56
aserver.example.org
Managed node is a server (node) bserver.example.org
controlled by Ansible Controller Node #by group called appservers
[appservers]
What is Inventory? 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
It's a file that contains information about the servers
#host (DNS will resolve automatically)
Ansible controls, typically located at /etc/ansible/hosts ,
[dbservers]
using the -i parameter we can
one.example.com
provide custom inventory path
two.example.com
three.example.com
Targetting hosts and groups by patterns #dev_servers1 is a group containing other groups
All hosts: all (or *) [dev_servers1:children]
10.0.0.* : All host with IP starting from 10.0.0.* appservers
ungrouped: all hosts that's not within any group dbservers
One host: host1
Example targeting hosts
Multiple hosts: host1:host2 (or host1,host2)
One group: appservers ansible appservers -m ping
Multiple groups: appservers:dbservers ansible appservers -m service -a "name=httpd state=restarted"
Excluding groups: appservers:!dbservers Note: Ansible supports inventory scripts for building dynamic inventory files, this is useful when host
The intersection of groups: appservers:&dbservers changes very often. To know more read documentation here
e.g. ansible all -m ping -i get_inventory.py Learn.sandipdas.in
Ansible Modules Useful Modules based on use cases

ping – Try to connect to host, verify a usable python and return


A module is a reusable, pong on success
reboot – Reboot a machine
standalone script that Ansible get_url – Downloads files from HTTP, HTTPS, or FTP to node
runs on our behalf, either locally git – Deploy software (or files) from git checkouts
or remotely copy – Copy files to remote locations
file – Manage files and file properties
command – Execute commands on targets
Where to use modules? shell – Execute shell commands on targets
script – Runs a local script on a remote node after transferring it
Each module can be used by the Ansible API, or by service – Manage services
the ansible or ansible-playbook programs. user – Manage user accounts
cron – Manage cron.d and crontab entries
A module provides a defined interface, accepts apt – Manages apt-packages
yum – Manages packages with the yum package manager
arguments, and returns information to Ansible by
add_host – Add a host (and alternatively a group) to the ansible-
printing a JSON string to stdout before exiting.
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

Click here to know more about Build In Modules Learn.sandipdas.in


Executing Single Tasks Ad-hoc commands example
Managing files (Copy and moving file)

via Ad-hoc commands #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"
What is Task? 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
The units of action in Ansible. We can execute a single task once
state=directory"
with an ad hoc command. #Remove Directory/File
ansible appservers -m ansible.builtin.file -a "dest=/path/to/c state=absent"

What is ad-hoc commands? 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"
Ad-Hoc commands are an easy way to run quick commands to ansible appservers -m ansible.builtin.yum -a "name=acme-1.5 state=present"
perform the actions, and it will not be saved for later. ansible appservers -m ansible.builtin.yum -a "name=acme state=latest"
It uses the /usr/bin/ansible command-line tool to automate a single ansible appservers -m ansible.builtin.yum -a "name=acme state=absent"
#using apt package manager to install and uninstall packages
task on one or more managed nodes.
ansible appservers -m apt -a "name=acme state=latest"
ansible appservers -m apt -a "name=acme-1.5 state=present"

Why use ad-hoc commands and use cases? Managing users and groups (adding , removing users and/or groups )
ansible all -m ansible.builtin.user -a "name=foo password=<crypted password here>"
ad hoc commands are great for tasks we repeat rarely. Below are the use cases: ansible all -m ansible.builtin.user -a "name=foo state=absent"
Syntax : Command hostgroup module/options[arguments]
Specify command : -a parameter | Specify Module: -m parameter Managing services (Start, Stop, Restart Services)
Rebooting servers ansible appservers -m ansible.builtin.service -a "name=httpd state=started"
#reboot all servers in appservers group ansible appservers -m ansible.builtin.service -a "name=httpd state=restarted"
ansible appservers -a "/sbin/reboot" ansible appservers -m ansible.builtin.service -a "name=httpd state=stopped"
#reboot the appservers hosts with 10 parallel forks
ansible appservers -a "/sbin/reboot" -f 10 Deploying From Source Control
#to run To run /usr/bin/ansible from a differet user account (not root) ansible appservers -m git -a "repo=https://foo.example.org/repo.git dest=/src/myapp version=HEAD"
ansible appservers -a "/sbin/reboot" -f 10 -u username Gathering facts
#run commands through privilege escalation ansible all -m ansible.builtin.setup
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
Ansible Playbook Ansible Playbook Components

Ansible Playbook is ordered lists of tasks, saved so hosts: Use hosts keyword to target hosts/servers by hostname, group
we can run those tasks in that order repeatedly. name, or any pattern
Playbooks in Ansible are written in YAML format ad Variables: The Variables are the way for Ansible to pass custom values in
easy to read. YAML means "Yet Another Markup tasks. We can define these variables in our playbooks, in our inventory, in
Language". Every YAML file starts with ---. Playbooks re-usable files or roles, or at the command line.
usually stored in source code control e.g. git
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:
String
List
Dictionary
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"

Learn.sandipdas.in
Ansible Playbook Tasks What is Ansible Playbook Task?

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

Want to learn more about tasks?

Check Official Documentation here

Learn.sandipdas.in
Ansible Playbook Handlers
What is Ansible Playbook 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: Trigger Multiple Handlers Use Variables in Handlers

“listen” to generic topics, and tasks can notify those topics

Re-use tasks in Handlers

Learn.sandipdas.in
Ansible Playbook Roles
What is Ansible Playbook Roles?

call a role with a fully qualified path


The classic (original) way to use
The Roles are the tidy way to write playbooks. It permits to store a group
roles is with the roles option 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
include a role
users.
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.
Pass other keywords to the roles option:
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.

conditionally include a role

To know more about the roles Click Here

Learn.sandipdas.in
Run Ansible Playbook Running Playbook

# Run on 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

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
Ansible Vault Working With Ansible Vault
What is Ansible Vault?
Creating a New Encrypted File
If our Ansible playbooks deal with sensitive data like ansible-vault create credentials.yml
passwords, API keys, and credentials, it is important to
keep that data safe by using an encryption mechanism. Encrypting an Existing Ansible File
Ansible provides ansible-vault to encrypt files and ansible-vault encrypt credentials.yml
variables.
View encrypted file
ansible-vault view credentials.yml
After encrypting a file with this tool, we will only be able
to execute, edit or view its contents by providing the Edit encrypted file
relevant password defined when we first encrypted the ansible-vault edit credentials.yml
file.
Permanently Decrypt a file
Running Playbook with Vault ansible-vault decrypt credentials.yml

ansible-playbook myplaybook.yml --ask-vault-pass


Using Multiple Vault Passwords for multiple environments
ansible-playbook myplaybook.yml --vault-password-file We can have dedicated vault passwords for different environments, such as
path/to/passfile development, testing, and production environments
ansible-playbook myplaybook.yml --vault-id ansible-vault create --vault-id dev@prompt credentials_dev.yml
dev@prompt ansible-vault create --vault-id prod@prompt credentials_prod.yml
ansible-playbook myplaybook.yml --vault-id To Edit/edit have to provide the same id
dev@path/to/passfile 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
Learn.sandipdas.in ansible-vault create --vault-id dev@path/to/passfile credentials_dev.yml
Ansible Galaxy How to Use Ansible Galaxy?
What is Ansible Galaxy?
Create a role template suitable for submission to Ansible Galaxy.
Ansible Galaxy is a repository for Ansible Roles that are ansible-galaxy init
available to drop directly into your Playbooks to
streamline your automation projects. 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

Learn.sandipdas.in
Learn.sandipdas.in

Contact Me [email protected]

You might also like