Basics of Ansible
1
Agenda
2
What isAnsible?
“ Simple, agentless and powerful open
source IT automation tool
Provisioning
Configuration Management
Application Deployment
Continuous Delivery Security &
Compliance Orchestration
11
What are theoptions?
12
What are theoptions?
13
Why Ansible?
Agent-less architecture (no agent is required, everything is done by
using SSH, ssh for communication)
No centralised server, no client-sideagents SSH
based
Configuration as data, not code (YAMLfiles)
14
How SSH is achieved
Key generation (public and private key) is performed using the ssh-keygen
command.
This generates the private key, ~/.ssh/id_rsa, and the public key,
~/.ssh/id_rsa.pub.
Trust will be initiated between client and server with the help of ssh-copy-id <IP-
Address>
Life before Ansible
Multiple ssh, control panels, editing config filesmanually.
25
Building Blocks
An Ansible solution is composed of one or more items listed
on the leftside.
Typically, our solutions executes tasks for an inventory, utilizing
some modules, using or populating some variables, processing
some file templates, in a playbook, which can be organized in
roles.
Let's see each of them indetail.
26
Building Blocks - Inventory
Tells Ansible about hosts it shouldmanage
Hostnames, IPs, ports, SSHparameters
Server specific variables
Hosts are grouped. They can belong tomultiple
groups
Groups can also belong to multiplegroups
27
Building Blocks - Inventory
• Example for Inventory file
28
Building Blocks - Module
• Modules provide Ansible means to control ormanage
resources on local or remoteservers.
• They perform a variety of functions. For example a module
may be responsible for rebooting amachine or it can simply
display a message on thescreen.
• Ansible allows users to write their own modules and also
provides out-of-the-box core or extrasmodules.
• Core: Maintained by the core Ansible teamand
always shipped with Ansible.
• Extras: Maintained by the community. Mightbe
shipped separately in thefuture. 29
Building Blocks - Module
Some of the most commonly used modulesare:
File handling: file, stat, copy, template
Remote execution: command, shell Service
management: service
Package management: apt, yum, bsd, ports
Source control systems: git, subversion
30
Building Blocks - Task
Tasks are responsible for calling a module with aspecific set of
parameters.
Each Ansible task contains:
a descriptive name [optional] a
module to be called module
parameters
pre/post-conditions [optional]
processing directives [optional]
They allow us to call Ansible modules andpass
information to consecutivetasks.
31
Building Blocks - Variable
• Variables in Ansible are very useful forreusing
information. Sources for variablesare:
• Inventory: We can assign variables to hostsor groups
(group vars, host vars).
• YAML files: We can include files containing variables. Task
results: Result of a task can be assigned to a variable using the
register keyword as shown in the previous slide.
• Playbooks: We can define variables inAnsible
playbooks (more on that later).
•Command line: (-e means extra variable //-e
"uservar=gulcin")
32
Building Blocks - Playbook
Playbooks contains Plays
Plays contain Tasks
Tasks call Modules and may (optionally) trigger
handlers (run once, run at the end)
33
Building Blocks - Playbook
Ansible playbooks are written using the YAMLsyntax.
Playbooks may contain more than oneplays
Each play contains:
name of host groups to connectto
tasks it needs to perform.
A play may also contain variables/roles/handlers, if
defined.
Strict dependency ordering: everything infile performs
in a sequentialorder.
34
Building Blocks - Role
In Ansible,
playbooks organize tasks
roles organize playbooks
Imagine that we have lots of independent resourcesto
manage (e.g., web servers, PostgreSQL servers, logging,
monitoring, AWS, ...).
Putting everything in a single playbook may result inan
unmaintainable solution.
35
Building Blocks - Role
Here you can see a dependency graph andthe
corresponding role directory structure:
36
Howto Invoke Ansible?
To work with Ansible, we have 2 main alternatives;
1. Running ad-hoccommands
2. Runningplaybooks
Let's check them out one byone.
37
Ad-hoc Commands
We can call any Ansible module from the command line,anytime.
The ansible CLI tool works like a single task. It requires an inventory, a module
name, and module parameters.
For example, given an inventory filelike:
[dbservers]
[Link]
Now we can call anymodule.
38
Ad-hoc Commands
We can check uptimes of all hosts in dbserversusing:
ansible dbservers -i [Link] -m command -a "uptime"
Here we can see the Ansibleoutput:
$ ansible -i hosts web -m ping
[Link] | SUCCESS => {
"changed": false,
"ping": "pong"
}
39
How to Run Playbooks?
Given an inventory file likethis:
[dbservers]
[Link]
Now let's create a simple playbook to see how it can be ran.
---
- hosts: dbservers
tasks:
- name: retrieve the uptime
command: uptime
register: command_result # Store this command's result in this variable
- name: Display the uptime
debug: msg="{{ command_result.stdout }}" # Display command output here
40
How to Run Playbooks?
Now we can run the playbook and see it's outputhere:
gulcin@apathetic ~ $ ansible-playbook -i [Link] [Link]
PLAY [dbservers] **************************************************************
GATHERING FACTS ***************************************************************
ok: [[Link]]
TASK: [retrieve the uptime] ***************************************************
changed: [[Link]]
TASK: [Display the uptime] ****************************************************
ok: [[Link]] => {
"msg": " [Link] up 3 days, 14:32, 2 users, load average: 0.00, 0.01, 0.05"
}
PLAY RECAP ********************************************************************
[Link] : ok=3 changed=1 unreachable=0 failed=0
41
Playbook control
--tags / --skip-tags
Runs or skips tasks with specifiedtags
--limit
Manages only specified hosts or groups
--start-at-task
Start execution from a specifictask
--step
Executes step-by-step and asks for confirmation tocontinue
--check / --diff / --syntax-check
Runs a playbook without actually executinganything
42
Playbook loops
Ansible supports iterating over facts with loopstatements:
with_items: runs the task using the provided array variable
with_indexed_items: runs the task using the providedarray variable
and adds item index
with_flattened: runs the task using mergedvariables
with_file: runs the task using given file'scontents
Some other with_typefunctions:
with_together, with_nested, with_subelements, with_sequence,
with_random_choice, with_first_found, with_lines..
43
with_items
Executes the task for each element in given array Current
element value can be accessed using {item}}
- name: with_items
debug:
msg: "{{ item }}"
with_items: "{{ items }}"
44
w ith_ indexed items
Executes the task for each element in given array Current
element index can be accessed using {item.0}}Current element
value can be accessed using {item.1}}
- name: indexed loop demo
debug:
msg: "at array position {{ item.0 }} there is a value {{ item.1 }}"
with_indexed_items:
- "{{ some_list }}"
45
with_flattened
Merges given arrays into a singleone
Executes the task for each element in merged array Current
element value can be accessed using {item}}
name: with_flattened
debug:
msg: "{{ item }}"
with_flattened: "{{ items }}"
46
w ith_file
Executes the task for the givenfile
Contents of the file can be accessed using {item}}
---
- hosts: all
tasks:
# emit a debug message containing the content of each file.
- debug:
msg: "{{ item }}"
with_file:
- first_example_file
47
Questions?
Huge Thanks!
48