Network Automation With Ansible

Download as pdf or txt
Download as pdf or txt
You are on page 1of 40

Network Automation with

Ansible

April 13, 2018


Objective Fact-check
After this session, you will be able • Limited time (=4 hr.)
to:
• Unfamiliar area
• Write Ansible playbooks to perform
simple tasks • Topic requires practice
• Read and understand basic Ansible
playbooks
• Research on your own to read and
understand complex playbooks
• Research on your own to create
playbooks to perform complex tasks
Speakers Introduction
Attendees Introduction
Break
History of Ansible
Motivation
Agenda Advantages of Ansible
Ansible Market share
Ansible in Devops
Adopting Ansible for Operations
Lessons learned
Ansible Concepts
Lab
Basic Playbooks
Lab
Agenda Break
Lab
Roles
Lab
What is Ansible
• Platform that can automate:
• Software provisioning
• Configuration management
• Application deployment.
• Automation model: 2 components
• Ansible Control Machine: Linux server with Ansible SW
• Managed devices: Devices that are being automated by Ansible.
• Ansible Control Machine talks to devices over SSH (and other
transports)
• Only requirement on on network devices = enable SSH
Ansible Concepts: Config File

• Ansible config file can be • In this session, we will configure


edited for customization the below (uncomment):
• To find your Ansible config file, • inventory = /etc/ansible/hosts
do: • host_key_checking = False
• $ ansible --version • timeout = 10
• retry_files_enabled = False
• Other methods to customize:
• Multiple config files
• Environmental settings
• Command line options
• Roles
Ansible Concepts: Inventory File
• Managed device info is saved
in inventory file Example:

• Inventory file path should be $ cat /etc/ansible/hosts


uncommented in the config file [IOS]
172.16.101.91 ansible_user=cisco ansible_ssh_pass=cisco
• Device info can be listed as [XR]
individual hosts or groups 172.16.101.92 ansible_user=cisco ansible_ssh_pass=cisco

[ALL:children]
• Variables can be assigned to IOS
XR
hosts or groups
• Default groups:
• all
• ungrouped
Ansible Concepts: Modules
• Modules are the nuts and bolts
$ ansible IOS -m raw -a “show ip route sum”
of Ansible automation tasks
• Playbooks use Modules to
execute tasks on the managed $ cat ios_sh_ip_route_sum.yml
devices ---

• Modules are Operating - name: route summary from IOS devices

System specific. hosts: IOS

gather_facts: false
• Example modules:
tasks:
• raw
- raw: sho ip route summary
• ios_command
• ios_config
Ansible Concepts: YAML

• YAML = YAML Ain't Markup Language


• YAML is a data serialization language
• Ansible playbooks are written in YAML
• YAML is intuitive, human readable
• Space indentation is important
• Tab invalid. Use “space” key.
• Check out Youtube links in the reference section
Ansible Concepts: YAML
• Key-value-pair is represented • Key-value pair
as: platform: ASR9K
• <key><colon><space><value> • List
• List: “ordered data”, - show ip int brief
- show ip route summ
represented as:
• <dash><space><data> • Dictionary
name: Verify Router OS
• Dictionary: “non-ordered data” hosts: IOS
• Bunch of key-value pairs gather_facts: false
connection: local
• There can be lists of
dictionaries and dictionary of
lists
Ansible Concepts: Playbooks
Example structure:

• Playbooks are the main means - name: play1


of Ansible automation. hosts: group1
tasks:
• Playbook is a collection of - module1: parameters
plays - module2: parameters
• Each play is a collection tasks
- name: play2
• Each task is a collection of hosts: group2
modules tasks:
- module1: parameters
- module2: parameters
Ansible Concepts: Playbooks

Example: - name: play1


• Capture the below data from hosts: IOS
IOS and XR devices tasks:
• Interface list - raw: show ip int br
• Route summary - raw: sho ip route summ

• Playbook: - name: play2


- play1 hosts: XR
- play2 tasks:
- raw: show ipv4 int br
- raw: sho route summ
Basic Playbooks
Basic Playbooks: ios & xr command module
• Module Names: ios_command & iosxr_command
• Module sends exec command to remote devices and returns the results
• Both modules require local connection execution method
• Required Parameters for ios & xr command module:
- commands option : specify router command to retrieve data
ios_command iosxr_command
--- ---
- name: IOS Module Router Config - name: XR Module Router Config
hosts: IOS hosts: XR
gather_facts: false gather_facts: false
connection: local connection: local

tasks: tasks:
- name: Collect Router Version and Config - name: Collect Router Version and Config
ios_command: iosxr_command:
authorize: yes commands:
commands: - show version
- show version - show ip int bri
- show run
register: value
register: value
- debug: var=value.stdout_lines
- debug: var=value.stdout_lines
Basic Playbooks: Register & Debug
• Basic Playbooks contain register and debug commands.
• Register
- The “register” statement is used to capture the output of a task into a variable.
- In previous example, we are saving the output of the show commands to the variable value.
- Refer: http://docs.ansible.com/ansible/latest/playbooks_conditionals.html#register-variables

• Debug
- The “debug” module prints statements during playbook execution.
- The ”debug” modules takes in a var parameter, which is the variable you want to print.
- Refer: http://docs.ansible.com/ansible/latest/debug_module.html
Basic Playbooks: ios & xr config module
• Module Names: ios_config & iosxr_config
• The config modules are used to configure the cisco routers.
• The modules uses parent and line options to structure the configuration in a
hierarchical way.
• Both modules require local connection execution method.
ios_config iosxr_config
--- ---
- name: IOS Module Router Config - name: XR Module Router Config
hosts: IOS hosts: XR
gather_facts: false gather_facts: false
connection: local connection: local

tasks: tasks:
- name: Configure Interface Setting - name: Configure Interface Setting
ios_config: iosxr_config:
parents: "interface Ethernet1” parents: "interface GigabitEthernet0/0/0/0”
lines: lines:
- "description test” - "description test”
- "ip address 172.31.1.1 255.255.255.0” - "ip address 172.31.1.1 255.255.255.0”
Basic Playbooks: Variables
• Ansible variables are used to store ---

information that will change with each - name: Play 1


host. hosts: IOS

• Variable can be defined: gather_facts: false


• inventory file (ansible_host) vars:
• created directly in the playbook
host: "{{ ansible_host }}"
• created in a separate file and included within
the playbook. username: ”This variable is {{ ansible_user }}"

password: "{{ ansible_ssh_pass }}"


• Variables are defined in playbooks
• Using“{{ }}” the single/double quotes around
double curly brackets
• Using {{ }} the double curly brackets if its part
of a sentence/string
Basic Playbooks: Loops
• Ansible loops are used when repeatedly performing the same task with a set of
different items.
• Ansible with_items loop is a combination of with_ and lookup().

With_items before Ansible Ver 2.5 Updated to loop in Ansible Ver 2.5
tasks: tasks:
- name: Collect Rtr Ver and Cfg - name: Collect Rtr Ver and Cfg
ios_command: ios_command:
authorize: yes authorize: yes
commands: "{{ item }}" commands: "{{ item }}"

with_items: loop:
- show version - show version
- show run - show run
Basic Playbooks: Conditionals
• Ansible conditionals are used in a statement to decide whether to run the task or
not.
• Ansible uses a when clause to dictate a conditional which needs to be true in order
for the task to be performed.

tasks:
- name: Collect Router Version
ios_command:
authorize: yes
commands:
- show ip int bri
when: ansible_user == "cisco"
Automating Network
Operations Tasks
Network Automation Exercises
• Exercise 1 – Configure OSPF on all routers
• Create Ansible playbook to configure OSPF on both IOS and XR router
• Setup pre and post checks to ensure OSPF is working correctly

• Exercise 2 – Automatically backup router’s config to server daily


• Create Ansible playbook to capture router’s running config from all Cisco device types.
• Setup cron job to execute playbook daily and backup router’s config on server.

• Exercise 3 – Create a playbook to compare two files to find the differences


• Create Ansible playbook to find differences between two files.
• Ex: comparing pre-upgrade and post-upgrade router captures.

• Exercise 4 – Ansible Vault


• Use ansible-vault feature to encrypt sensitive data in inventory files.
• Ex: comparing pre-upgrade and post-upgrade router captures.
Conclusion

• Ansible is an open-source, agentless automation tool that can be


leveraged for networks configuration management functions.
• Ansible-playbooks provides capabilities to automate daily operations
tasks.
• Automating repetitive tasks with Ansible can reduce OPEX costs and
improve efficiency.
• With increasing support of modules, it is possible to automate even
more network functions through Ansible.
Ansible Roles
Playbook
---
Efficient Usage
- name: output from IOS routers
hosts: XR
gather_facts: false • We can simplify
connection: local
• Playbook of playbooks
vars:
INTF: loopback1
• We can modularize
tasks:
- name: read config • vars
iosxr_command:
• tasks
commands: show run int {{INTF}}
register: DATA • And other components
- name: print output
debug: var=DATA.stdout_lines • We can reuse
• Modularize components that
are used repeatedly
Playbook of playbooks
Playbook to acquire data from IOS and XR devices:
• We can call playbooks within a
playbook
---

- name: ios config

import_playbook: basic_ios_cmd.yml

- name: xr config

import_playbook: basic_xr_cmd.yml
Roles
[roles/
• Organize a large playbook into reusable file ├── xr-ospf >> Name of this role
structures │ ├── defaults >> default variables for the role
│ │ └── main.yml
• Creates a separation of functions; │ ├── files >> contains files which can be deployed
variables, tasks, & templates in unique │ ├── handlers >> contains handlers
│ │ └── main.yml
directories │ ├── meta >> defines some meta data for this role
│ │ └── main.yml
• Expects files main.yml, and .j2 files in │ ├── README.md
respective folders │ ├── tasks >> contains the list of tasks
│ │ └── main.yml
• File structure can be created manually or │ ├── templates >> contains templates which can be deployed
automatically via ansible CLI – “ansible- │ └── vars>> contains variables used in this role
galaxy”
Roles Style Config
name: read config

iosxr_command:

commands: show run int {{INTF}}

register: OUT

name: print output debug: var=OUT.stdout_lines


Config Generation Using Templates
• Templates contain common and device/role
specific elements
• Ansible uses Jinja 2 templating language
for access to variables and logic/dynamic
expression
• Jinja 2 template files end with .j2 ext

• Ansible can automatically access the Jinja2


templates through its Python API
Role with lists with single variables – Example 1

• Creating a role to generate configuration across multiple devices

- name: execute xr-config role # Executes main.yml in xr-config/tasks/main.yml


hosts: localhost - name: Generate the configuration from templates
gather_facts: no template: src=xr-config-template.j2
dest=/home/cisco/{{item.hostname}}.txt
roles: with_items:
- xr-config - "{{ router_hostname }}"

# playbook for executing role of xr-config # tasks file for xr

# Variable defined in xr-config/vars/main.yml # Leverages j2 template for standard and variable config
hostname {{item.hostname}}
---
service timestamps log datetime msec
router_hostname:
service timestamps debug datetime msec
- { hostname: router1 }
clock timezone {{item.timezone}} {{item.timezone_offset}}
- { hostname: router2 }
clock summer-time {{item.timezone_dst}} recurring
- { hostname: router3 }
...
Jinja2 Template – For loop

• For Loop is a continuous loop until it runs out of inputs variables

• For Loop is invoked using {% for x in y %} syntax and ends with {% endfor %} syntax

# /template/template.j2
{% for INTF in interface_list %}
interface {{INTF}}
cost 1
!
{% endfor %}
!

# /vars/main.yml
Interface_list:
- GigabitEthernet0/0/0/0
- GigabitEthernet0/0/0/1
Hierarchical templates and Block configs

• Base template *.J2 is pulled to specific template through {% extends ”base_config_template.j2"


%} knob
• Configurations from specific template are inserted through block configs that being with { %
block x %} and end with { % endblock % }

## Config lines from lsr_config referring base #/templates/ lsr__config.j2


template
{% block rsvp %}
{% extends "ler_lsr_config_template.j2" %} !
rsvp
{% for interface in interface_list_ler %}
#/templates/ ler_lsr_config_template.j2 interface {{interface}}
hostname {{item.hostname}} bandwidth percentage 100
service timestamps log datetime msecservice !
timestamps debug datetime msectelnet vrf default {% endfor %}
ipv4 server max-servers 10telnet vrf Mgmt-intf {% endblock %}
ipv4 server max-servers 10domain name
virl.infodomain lookup disablecdp
{% block rsvp %}
{% endblock %}
!,,
Lab Exercises

• Exercise A – Create a playbook using role and Jinja2 template


• Utilize roles to generate simple config by passing template and variable

• Exercise B – Create a playbook utilizing looping function


• Utilize roles and Jinja2 template to create a config with looping function

• Exercise C – Create BGP generation for different device types


• Utilize the templates and variables for config generation for different OS type

• Exercise D - Hierarchical Template


• Utilize Hierarchical Template model for config generation
Reference
Reference
• Ansbile user guide URL
• Ansible installation URL
• YAML resources
• http://docs.ansible.com/ansible/latest/YAMLSyntax.html
• http://www.yaml.org
• https://www.youtube.com/watch?v=cdLNKUoMc6c
• https://www.youtube.com/watch?v=U9_gfT0n_5Q

• Ansible Training
• Ansible for the Absolute Beginner @Udemy Click here
• Ansible for Network Engineers @Udemy Click here
• Kirk Byers Ansible training Jive page
• Dcloud lab Ansible for Cisco Nexus Switches v1
Acknowledgement
Acknowledgements

• Some material in this session are sourced from Ansible docs


• http://docs.ansible.com/ansible/latest/index.html
Lab Access
Step-1: SSH to hop-on-server
• IP address: 152.22.242.56
• Port: 8080
• Username: att-ansible
• Password: ansible@ATT18

Step-2: ssh to Ansible server


• $ ssh 172.16.101.X

You might also like