0% found this document useful (0 votes)
86 views60 pages

Ansible Deeper Dive

Uploaded by

m
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views60 pages

Ansible Deeper Dive

Uploaded by

m
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/ 60

Ansible Deeper Dive

Ivan Pepelnjak ([email protected])


Network Architect

ipSpace.net AG

This material is copyrighted and licensed for the sole use by Mikel Maeso ([email protected] [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Revision history
2017-06-27 Ansible assemble module

2 This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Agenda
• Ansible variables
• Play and task execution
• Error handling

New in January 2017


• File handing
• Task loops
• Exotic Jinja2 filters

3 This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Reference:
Ansible Variables

This material is copyrighted and licensed for the sole use by Mikel Maeso ([email protected] [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Review: How Ansible Playbooks Really Work

Select hosts to be included in this play Also collects Ansible


variables for each host

Gather facts Gather facts Augments Ansible


variables with facts
gathered on hosts
Execute task #1 Execute task #1

How exactly are Ansible variables for each host collected?

5 This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Step#1: Inventory File

[ios]
r1.lab.local location=Rack-1
1.3: Host variables
[nxos]
s1.lab.local location=Rack-2

[all:vars] 1.1: Variables in all group


ansible_user=cisco
ansible_ssh_pass=cisco

[ios:vars] 1.2: Group variables


ansible_device_os=ios

6 This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Step#2 Variable Files

.
├── group_vars
│ ├── ios.yml 2.2: Variables in group_vars/group.yml
│ ├── nxos.yml
│ └── all.yml 2.1: Variables in group_vars/all.yml
└── host_vars
├── r1.lab.local.yml
└── s1.lab.local.yml

2.2: Variables in host_vars/host.yml

7 This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Move the Variables in Host- and Group Variables Files

[ios]
r1.lab.local location=Rack-1 to host_vars/r1.lab.local.yml

[nxos]
s1.lab.local location=Rack-2 to host_vars/s1.lab.local.yml

[all:vars]
ansible_user=cisco
ansible_ssh_pass=cisco
snmp_community=cisco
to group_vars/all.yml
[email protected]
snmp_host=172.16.1.12
syslog_host=172.16.1.12

8 This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Step#3: Gather Facts

Select hosts to be included in this play

Gather facts Gather facts

Execute task #1 Execute task #1

• Setup module executed on remote host


• Facts gathered by setup module added to host Ansible variables
• Optional: Additional facts supplied by /etc/ansible/facts.d on host
• Can be disabled with gather_facts: no

9 This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Step#4: Play Variables

---
- hosts: all
connection: local
vars:
dir: configs
tasks:
- template: src={{ansible_device_os}}/common.j2 
dest={{dir}}/{{inventory_hostname}}.txt

• Plays or tasks can include vars attribute


• vars attribute is a dictionary of variable values
• Most useful with roles and included tasks

10This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Step#5: Included Variable Files
show-arp-secure.yml /secure/passwords

--- ---
- hosts: ios ansible_user: cisco
vars_files: ansible_ssh_pass: cisco
- /secure/passwords
tasks:
- raw: "show arp"

• Tasks and plays can include variables from YAML files


Use cases:
• Publish source code in a repository, keep some variable private
• Include variables created by other plays or playbooks
• Keep play-specific variables out of group files

11This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Using Include Files for Multi-Vendor Support
show-arp-multi-vendor.yml ios/commands.yml
--- ---
- hosts: ios show_arp: show arp
vars_files:
- "{{os}}/commands.yml"
nxos/commands.yml
tasks:
- raw: "{{show_arp}}" ---
show_arp: show ip arp

• Names of included variable files can be Jinja2 expressions


• Use to set playbook variables based on previously-set Ansible variables
• The above scenario is identical to using group files but cleaner

12This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Step#6: Registered Variables and Facts

---
- tasks:
- raw: "show arp"
register: show
- set_fact: extra_fact=123

Registered variables:
• Ansible can store the results of a module in a variable (dictionary)
• Typical keys stored in the dictionary: stdout, stdout_lines
• Use debugging to find what else a module can return
Additional facts:
• set_fact module sets (or replaces) variable values
13This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Set_fact Example

---
- hosts: nxos
tasks:
Create JSON printout
- nxos_command:
commands: "show ip arp | json"
provider: "{{cli}}"
Convert JSON printout to variable
register: result
- set_fact: json_result="{{ result.stdout[0] }}"
- set_fact: arp_table="{{ json_result.TABLE_vrf.
ROW_vrf.TABLE_adj }}"

Dig into the data structure to get ARP table

See Ansible Networking Modules for more details


14This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Step#7: Task and Block Variables

---
- hosts: all
connection: local
tasks:
- template: src={{ansible_device_os}}/common.j2 
dest={{dir}}/{{inventory_hostname}}.txt
vars:
dir: configs

Particularly useful when you have to override standard Ansible variables


(example: username, password, become root) for a single task

15This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Step#8: Extra Variables Specified on Command Line

$ ansible-playbook nexus-enable-api.yml --extra-vars "API=stopped"

Ansible playbook accepts extra variables with --extra-vars argument


• CLI-specified variables override any other variable values

Format
• “key=value key=value key=value” format (quotes are needed for multiple
key/value pairs)
• Quoted JSON string
• “@somefile.json” includes extra variables from JSON file

Use to modify the behavior of a generic playbook

16This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Extra Variables Example

---
- hosts: nxos
tasks:
- nxos_nxapi:
provider: "{{cli}}"
state: "{{API|default('started')}}"

Enable or disable Nexus OS API


• Desired state is specified in the API variable
• Default value of API variable = started (default filter)
• To disable the API, set API variable value with extra-vars

See Ansible Networking Modules for more details


17This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Summary: Ansible Variable Precedence
Inventory file Play variables
• All group variable • Set with vars argument
• Group variables • Included with vars_files
• Host variables argument

Groups and hosts variable files Inter-task variables


• group_vars/all.yml • Registered results
• group_vars/group.yml • Variable set with set_fact
• host_vars/host.yml Task block and individual task
variables
Host facts
Extra variables passed via CLI

18This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Ansible Variable Precedence: What We Ignored
Role defaults Play variables
Inventory file • Set with vars argument
• All group variable • Set with vars_prompt
• Group variables • Included with vars_files
• Host variables argument

Groups and hosts variable files Inter-task variables


• group_vars/all.yml • Registered results
• group_vars/group.yml • Variable set with set_fact
• host_vars/host.yml • Role variables

Host facts Task/task block variables


Extra variables passed via CLI

19This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Saving Variables to Files and Databases


- tasks:
- raw: "{{show arp}}"
register: show
- local_action: >
copy content={{show.stdout}}
dest={{inventory_hostname}}.arp.txt

Ansible does not have a module to save variable(s) to a file


Workarounds include:
• Run copy module on Ansible host and use a variable as file content
• Use template module to generate YAML or JSON file

Demo 12
20This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Reference:
Play and Task
Execution

This material is copyrighted and licensed for the sole use by Mikel Maeso ([email protected] [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
How Ansible Playbooks Really Work

Select hosts to be included in this play

Collect variables for each host

Gather facts Gather facts


Gather facts with setup
module
Execute task #1 Execute task #1
Tasks are executed in
parallel on all hosts
Execute task #2 Execute task #2

Cleanup

22This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Select Hosts to be Included in Play
---
- name: Execute show arp on IOS
hosts: ios
tasks:
- raw: "show arp"

Each play can specify the hosts it’s executed on


• Specific host or a list of hosts (separated with colon), including IP addresses and
wildcards
• One or more groups (union, intersection or difference)
• Jinja2 variables or expressions
Default: all hosts are included in a play
• List of hosts can be further limited with the -l CLI parameter
• -l parameter also takes a file argument (with a list of hosts)

More details @ http://docs.ansible.com/ansible/intro_patterns.html


23This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Conditional Task Execution

---
- name: execute show arp
gather_facts: no
tasks:
- raw: "show arp"
when: "'ios' in group_names"
register: show

Use when parameter to skip a step (task) for a subset of hosts


• when parameter is a Jinja2 expression without curly braces
• The when expression is evaluated for every host in the play
• A task is skipped if the when expression for a host is false
• If a when parameter is a list, all expressions in the list must be true

More details @ http://docs.ansible.com/ansible/playbooks_conditionals.html


24This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Control the Amount of Parallelization

---
- name: generate configurations
connection: local
serial: 10
tasks:
- template: src={{ansible_device_os}}/common.j2 
dest=configs/{{inventory_hostname}}.txt
name: create common part of device configuration

Ansible runs every task in parallel on all hosts in the play


• Might result in an overload when the tasks are executed on Ansible host
• serial parameter limits the number of concurrently-executed tasks
Another use case: rolling updates or software upgrades

More details @ http://docs.ansible.com/ansible/playbooks_delegation.html


25This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Running a Task Once

---
---
- name: Create directory
connection: local
gather_facts: no
tasks:
- file: path=configs state=absent
run_once: true

A task executed on Ansible host might not have to be executed more than once
• Example: delete or create a directory for configuration files
• Solution: use run_once to execute the task once (in context of a random host)

More details @ http://docs.ansible.com/ansible/playbooks_delegation.html


26This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Delegating a Task to Another Host

---
- name: Create directory
tasks:
- file: path=configs state=absent
run_once: true
delegate_to: localhost

A task can be delegated to another host with delegate_to keyword


• Typical use case: reconfigure load balancer before upgrading a server
Also used for: execute action on Ansible host instead of target host
• Use delegate_to: localhost or connection: local
• local_action is the shorthand syntax for delegate_to: localhost

More details @ http://docs.ansible.com/ansible/playbooks_delegation.html


27This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Example: Create Local Files

---
tasks:
- name: Create directory on local file system
local_action: file path={{output}} state=directory
run_once: true

- raw: "{{show_arp}}"
register: show

- name: Save ARP printout in a local file


local_action: >
copy content={{show.stdout}}
dest={{output}}/{{inventory_hostname}}.arp.txt

28This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Example: Use SCP to Copy Configs to Network Devices

---
- hosts: all
name: Deploy configurations
gather_facts: no
tasks:
- name: copy configuration into the device running config
local_action: >
command /usr/bin/sshpass -p {{ansible_ssh_pass}}
/usr/bin/scp configs/{{inventory_hostname}}.txt
{{ansible_user}}@{{inventory_hostname}}:running-config

• command module does not use shell  use full path to scp and sshpass
• Use sshpass to pass password to SCP
• Use ansible_ssh_pass and ansible_user variables to authenticate SCP

29This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Reference:
Error Handling

This material is copyrighted and licensed for the sole use by Mikel Maeso ([email protected] [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Default Ansible Error Handling

Select hosts to be included in this play

Collect variables for each host

Gather facts Gather facts

Execute task #1 Failed task


Any Ansible task can fail

Execute task #2 Task is skipped Subsequent tasks on the


same host are skipped

Play has failed, Ansible stops the playbook

31This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Fail a Play

---
- hosts: ios
tasks:
- ios_command:
commands: show version
provider: "{{cli}}"
register: result
- fail: msg="Wrong Cisco IOS version"
when: "not ('Version {{version}}' in result.stdout[0])"

• fail module fails a play (on a host) with custom error message
• Always use together with when expression

More details in Ansible Networking Modules section


32This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Conditionally Fail a Task

---
- hosts: ios
tasks:
- ios_command:
commands: show version
provider: "{{cli}}"
register: result
failed_when: >
not ('Version {{version}}' in result.stdout[0])

• Some tasks might succeed but are still a failure based on their results
• failed_when expression is evaluated after the task is completed
• Task is failed if the failed_when expression is true
• Equivalent to a subsequent fail task with when condition

More details in http://docs.ansible.com/ansible/playbooks_error_handling.html


33This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Fail the Play after a Task Failure

---
- hosts: ios
any_errors_fatal: true
tasks:
- ios_command:
commands: show version
provider: "{{cli}}"
register: result
failed_when: >
not ('Version {{version}}' in result.stdout[0])

• Task failure does not impact other hosts


• any_errors_fatal parameter stops playbook execution for all hosts after the first
failure
• Use with serial: 1 to stop a process (example: software upgrade) after the first
failure

34This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Assert Assumptions

---
- name: generate device configurations
connection: local
tasks:
- assert:
that:
- syslog_host is defined
- snmp_host is defined
msg: One of the NMS servers is not defined

• Assert module fails if at least one of the that conditions is not true
• Used to validate inputs or device state

More details in http://docs.ansible.com/ansible/test_strategies.html


35This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Error Handling with Task Blocks

---
- hosts: ios
tasks:
- block:
- list of actions
rescue:
- actions to execute on failure
always:
- actions to execute at the end no matter what

• Tasks in a block are execute like regular tasks in a play


• rescue tasks are executed if any task in the block fails
• always tasks are executed regardless of the status of the tasks in the block.

36This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Reference:
Working with Files

This material is copyrighted and licensed for the sole use by Mikel Maeso ([email protected] [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
The File Module

---
- hosts: localhost
connection: local
tasks:
- file: path=version_report.txt state=absent
- file: path=version_report.txt state=touch

• File module usually works on files residing on managed nodes


• Execute the file module on localhost, with connection: local or within
local_action
Parameters:
• path: path to managed file
• state: desired state
• Other parameters: owner, group, mode, se*, src (for symlinks)

38This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
The Target File State

---
- hosts: localhost
connection: local
tasks:
- file: path=version_report.txt state=absent
- file: path=version_report.txt state=touch

absent delete the file if it exists


file regular file, must exist (or file module fails)
touch create an empty file if it doesn’t exist
directory path is a directory (also creates missing intermediate directories)
link
hardlink create symbolic links or hard links (requires src parameter)

39This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Adding Lines to Text Files

- lineinfile:
dest: version_report.txt
regexp: "{{inventory_hostname}}"
line: "{{inventory_hostname}} has wrong IOS version"
when: "not ('Version {{version}}' in result.stdout[0])"

Lineinfile: ensure the specified line is in the specified file

dest  target file


regexp  regexp used to find exiting line in the file
line  new line content
when  execute the task only if the condition is met

The module does not use file locking. Use serial: 1 when using lineinfile on localhost
40This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Adding Blocks to Text Files

- blockinfile:
dest: results.txt
marker: "### {mark} {{inventory_hostname}}"
block: result.stdout[0]

Inserts, replaces or deletes a text block from a text file


• marker text identifying the begin/end of block
({mark} is replaced with BEGIN and END)
• block block content
• backup create a backup copy of the file before modifying it
• create create a file if it doesn’t exist
• insertbefore, insertafter
insert the block before/after specified regular expression

The module does not use file locking. Use serial: 1 when using this module on localhost
41This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Combining Multiple
Files into an
Output File

This material is copyrighted and licensed for the sole use by Mikel Maeso ([email protected] [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Assembling Multiple Files into a Single Output File

- assemble:
src: directory_path
regex: file_matching_pattern (optional)
dest: file_path

Ansible assemble module


• Searches source directory for files (optionally matching the regex pattern)
• Sorts the files in alphabetical order
• (Optionally) creates a backup copy of the destination file
• Combines contents of sorted source files into the destination file
(optionally) separated by delimiter parameter

43This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Assemble File Locations

- assemble:
src: directory_path
regex: file_matching_pattern (optional)
dest: file_path
connection: local

Source directory and destination file are on the managed node


• Use remote_src: true to use source files on Ansible host and write destination
file on managed device
• Use connection: local or delegate_to: localhost to use source and destination
files on Ansible host
• Use absolute paths (for example, using {{inventory_dir}}) with delegate_to
option

44This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Assemble Use Cases

- assemble:
src: directory_path
regex: file_matching_pattern (optional)
dest: file_path
connection: local

• Create configuration snippets with Ansible roles and combine them into device
configuration
• Create reports for every managed device and combine them into a single
summary report

45This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Creating Configurations with Ansible Roles

- name: Generate hub configs


hosts: hubs
roles:
- routing
- base
- dmvpn
- virl

post_tasks:
- assemble:
src: "{{build_dir}}/{{inventory_hostname}}"
dest: "{{build_dir}}/{{inventory_hostname}}.conf"

Source code in https://github.com/ipspace/ansible-examples/tree/master/DMVPN


46This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Summary Report: Configuration Changes

- name: Document changes


copy:
content: |
*************************************
{{component}} changes on {{inventory_hostname}}
*************************************
{% for line in changes.commands %}
{{ line }}
{% endfor %}
dest: "{{configs}}/changes/ 
{{inventory_hostname}}.{{component}}.changes"
delegate_to: localhost

• Changes detected by *_config module are reported in commands property of


changes fact
• Changes are written into per-device changes file

Source code in https://github.com/ipspace/MPLS-infrastructure/tree/master/tools


47This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Summary Report: Configuration Changes

- assemble:
src: {{configs}}/changes
dest: {{configs}}/changes.txt
delegate_to: localhost
run_once: true

Change files created for individual managed devices are combined into a single
changes.txt file
• Assembly process is delegated to localhost and executed only once

Source code in https://github.com/ipspace/MPLS-infrastructure/tree/master/tools


48This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Reference:
Ansible Loops

This material is copyrighted and licensed for the sole use by Mikel Maeso ([email protected] [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Ansible Loops
Sometimes you have to execute a single task multiple times:
• For every item in a list
• For every key/value pair in a dictionary
• For first file found
• Until a certain condition is met

Also possible:
• Looping over nested lists
• Looping over parallel sets of data
• Looping over a list of files (or all files matching a pattern)
• Executing a task block or an included task list in a loop

More details in http://docs.ansible.com/ansible/playbooks_loops.html


50This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Looping over a List

---
- hosts: ios
tasks:
- name: "Ping targets from IOS devices"
ios_command: commands="ping {{item}}" …
register: results
with_items: "{{ping_target}}"
---

Executes the Ansible task for every item in ping_target:
with_items list - '172.16.1.1'
• with_items value must be a list (not a string) - '172.16.1.12'
• item variable contains current item value - '172.16.1.100'
- '172.16.1.105'
• Results variable is a list of module results
(example: results[0].stdout[0])

51This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Looping over a Dictionary

---
- hosts: ios
tasks:
- name: "Ping targets from IOS devices"
ios_command: commands="show standby neigh {{item.key}}" …
register: results
with_dict: "{{intefaces}}"
---

Executes the Ansible task for every key/value pair in interfaces:
with_dict dictionary
Fa0/0: { ip: … }
• item.key contains current key value Fa0/1: { ip: … }
• item.value contains current value
• Use item.value.ip to access interface IP address
• Results variable is a list of module results

52This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Loop Until a Condition Is Met

---
- hosts: ios
tasks:
- name: "Check interface status"
ios_command: commands="show interface dialer 1" …
register: ifstate
until: ifstate.stdout[0].find("protocol is up") > 0
retries: 5
delay: 10

• Executes an Ansible task until the condition is met or the task has been
retried too many times
• Use to check interface status, OSPF/BGP neighbor state…

53This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Execute a Task for First File Found

---
- hosts: all
tasks:
- include_vars: "{{ item }}"
with_first_found:
- nodes.yml
- "{{ inventory_dir }}/nodes.yml"

• Executes the task with item set to the path to the first file found in the list
• Use to specify alternate file paths (locations of configuration files)

54This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Reference:
Exotic Jinja2 Filters

This material is copyrighted and licensed for the sole use by Mikel Maeso ([email protected] [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Extracting Attributes from Lists of Dictionaries


- set_fact:
target_list: "{{ vlans|map(attribute='id')|list }}"

vlans:
- { id: "100", name: "mgmt", subnet: "172.16.1.0/24"}
- { id: "101", name: "web", subnet: "192.168.201.0/24"}

map filter can be used to:


• Extract attributes from list of dictionaries
• Perform a filter operation on every item in the list
example: list-of-integers | map(‘string’)
• Result of a map filter is a generator, to convert it to list use list filter

56This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Set Filters


- fail: msg="Extra VLAN configured on {{inventory_hostname}}"
when: "{{ vlans_list | difference(target_list) }}"

Set filters available in Ansible


• unique return unique values from a list
• union returns elements present in at least one of the lists
• intersect returns elements present in both lists
• difference returns elements present in first list but no in the second one
• symmetric_difference
returns union of differences

Warning: 1 and “1” are different elements


57This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Select a Subset of Elements from a List

name: |
vlans|selectattr('id','equalto',target_vlan)|
map(attribute='name')|first

vlans:
- { id: "100", name: "mgmt", subnet: "172.16.1.0/24"}
- { id: "101", name: "web", subnet: "192.168.201.0/24"}

Required operation:
• Find VLAN name for specified VLAN ID
Steps
• Start with the vlans list of dictionaries
• Select all dictionaries from the list where the id key has value equal to target_vlan
• Select attribute name from all selected dictionaries
• selectattr and map are generators  select the first item from the generator

58This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Extract Data From Text Printouts

- ios_command:
commands: "show ip interface brief | exclude Interface"
register: printout
- set_fact:
intf: |
{{printout.stdout_lines[0] |
map('regex_findall','^([A-Za-z]+[0-9./]+)') |
map('join') | list }}

Steps
• regex_findall performs a regular expression match and returns a list of matched groups
(in our case, the list has a single item, but it’s still a list)
• regex_findall within a map returns a list of groups for every input item  we get a list of
lists of groups
• join within a map merges inner lists into strings  we get a list of strings (interface
names)
• map is a generator  we have to use list filter to make a list out of its output

More @ http://automation.ipspace.net/Example:Ansible_Regex
59This material is copyrighted
© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars
Questions?

Send them to [email protected] or @ioshints

60This material is copyrighted


© ipSpace.net 2016 and licensed for the sole use by Mikel Maeso
Ansible([email protected]
Deeper Dive [85.87.178.33]). More information at http://www.ipSpace.net/Webinars

You might also like