SlideShare ist ein Scribd-Unternehmen logo
1 von 55
Automating with
ansible (part A)
Iman darabi
https://www.linkedin.com/in/imandarabi/
Table of contents (
part A - Basics )
1. Introduction
a. Definitions
b. Why ansible
c. Understanding YAML
■ YAML Data presentation
syntax
2. Basics getting started
a. Setting up ansible
b. Managing configuration and Inventory
c. Ad-hoc commands
d. Working with modules
e. Understanding playbooks
f. Variables, includes, imports and facts
g. Understanding Jinja2 templates
3. Working with roles
a. Understanding role structure
b. Creating roles
c. Deploying roles with ansible galaxy
d. Using the ansible galaxy CLI utility
Iman Darabi
https://www.linkedin.com/in/imandarabi/
Table of contents (
part B - Advanced )
1. Managing task control
a. Using with_items
b. Using Nested Loops
c. Using the when statement
d. Registering variables
e. Working with handlers
f. Working with tags
g. Dealing with errors
h. Using ansible blocks
2. Ansible vault
a. Understanding ansible Vault
b. Working with encrypted files
c. Executing with ansible vault
3. Optimizing ansible
a. Selecting hosts with host patterns
b. Configuring delegation
c. Delegation outside the inventory
d. Configuring parallelism
4. Troubleshooting ansible
a. Understanding ansible logging
b. Troubleshooting playbooks
c. Troubleshooting managed hosts
Iman Darabi
https://www.linkedin.com/in/imandarabi/
1_Introduction
Iman darabi
https://www.linkedin.com/in/imandarabi/
1.a) Definitions
● Simple automation language that can perfectly describe an IT application infrastructure
in ansible playbooks
● Open-source software provisioning, configuration management, and application-
deployment tool (wikipedia).
● Initial release: February 20, 2012
● Repository: github.com/ansible/ansible
● Ansible, an open source community project sponsored by Red Hat,
● Other configuration management tools:
○ Puppet
○ Chef
○ Juju
○ Salt …
1.b) Why ansible
● Minimal learning required
○ Human readable automation
○ No special coding skills needed
○ Tasks executed in order
● Only OpenSSH and Python are required on the managed nodes
● Agent-less ( no exploit or update )
● Powerful
○ App deployment
○ Configuration management
○ Workflow orchestration
1.b_Understanding
YAML
Iman darabi
https://www.linkedin.com/in/imandarabi/
What is YAML?
YAML Ain’t Markup Language
● YAML is a human-readable data serialization standard that can be used in conjunction
with all programming languages and is often used to write configuration files.
● YAML has no executable commands. It is simply a data-representation language.
● It is commonly used for configuration files and in applications where data is being
stored or transmitted.
● YAML files should end in .yaml/.yml
● YAML is case sensitive.
● YAML does not allow the use of tabs. Spaces are used instead as tabs are not
universally supported.
● We use YAML because it is easier for humans to read and write than other common
data formats like XML or JSON
YAML Data presentation
syntax
YAML style comparison
XML
<Servers>
<Server>
<name>SERVER1</name>
<owner>iman</owner>
<created>1399</created>
</Server>
</Servers>
JSON
{
Servers: [
{
name: Server1,
owner: iman,
created: 1399,
status: active,
}
]
}
YAML
Servers:
- Name: Server1
owner: iman
created: 1399
status: active
Document separator
--- <- Document header
… <- Document terminator
Data type - key value pair
● Key value pairs are defined using a
colon ( : ) and a space ( )
---
Fruit: Apple
Vegetable: Carrot
Liquid: Water
Meet: Chiken
Data type - Array / Lists
● Dash “-” indicates elements of lists
# Block Format
Fruites:
- Orange
- Apple
# Inline Format
Fruits: [ Orange, Apple ]
Data type - Dictionary / Map
● There must be equal number of blank
space ( ) for each of properties
Banana:
Calories: 105
Fat: 0.4
Grapes:
Calories: 62
Fat: 0.3
Data type - Strings
data: |
Each of these
Newlines
Will be broken up
data: >
This text is
wrapped and will
be formed into
a single paragraph
Check syntax with
http://yamllint.com
2_Basic getting
started
Iman darabi
https://www.linkedin.com/in/imandarabi/
2.a) Setting up
ansible
Iman darabi
https://www.linkedin.com/in/imandarabi/
Setting up controller and remote hosts
1. Install Ansible software
a. Only the control node needs ansible
i. # apt install ansible
b. Managed hosts need Python and SSH
2. Create a non-root user and perform all tasks as this user
3. Set up SSH for communications
4. Configure sudo
a. user ALL=(ALL) NOPASSWD: ALL
2.b) Managing
configuration and Inventory
Iman darabi
https://www.linkedin.com/in/imandarabi/
configuration file
● ansible.cfg defines ansible configurations
● It is common work to work with project directories that contain these files
● Search order of changes in configuration files are as follow:
○ ANSIBLE_CONFIG (environment variable if set)
○ ansible.cfg (in the current directory)
○ ~/.ansible.cfg (in the home directory)
○ /etc/ansible/ansible.cfg
● Create Base directory and add ansible.cfg & inventory files as follows
● Change directory to the Base dir and run the following command to check it all works:
○ $ ansible all --list-hosts
Inventory file
● Inventory contains a list of hostnames or IP addresses
● Dynamic inventory is discussed later
● Default inventory file: /etc/ansible/hosts
Inventory file sample
INI format
mail.example.com
[webservers]
foo.example.com
bar.example.com
[dbservers]
one.example.com
two.example.com
three.example.com
YAML format
all:
hosts:
mail.example.com:
children:
webservers:
hosts:
foo.example.com:
bar.example.com:
dbservers:
hosts:
one.example.com:
two.example.com:
three.example.com:
Base directory
ansible.cfg inventory
2.c) Ad-hoc Commands
Iman darabi
https://www.linkedin.com/in/imandarabi/
Ad-hoc Commands Summarized
● Ansible modules can be called using the ansible command
● Use ansible-doc -l for a list of modules, and ansible-doc modulename for
information
● Specify which module to use, using -m
● The command module is default, and does not have to be specified
○ ansible all ping
● about module options
○ Ansible <category_inventory> -m <module_name> -a <module_arg>
○ Ansible all -m command -a id
○ Ansible all -m shell -a env
2.d) working with modules
Iman darabi
https://www.linkedin.com/in/imandarabi/
modules
● Modules are reusable, standalone scripts that can be used by the Ansible API,
the ansible command, or the ansible-playbook command.
● Modules provide a defined interface, accepting arguments and returning
information to Ansible by printing a JSON string to stdout before exiting.
Module usage
Ad-hoc command
# ansible all -m apt -a "name=htop
state=present"
Playbook
hosts: all
tasks:
- name: install htop application
apt:
name: htop
state: present
2.e) Understanding
Playbooks
Iman darabi
https://www.linkedin.com/in/imandarabi/
playbooks
● A list of instruction describing the steps to bring your server to a certain
configuration stat
● Playbook - A single YAML file
○ Play - Defines a set of activities (task) to be run on hosts
■ Task - An action to be performed on the host
● Execute a command
● Run a script
● Install a package
● Shutdown/Restart
Playbook format
# simple Ansible Playbook.yml
---
-
name: Play 1
hosts: localhost
tasks:
- name: Execute command ‘date’
command: date
- name: Execute script on server
script: test_script.sh
-
name: Play 2
hosts: localhost
tasks:
- name: Install web service
yum:
name: httpd
state: present
Playbook keywords
# simple Ansible Playbook.yml
---
-
name: Play 1
hosts: localhost
tasks:
- name: Execute command ‘date’
command: date
- name: Execute script on server
script: test_script.sh
-
name: Play 2
hosts: localhost
tasks:
- name: Install web service
yum:
name: httpd
state: present
Playbook keywords
● name: Identifier. Can be used for documentation, in or tasks/handlers.
● hosts: A list of groups, hosts or host pattern that translates into a list of hosts that are
the play’s target.
● tasks: Main list of tasks to execute in the play, they run after roles and before
post_tasks.
● vars, when, tags, until, async, become, delegate_to and …
○ https://docs.ansible.com/ansible/latest/reference_appendices/playbooks_keywords.html
Playbooks VS shell scripts
---
- hosts: all
tasks:
- name: Install Apache
Command: yum install httpd
- name: Copy configuration files.
command: >
Cp /<path>/httpd.conf /<path2>/httpd.conf
- name: start apache service
command: systemctl start httpd
echo ‘Install Apache’
yum install --quiet -y httpd
cp /<path>/httpd.conf /<path2>/httpd.conf
echo ‘start apache service’
Systemctl start httpd
Simple VS complex playbooks
# Simple Ansible Playbook
- Run command1 on server1
- Run command2 on server2
- …
- Run command10 on server10
- Restarting server1
- Restarting server2
- …
- Restarting server10
# Complex Ansible Playbook
- Deploy 50 VMs on Public Cloud
- Deploy 50 VMs on Private Cloud
- Provision Storage to all VMs
- Setup Cluster Configuration
- Install and Config Backup clients
- Update CMDB database
- …
2.f) variables, include,
imports and facts
Iman darabi
https://www.linkedin.com/in/imandarabi/
Understanding Variables and Inclusions
● Variables are what makes ansible flexible: set a variable locally to have it behave
differently on different managed hosts
○ Variables can be set through the inventory file, at the top of a playbook or using
inclusions
● Ansible facts can be used like variables as well:
● Inclusions allow you to make ansible playbooks more modular
○ Instead of writing one big playbook, you can work with several small playbooks, where
each playbook is used to focus on a specific set of tasks.
Including and Importing
include: install-packages.yml import_tasks: install-packages.yml
● All import* statements are pre-processed at the time playbooks are parsed.
● All include* statements are processed as they are encountered during the
execution of the playbook.
Facts
● As we’ve already seen, when Ansible runs a playbook, before the first task runs, this
happens:
● GATHERING FACTS **************************************************
● ok: [servername]
● When Ansible gather facts, it connects to the host and queries the host for all kind of
details about the host: CPU arch, operating system, IP address, memory, disk info …
● This information is stored in variables that are called facts, and they behave just like
any other variable does.
Facts - ad-hoc samples
● Display facts from all hosts and store them indexed by I(hostname) at C(/tmp/facts).
○ # ansible all -m setup --tree /tmp/facts
● Display only facts regarding memory found by ansible on all hosts and output them.
○ # ansible all -m setup -a 'filter=ansible_*_mb'
● Display only facts about certain interfaces.
○ # ansible all -m setup -a 'filter=ansible_eth[0-2]'
Special variables
● These variables cannot be set directly by the user; Ansible will always override them to
reflect internal state.
● Inventory_hostname
○ The inventory name for the ‘current’ host being iterated over in the play
● Inventory_hostname_short
○ The short version of inventory_hostname
● ansible_distribution
○ Os distribution like “Debian” or “Ubuntu” or “CentOS”
● Reference:
○ https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html
2.g) Understanding Jinja2
Templates
Iman darabi
https://www.linkedin.com/in/imandarabi/
Jinja2 Templates
● Jinja2 templates are Python-based templates that are used to put host-specific data on
hosts, using generic YAML and Jinja2 files
● Jinja2 templates are used to modify Yaml files before they are sent to the managed
host
● Jinja2 can also be used to reference variables in playbooks
● As advanced usage, Jinja2 loops and conditionals can be used in templates to
generate very specific code
● The host-specific data is generated through variables or facts
3) working with roles
Iman darabi
https://www.linkedin.com/in/imandarabi/
3.a) Understanding role structure
● Idea: if you design in a structured way, everybody knows where to find what !
● Ansible roles provide uniform ways to load tasks, handlers, and variables from external
files
● A role typically corresponds to the type of service that is offered (web, database, etc.)
● The purpose is to keep the size of playbooks manageable
● Roles use a specific directory structure, with locations for default, handlers, tasks,
templates, and variables
Role directory structure contents
● defaults: contains a main.yml with default values for variables
● files: static files that are referenced by role tasks
● handlers: contains a main.yml with handler definitions
● meta: contains a main.yaml with informations about the role, including author,
license, platforms, and dependencies
● tasks: has a main.yml with task definitions
● vars: has a main.yml file with role variable definitions
Understanding role variables
● Role variables are defined in vars/main.yml
● These variables have a high priority and cannot be overridden by inventory
variables
● Default variables can be defined in defaults/main.yml and have the lowest
precedence
● Use default variables only if you intend to have the variable overridden
somewhere else
○ Overriding variables is common as roles are used as templates, where
specific variables may be overridden in specific playbooks
Using Roles
● Roles are easily used from playbooks:
---
- hosts: node2.ansible.local
roles:
- role1
- role2
3.b) Creating roles
● Creating roles involves the following steps
○ Create the role structure
○ Define the role content
○ Use the role in a playbook
● Use the ansible-galaxy init <role_name> command to automate creating the role
directory structure
3.c) Deploying roles with ansible galaxy
● Ansible Galaxy ( http://galaxy.ansible.com ) is the community resource for getting and
publishing roles
● Many roles that are ready to use are offered for download
● Roles that are still in development can be followed by watchers
● Use ansible-galaxy command to install roles from galaxy.ansible.com
○ Ansible-galaxy install <rolename>
http://galaxy.ansible.com
3.d) Using the ansible galaxy CLI utility
● # Ansible-galaxy search
○ Search for roles
● Use options --author, --platforms and --galaxy-tags to narrow down search results
● # ansible-galaxy search “install mariadb” --platforms el
● # ansible-galaxy info
○ Provides information about roles
○ # ansible galaxy info f500.mariadb55
● # ansible-galaxy install <rolename>
○ Download a role and install it on the control node in ~/.ansible/roles
End of part A
Iman darabi
https://www.linkedin.com/in/imandarabi/

Weitere ähnliche Inhalte

Was ist angesagt?

Configuration management and orchestration with Salt
Configuration management and orchestration with SaltConfiguration management and orchestration with Salt
Configuration management and orchestration with SaltAnirban Saha
 
Process scheduling
Process schedulingProcess scheduling
Process schedulingHao-Ran Liu
 
Treasure Data Summer Internship Final Report
Treasure Data Summer Internship Final ReportTreasure Data Summer Internship Final Report
Treasure Data Summer Internship Final ReportRitta Narita
 
Fluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellFluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellN Masahiro
 
Deploying Foreman in Enterprise Environments
Deploying Foreman in Enterprise EnvironmentsDeploying Foreman in Enterprise Environments
Deploying Foreman in Enterprise Environmentsinovex GmbH
 
Fluentd v0.14 Plugin API Details
Fluentd v0.14 Plugin API DetailsFluentd v0.14 Plugin API Details
Fluentd v0.14 Plugin API DetailsSATOSHI TAGOMORI
 
Fluentd at HKOScon
Fluentd at HKOSconFluentd at HKOScon
Fluentd at HKOSconN Masahiro
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scriptingTony Fabeen
 
Can you upgrade to Puppet 4.x?
Can you upgrade to Puppet 4.x?Can you upgrade to Puppet 4.x?
Can you upgrade to Puppet 4.x?Martin Alfke
 
Fluentd Meetup 2016 - ServerEngine Integration & Windows support
Fluentd Meetup 2016 - ServerEngine Integration & Windows supportFluentd Meetup 2016 - ServerEngine Integration & Windows support
Fluentd Meetup 2016 - ServerEngine Integration & Windows supportRitta Narita
 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Evel xf
 
JActor Cluster Platform
JActor Cluster PlatformJActor Cluster Platform
JActor Cluster PlatformBill La Forge
 
Fluentd v0.14 Overview
Fluentd v0.14 OverviewFluentd v0.14 Overview
Fluentd v0.14 OverviewN Masahiro
 
Foreman in your datacenter
Foreman in your datacenterForeman in your datacenter
Foreman in your datacenterlzap
 
I/O, You Own: Regaining Control of Your Disk in the Presence of Bootkits
I/O, You Own: Regaining Control of Your Disk in the Presence of BootkitsI/O, You Own: Regaining Control of Your Disk in the Presence of Bootkits
I/O, You Own: Regaining Control of Your Disk in the Presence of BootkitsCrowdStrike
 
Running at Scale: Practical Performance Tuning with Puppet - PuppetConf 2013
Running at Scale: Practical Performance Tuning with Puppet - PuppetConf 2013Running at Scale: Practical Performance Tuning with Puppet - PuppetConf 2013
Running at Scale: Practical Performance Tuning with Puppet - PuppetConf 2013Puppet
 
Installation of LAMP Server with Ubuntu 14.10 Server Edition
Installation of LAMP Server with Ubuntu 14.10 Server EditionInstallation of LAMP Server with Ubuntu 14.10 Server Edition
Installation of LAMP Server with Ubuntu 14.10 Server EditionSammy Fung
 
PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12Andrew Dunstan
 
The SaltStack Pub Crawl - Fosscomm 2016
The SaltStack Pub Crawl - Fosscomm 2016The SaltStack Pub Crawl - Fosscomm 2016
The SaltStack Pub Crawl - Fosscomm 2016effie mouzeli
 

Was ist angesagt? (20)

Configuration management and orchestration with Salt
Configuration management and orchestration with SaltConfiguration management and orchestration with Salt
Configuration management and orchestration with Salt
 
Process scheduling
Process schedulingProcess scheduling
Process scheduling
 
Treasure Data Summer Internship Final Report
Treasure Data Summer Internship Final ReportTreasure Data Summer Internship Final Report
Treasure Data Summer Internship Final Report
 
Fluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshellFluentd v1.0 in a nutshell
Fluentd v1.0 in a nutshell
 
Deploying Foreman in Enterprise Environments
Deploying Foreman in Enterprise EnvironmentsDeploying Foreman in Enterprise Environments
Deploying Foreman in Enterprise Environments
 
Fluentd v0.14 Plugin API Details
Fluentd v0.14 Plugin API DetailsFluentd v0.14 Plugin API Details
Fluentd v0.14 Plugin API Details
 
Puppi. Puppet strings to the shell
Puppi. Puppet strings to the shellPuppi. Puppet strings to the shell
Puppi. Puppet strings to the shell
 
Fluentd at HKOScon
Fluentd at HKOSconFluentd at HKOScon
Fluentd at HKOScon
 
Devinsampa nginx-scripting
Devinsampa nginx-scriptingDevinsampa nginx-scripting
Devinsampa nginx-scripting
 
Can you upgrade to Puppet 4.x?
Can you upgrade to Puppet 4.x?Can you upgrade to Puppet 4.x?
Can you upgrade to Puppet 4.x?
 
Fluentd Meetup 2016 - ServerEngine Integration & Windows support
Fluentd Meetup 2016 - ServerEngine Integration & Windows supportFluentd Meetup 2016 - ServerEngine Integration & Windows support
Fluentd Meetup 2016 - ServerEngine Integration & Windows support
 
Stackless Python In Eve
Stackless Python In EveStackless Python In Eve
Stackless Python In Eve
 
JActor Cluster Platform
JActor Cluster PlatformJActor Cluster Platform
JActor Cluster Platform
 
Fluentd v0.14 Overview
Fluentd v0.14 OverviewFluentd v0.14 Overview
Fluentd v0.14 Overview
 
Foreman in your datacenter
Foreman in your datacenterForeman in your datacenter
Foreman in your datacenter
 
I/O, You Own: Regaining Control of Your Disk in the Presence of Bootkits
I/O, You Own: Regaining Control of Your Disk in the Presence of BootkitsI/O, You Own: Regaining Control of Your Disk in the Presence of Bootkits
I/O, You Own: Regaining Control of Your Disk in the Presence of Bootkits
 
Running at Scale: Practical Performance Tuning with Puppet - PuppetConf 2013
Running at Scale: Practical Performance Tuning with Puppet - PuppetConf 2013Running at Scale: Practical Performance Tuning with Puppet - PuppetConf 2013
Running at Scale: Practical Performance Tuning with Puppet - PuppetConf 2013
 
Installation of LAMP Server with Ubuntu 14.10 Server Edition
Installation of LAMP Server with Ubuntu 14.10 Server EditionInstallation of LAMP Server with Ubuntu 14.10 Server Edition
Installation of LAMP Server with Ubuntu 14.10 Server Edition
 
PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12PostgreSQL 8.4 TriLUG 2009-11-12
PostgreSQL 8.4 TriLUG 2009-11-12
 
The SaltStack Pub Crawl - Fosscomm 2016
The SaltStack Pub Crawl - Fosscomm 2016The SaltStack Pub Crawl - Fosscomm 2016
The SaltStack Pub Crawl - Fosscomm 2016
 

Ähnlich wie Automating with ansible (Part A)

#OktoCampus - Workshop : An introduction to Ansible
#OktoCampus - Workshop : An introduction to Ansible#OktoCampus - Workshop : An introduction to Ansible
#OktoCampus - Workshop : An introduction to AnsibleCédric Delgehier
 
Introduction to ansible
Introduction to ansibleIntroduction to ansible
Introduction to ansibleOmid Vahdaty
 
Introduction to Ansible - (dev ops for people who hate devops)
Introduction to Ansible - (dev ops for people who hate devops)Introduction to Ansible - (dev ops for people who hate devops)
Introduction to Ansible - (dev ops for people who hate devops)Jude A. Goonawardena
 
Ansible Tutorial.pdf
Ansible Tutorial.pdfAnsible Tutorial.pdf
Ansible Tutorial.pdfNigussMehari4
 
ansible : Infrastructure automation,idempotent and more
ansible : Infrastructure automation,idempotent and moreansible : Infrastructure automation,idempotent and more
ansible : Infrastructure automation,idempotent and moreSabarinath Gnanasekar
 
Introduction to Ansible - Peter Halligan
Introduction to Ansible - Peter HalliganIntroduction to Ansible - Peter Halligan
Introduction to Ansible - Peter HalliganCorkOpenTech
 
A tour of Ansible
A tour of AnsibleA tour of Ansible
A tour of AnsibleDevOps Ltd.
 
Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)Chu-Siang Lai
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansibleGeorge Shuklin
 
PLNOG Automation@Brainly
PLNOG Automation@BrainlyPLNOG Automation@Brainly
PLNOG Automation@Brainlyvespian_256
 
PLNOG14: Automation at Brainly - Paweł Rozlach
PLNOG14: Automation at Brainly - Paweł RozlachPLNOG14: Automation at Brainly - Paweł Rozlach
PLNOG14: Automation at Brainly - Paweł RozlachPROIDEA
 
Introduction to ansible
Introduction to ansibleIntroduction to ansible
Introduction to ansibleMukul Malhotra
 
Introduction to Ansible
Introduction to AnsibleIntroduction to Ansible
Introduction to AnsibleCoreStack
 
Getting Started with Ansible - Jake.pdf
Getting Started with Ansible - Jake.pdfGetting Started with Ansible - Jake.pdf
Getting Started with Ansible - Jake.pdfssuserd254491
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleStein Inge Morisbak
 

Ähnlich wie Automating with ansible (Part A) (20)

#OktoCampus - Workshop : An introduction to Ansible
#OktoCampus - Workshop : An introduction to Ansible#OktoCampus - Workshop : An introduction to Ansible
#OktoCampus - Workshop : An introduction to Ansible
 
Introduction to ansible
Introduction to ansibleIntroduction to ansible
Introduction to ansible
 
Introduction to Ansible - (dev ops for people who hate devops)
Introduction to Ansible - (dev ops for people who hate devops)Introduction to Ansible - (dev ops for people who hate devops)
Introduction to Ansible - (dev ops for people who hate devops)
 
Ansible intro
Ansible introAnsible intro
Ansible intro
 
Ansible Tutorial.pdf
Ansible Tutorial.pdfAnsible Tutorial.pdf
Ansible Tutorial.pdf
 
Ansible - Hands on Training
Ansible - Hands on TrainingAnsible - Hands on Training
Ansible - Hands on Training
 
ansible : Infrastructure automation,idempotent and more
ansible : Infrastructure automation,idempotent and moreansible : Infrastructure automation,idempotent and more
ansible : Infrastructure automation,idempotent and more
 
Introduction to Ansible - Peter Halligan
Introduction to Ansible - Peter HalliganIntroduction to Ansible - Peter Halligan
Introduction to Ansible - Peter Halligan
 
A tour of Ansible
A tour of AnsibleA tour of Ansible
A tour of Ansible
 
Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)Automate with Ansible basic (2/e, English)
Automate with Ansible basic (2/e, English)
 
Best practices for ansible
Best practices for ansibleBest practices for ansible
Best practices for ansible
 
PLNOG Automation@Brainly
PLNOG Automation@BrainlyPLNOG Automation@Brainly
PLNOG Automation@Brainly
 
PLNOG14: Automation at Brainly - Paweł Rozlach
PLNOG14: Automation at Brainly - Paweł RozlachPLNOG14: Automation at Brainly - Paweł Rozlach
PLNOG14: Automation at Brainly - Paweł Rozlach
 
Ansible 202 - sysarmy
Ansible 202 - sysarmyAnsible 202 - sysarmy
Ansible 202 - sysarmy
 
Installing AtoM with Ansible
Installing AtoM with AnsibleInstalling AtoM with Ansible
Installing AtoM with Ansible
 
Ansible_Basics_ppt.pdf
Ansible_Basics_ppt.pdfAnsible_Basics_ppt.pdf
Ansible_Basics_ppt.pdf
 
Introduction to ansible
Introduction to ansibleIntroduction to ansible
Introduction to ansible
 
Introduction to Ansible
Introduction to AnsibleIntroduction to Ansible
Introduction to Ansible
 
Getting Started with Ansible - Jake.pdf
Getting Started with Ansible - Jake.pdfGetting Started with Ansible - Jake.pdf
Getting Started with Ansible - Jake.pdf
 
Zero Downtime Deployment with Ansible
Zero Downtime Deployment with AnsibleZero Downtime Deployment with Ansible
Zero Downtime Deployment with Ansible
 

Kürzlich hochgeladen

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Christo Ananth
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxupamatechverse
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...ranjana rawat
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINESIVASHANKAR N
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSRajkumarAkumalla
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...ranjana rawat
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escortsranjana rawat
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)Suman Mia
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations120cr0395
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )Tsuyoshi Horigome
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 

Kürzlich hochgeladen (20)

Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
Call for Papers - African Journal of Biological Sciences, E-ISSN: 2663-2187, ...
 
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINEDJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
DJARUM4D - SLOT GACOR ONLINE | SLOT DEMO ONLINE
 
Introduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptxIntroduction to IEEE STANDARDS and its different types.pptx
Introduction to IEEE STANDARDS and its different types.pptx
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
The Most Attractive Pune Call Girls Budhwar Peth 8250192130 Will You Miss Thi...
 
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINEMANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
MANUFACTURING PROCESS-II UNIT-2 LATHE MACHINE
 
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICSHARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
HARDNESS, FRACTURE TOUGHNESS AND STRENGTH OF CERAMICS
 
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
(SHREYA) Chakan Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Esc...
 
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
(MEERA) Dapodi Call Girls Just Call 7001035870 [ Cash on Delivery ] Pune Escorts
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)Software Development Life Cycle By  Team Orange (Dept. of Pharmacy)
Software Development Life Cycle By Team Orange (Dept. of Pharmacy)
 
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANVI) Koregaon Park Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
Extrusion Processes and Their Limitations
Extrusion Processes and Their LimitationsExtrusion Processes and Their Limitations
Extrusion Processes and Their Limitations
 
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
Call Girls in Nagpur Suman Call 7001035870 Meet With Nagpur Escorts
 
SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )SPICE PARK APR2024 ( 6,793 SPICE Models )
SPICE PARK APR2024 ( 6,793 SPICE Models )
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service NashikCall Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
Call Girls Service Nashik Vaishnavi 7001305949 Independent Escort Service Nashik
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(ANJALI) Dange Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(PRIYA) Rajgurunagar Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 

Automating with ansible (Part A)

  • 1. Automating with ansible (part A) Iman darabi https://www.linkedin.com/in/imandarabi/
  • 2. Table of contents ( part A - Basics ) 1. Introduction a. Definitions b. Why ansible c. Understanding YAML ■ YAML Data presentation syntax 2. Basics getting started a. Setting up ansible b. Managing configuration and Inventory c. Ad-hoc commands d. Working with modules e. Understanding playbooks f. Variables, includes, imports and facts g. Understanding Jinja2 templates 3. Working with roles a. Understanding role structure b. Creating roles c. Deploying roles with ansible galaxy d. Using the ansible galaxy CLI utility Iman Darabi https://www.linkedin.com/in/imandarabi/
  • 3. Table of contents ( part B - Advanced ) 1. Managing task control a. Using with_items b. Using Nested Loops c. Using the when statement d. Registering variables e. Working with handlers f. Working with tags g. Dealing with errors h. Using ansible blocks 2. Ansible vault a. Understanding ansible Vault b. Working with encrypted files c. Executing with ansible vault 3. Optimizing ansible a. Selecting hosts with host patterns b. Configuring delegation c. Delegation outside the inventory d. Configuring parallelism 4. Troubleshooting ansible a. Understanding ansible logging b. Troubleshooting playbooks c. Troubleshooting managed hosts Iman Darabi https://www.linkedin.com/in/imandarabi/
  • 5. 1.a) Definitions ● Simple automation language that can perfectly describe an IT application infrastructure in ansible playbooks ● Open-source software provisioning, configuration management, and application- deployment tool (wikipedia). ● Initial release: February 20, 2012 ● Repository: github.com/ansible/ansible ● Ansible, an open source community project sponsored by Red Hat, ● Other configuration management tools: ○ Puppet ○ Chef ○ Juju ○ Salt …
  • 6. 1.b) Why ansible ● Minimal learning required ○ Human readable automation ○ No special coding skills needed ○ Tasks executed in order ● Only OpenSSH and Python are required on the managed nodes ● Agent-less ( no exploit or update ) ● Powerful ○ App deployment ○ Configuration management ○ Workflow orchestration
  • 8. What is YAML? YAML Ain’t Markup Language
  • 9. ● YAML is a human-readable data serialization standard that can be used in conjunction with all programming languages and is often used to write configuration files. ● YAML has no executable commands. It is simply a data-representation language. ● It is commonly used for configuration files and in applications where data is being stored or transmitted. ● YAML files should end in .yaml/.yml ● YAML is case sensitive. ● YAML does not allow the use of tabs. Spaces are used instead as tabs are not universally supported. ● We use YAML because it is easier for humans to read and write than other common data formats like XML or JSON
  • 11. YAML style comparison XML <Servers> <Server> <name>SERVER1</name> <owner>iman</owner> <created>1399</created> </Server> </Servers> JSON { Servers: [ { name: Server1, owner: iman, created: 1399, status: active, } ] } YAML Servers: - Name: Server1 owner: iman created: 1399 status: active
  • 12. Document separator --- <- Document header … <- Document terminator
  • 13. Data type - key value pair ● Key value pairs are defined using a colon ( : ) and a space ( ) --- Fruit: Apple Vegetable: Carrot Liquid: Water Meet: Chiken
  • 14. Data type - Array / Lists ● Dash “-” indicates elements of lists # Block Format Fruites: - Orange - Apple # Inline Format Fruits: [ Orange, Apple ]
  • 15. Data type - Dictionary / Map ● There must be equal number of blank space ( ) for each of properties Banana: Calories: 105 Fat: 0.4 Grapes: Calories: 62 Fat: 0.3
  • 16. Data type - Strings data: | Each of these Newlines Will be broken up data: > This text is wrapped and will be formed into a single paragraph
  • 19. 2.a) Setting up ansible Iman darabi https://www.linkedin.com/in/imandarabi/
  • 20. Setting up controller and remote hosts 1. Install Ansible software a. Only the control node needs ansible i. # apt install ansible b. Managed hosts need Python and SSH 2. Create a non-root user and perform all tasks as this user 3. Set up SSH for communications 4. Configure sudo a. user ALL=(ALL) NOPASSWD: ALL
  • 21. 2.b) Managing configuration and Inventory Iman darabi https://www.linkedin.com/in/imandarabi/
  • 22. configuration file ● ansible.cfg defines ansible configurations ● It is common work to work with project directories that contain these files ● Search order of changes in configuration files are as follow: ○ ANSIBLE_CONFIG (environment variable if set) ○ ansible.cfg (in the current directory) ○ ~/.ansible.cfg (in the home directory) ○ /etc/ansible/ansible.cfg ● Create Base directory and add ansible.cfg & inventory files as follows ● Change directory to the Base dir and run the following command to check it all works: ○ $ ansible all --list-hosts
  • 23. Inventory file ● Inventory contains a list of hostnames or IP addresses ● Dynamic inventory is discussed later ● Default inventory file: /etc/ansible/hosts
  • 24. Inventory file sample INI format mail.example.com [webservers] foo.example.com bar.example.com [dbservers] one.example.com two.example.com three.example.com YAML format all: hosts: mail.example.com: children: webservers: hosts: foo.example.com: bar.example.com: dbservers: hosts: one.example.com: two.example.com: three.example.com:
  • 26. 2.c) Ad-hoc Commands Iman darabi https://www.linkedin.com/in/imandarabi/
  • 27. Ad-hoc Commands Summarized ● Ansible modules can be called using the ansible command ● Use ansible-doc -l for a list of modules, and ansible-doc modulename for information ● Specify which module to use, using -m ● The command module is default, and does not have to be specified ○ ansible all ping ● about module options ○ Ansible <category_inventory> -m <module_name> -a <module_arg> ○ Ansible all -m command -a id ○ Ansible all -m shell -a env
  • 28. 2.d) working with modules Iman darabi https://www.linkedin.com/in/imandarabi/
  • 29. modules ● Modules are reusable, standalone scripts that can be used by the Ansible API, the ansible command, or the ansible-playbook command. ● Modules provide a defined interface, accepting arguments and returning information to Ansible by printing a JSON string to stdout before exiting.
  • 30. Module usage Ad-hoc command # ansible all -m apt -a "name=htop state=present" Playbook hosts: all tasks: - name: install htop application apt: name: htop state: present
  • 32. playbooks ● A list of instruction describing the steps to bring your server to a certain configuration stat ● Playbook - A single YAML file ○ Play - Defines a set of activities (task) to be run on hosts ■ Task - An action to be performed on the host ● Execute a command ● Run a script ● Install a package ● Shutdown/Restart
  • 33. Playbook format # simple Ansible Playbook.yml --- - name: Play 1 hosts: localhost tasks: - name: Execute command ‘date’ command: date - name: Execute script on server script: test_script.sh - name: Play 2 hosts: localhost tasks: - name: Install web service yum: name: httpd state: present
  • 34. Playbook keywords # simple Ansible Playbook.yml --- - name: Play 1 hosts: localhost tasks: - name: Execute command ‘date’ command: date - name: Execute script on server script: test_script.sh - name: Play 2 hosts: localhost tasks: - name: Install web service yum: name: httpd state: present
  • 35. Playbook keywords ● name: Identifier. Can be used for documentation, in or tasks/handlers. ● hosts: A list of groups, hosts or host pattern that translates into a list of hosts that are the play’s target. ● tasks: Main list of tasks to execute in the play, they run after roles and before post_tasks. ● vars, when, tags, until, async, become, delegate_to and … ○ https://docs.ansible.com/ansible/latest/reference_appendices/playbooks_keywords.html
  • 36. Playbooks VS shell scripts --- - hosts: all tasks: - name: Install Apache Command: yum install httpd - name: Copy configuration files. command: > Cp /<path>/httpd.conf /<path2>/httpd.conf - name: start apache service command: systemctl start httpd echo ‘Install Apache’ yum install --quiet -y httpd cp /<path>/httpd.conf /<path2>/httpd.conf echo ‘start apache service’ Systemctl start httpd
  • 37. Simple VS complex playbooks # Simple Ansible Playbook - Run command1 on server1 - Run command2 on server2 - … - Run command10 on server10 - Restarting server1 - Restarting server2 - … - Restarting server10 # Complex Ansible Playbook - Deploy 50 VMs on Public Cloud - Deploy 50 VMs on Private Cloud - Provision Storage to all VMs - Setup Cluster Configuration - Install and Config Backup clients - Update CMDB database - …
  • 38. 2.f) variables, include, imports and facts Iman darabi https://www.linkedin.com/in/imandarabi/
  • 39. Understanding Variables and Inclusions ● Variables are what makes ansible flexible: set a variable locally to have it behave differently on different managed hosts ○ Variables can be set through the inventory file, at the top of a playbook or using inclusions ● Ansible facts can be used like variables as well: ● Inclusions allow you to make ansible playbooks more modular ○ Instead of writing one big playbook, you can work with several small playbooks, where each playbook is used to focus on a specific set of tasks.
  • 40. Including and Importing include: install-packages.yml import_tasks: install-packages.yml ● All import* statements are pre-processed at the time playbooks are parsed. ● All include* statements are processed as they are encountered during the execution of the playbook.
  • 41. Facts ● As we’ve already seen, when Ansible runs a playbook, before the first task runs, this happens: ● GATHERING FACTS ************************************************** ● ok: [servername] ● When Ansible gather facts, it connects to the host and queries the host for all kind of details about the host: CPU arch, operating system, IP address, memory, disk info … ● This information is stored in variables that are called facts, and they behave just like any other variable does.
  • 42. Facts - ad-hoc samples ● Display facts from all hosts and store them indexed by I(hostname) at C(/tmp/facts). ○ # ansible all -m setup --tree /tmp/facts ● Display only facts regarding memory found by ansible on all hosts and output them. ○ # ansible all -m setup -a 'filter=ansible_*_mb' ● Display only facts about certain interfaces. ○ # ansible all -m setup -a 'filter=ansible_eth[0-2]'
  • 43. Special variables ● These variables cannot be set directly by the user; Ansible will always override them to reflect internal state. ● Inventory_hostname ○ The inventory name for the ‘current’ host being iterated over in the play ● Inventory_hostname_short ○ The short version of inventory_hostname ● ansible_distribution ○ Os distribution like “Debian” or “Ubuntu” or “CentOS” ● Reference: ○ https://docs.ansible.com/ansible/latest/reference_appendices/special_variables.html
  • 44. 2.g) Understanding Jinja2 Templates Iman darabi https://www.linkedin.com/in/imandarabi/
  • 45. Jinja2 Templates ● Jinja2 templates are Python-based templates that are used to put host-specific data on hosts, using generic YAML and Jinja2 files ● Jinja2 templates are used to modify Yaml files before they are sent to the managed host ● Jinja2 can also be used to reference variables in playbooks ● As advanced usage, Jinja2 loops and conditionals can be used in templates to generate very specific code ● The host-specific data is generated through variables or facts
  • 46. 3) working with roles Iman darabi https://www.linkedin.com/in/imandarabi/
  • 47. 3.a) Understanding role structure ● Idea: if you design in a structured way, everybody knows where to find what ! ● Ansible roles provide uniform ways to load tasks, handlers, and variables from external files ● A role typically corresponds to the type of service that is offered (web, database, etc.) ● The purpose is to keep the size of playbooks manageable ● Roles use a specific directory structure, with locations for default, handlers, tasks, templates, and variables
  • 48. Role directory structure contents ● defaults: contains a main.yml with default values for variables ● files: static files that are referenced by role tasks ● handlers: contains a main.yml with handler definitions ● meta: contains a main.yaml with informations about the role, including author, license, platforms, and dependencies ● tasks: has a main.yml with task definitions ● vars: has a main.yml file with role variable definitions
  • 49. Understanding role variables ● Role variables are defined in vars/main.yml ● These variables have a high priority and cannot be overridden by inventory variables ● Default variables can be defined in defaults/main.yml and have the lowest precedence ● Use default variables only if you intend to have the variable overridden somewhere else ○ Overriding variables is common as roles are used as templates, where specific variables may be overridden in specific playbooks
  • 50. Using Roles ● Roles are easily used from playbooks: --- - hosts: node2.ansible.local roles: - role1 - role2
  • 51. 3.b) Creating roles ● Creating roles involves the following steps ○ Create the role structure ○ Define the role content ○ Use the role in a playbook ● Use the ansible-galaxy init <role_name> command to automate creating the role directory structure
  • 52. 3.c) Deploying roles with ansible galaxy ● Ansible Galaxy ( http://galaxy.ansible.com ) is the community resource for getting and publishing roles ● Many roles that are ready to use are offered for download ● Roles that are still in development can be followed by watchers ● Use ansible-galaxy command to install roles from galaxy.ansible.com ○ Ansible-galaxy install <rolename>
  • 54. 3.d) Using the ansible galaxy CLI utility ● # Ansible-galaxy search ○ Search for roles ● Use options --author, --platforms and --galaxy-tags to narrow down search results ● # ansible-galaxy search “install mariadb” --platforms el ● # ansible-galaxy info ○ Provides information about roles ○ # ansible galaxy info f500.mariadb55 ● # ansible-galaxy install <rolename> ○ Download a role and install it on the control node in ~/.ansible/roles
  • 55. End of part A Iman darabi https://www.linkedin.com/in/imandarabi/