Ansible Networking Workshop

What You Will Learn

Ansible is capable of handling many powerful automation tasks with the flexibility to adapt to many environments and workflows. With Ansible, users can very quickly get up and running to do real work.

  • What is Ansible and The Ansible Way
  • Installing Ansible
  • How Ansible Works and its Key Components
  • Ad-Hoc Commands
  • Playbook Basics
  • Reuse and Redistribution of Ansible Content with Roles

What is Ansible?

It's a simple automation language that can perfectly describe an IT application infrastructure in Ansible Playbooks.

It's an automation engine that runs Ansible Playbooks.

Ansible Tower is an enterprise framework for controlling, securing and managing your Ansible automation with a UI and RESTful API.

The Ansible Way


CROSS PLATFORM – Linux, Windows, UNIX, Cisco, Juniper, Arista, Cumulus
Agentless support for all major OS variants, physical, virtual, cloud and network

HUMAN READABLE – YAML
Perfectly describe and document every aspect of your application environment

DYNAMIC INVENTORIES
Capture all the network hosts 100% of the time, regardless of infrastructure, location, etc.

Ansible: The Language of DevOps

COMMUNICATION IS THE KEY TO DEVOPS.

Ansible is the first automation language
that can be read and written across IT.

Batteries Included

Ansible comes bundled with hundreds of modules for a wide variety of automation tasks

  • cloud
  • containers
  • database
  • files
  • messaging
  • monitoring
  • networking
  • notifications
  • packaging
  • system
  • testing
  • utilities

Installing Ansible


# the most common and preferred way of
# installation
$ sudo pip install ansible

# you will need the EPEL repo configured on
# CentOS, RHEL, or Scientific Linux
$ sudo yum install ansible

# you will need the PPA repo configured on
# Debian or Ubuntu
$ sudo apt-get install ansible
          

Demo Time:
Installing Ansible

How Ansible Works

Plays & Playbooks

Modules & Tasks

Plugins

Inventory

Inventory

Modules

Modules do the actual work in ansible, they are what gets executed in each playbook task. But you can also run a module ad-hoc using the ansible command.

  • *os_facts
  • *os_command
  • *os_config
  • more modules depending on platform
  • Arista EOS = eos_
  • Cisco IOS/IOS-XE = ios_
  • Cisco NX-OS = nxos_
  • Cisco IOS-XR = iosxr_
  • Juniper Junos = junos_
  • VyOS = vyos_

Modules per network platform


  tasks:
    - name: configure eos system properties
      eos_system:
        domain_name: ansible.com
        vrf: management
      when: ansible_network_os == 'eos'

    - name: configure nxos system properties
      nxos_system:
        domain_name: ansible.com
        vrf: management
      when: ansible_network_os == 'nxos'
        

Modules Documentation

http://docs.ansible.com/

Modules Documentation


# List out all modules installed
$ ansible-doc -l
...
ios_banner                                Manage multiline banners on Cisco IOS devices
ios_command                               Run commands on remote devices running Cisco IOS
ios_config                                Manage Cisco IOS configuration sections
...

# Read documentation for installed module
$ ansible-doc ios_command
> IOS_COMMAND

     Sends arbitrary commands to an ios node and returns the results read from the
     device. This module includes an argument that will cause the module to wait for a
     specific condition before returning or timing out if the condition is not met. This
     module does not support running commands in configuration mode. Please use
     [ios_config] to configure IOS devices.

Options (= is mandatory):
...
          

Modules: Run Commands

If Ansible doesn’t have a module that suits your needs there are the “run command” modules:


  • command: Takes the command and executes it on the host. The most secure and predictable.
  • ios_command: Sends arbitrary commands to an ios node and returns the results read from the device.


NOTE: Unlike standard modules, run commands have no concept of desired state and should only be used as a last resort.

How it works

Inventory

Inventory is a collection of hosts (nodes) with associated data and groupings that Ansible can connect and manage.

  • Hosts (nodes)
  • Groups
  • Inventory-specific data (variables)
  • Static or dynamic sources

Static Inventory Example

This inventory will work but is not human readable.

10.42.0.2
10.42.0.6
10.42.0.7
10.42.0.8
10.42.0.100
host.example.com
          

Static Inventory Example


[all:vars]
ansible_user=lcage
ansible_ssh_pass=ansible
ansible_port=22

[routers]
rtr1 ansible_host=54.174.116.49 ansible_user=ec2-user ansible_network_os=ios
rtr2 ansible_host=54.86.17.101 ansible_user=ec2-user ansible_network_os=ios
[hosts]
host1 ansible_host=34.224.57.27 ansible_user=ec2-user
[control]
ansible ansible_host=34.228.79.198 ansible_user=ec2-user
          

Ad-Hoc Commands

An ad-hoc command is a single Ansible task to perform quickly, but don’t want to save for later.

Ad-Hoc Commands: Common Options

  • -m MODULE_NAME, --module-name=MODULE_NAME
    Module name to execute the ad-hoc command
  • -a MODULE_ARGS, --args=MODULE_ARGS
    Module arguments for the ad-hoc command
  • -b, --become
    Run ad-hoc command with elevated rights such as sudo (Linux) or enable (Networking)
  • -e EXTRA_VARS, --extra-vars=EXTRA_VARS
    Set additional variables as key=value or YAML/JSON
  • --version
    Display the version of Ansible
  • --help
    Display the MAN page for the ansible tool

Ad-Hoc Commands


# check all my inventory hosts are ready to be
# managed by Ansible
$ ansible all -m ping

# collect and display the discovered facts
# for the localhost
$ ansible localhost -m setup

# run the uptime command on all hosts in the
# web group
$ ansible web -m command -a "uptime"
          

Discovered Facts

Facts are bits of information derived from examining a host systems that are stored as variables for later use in a play.


$ ansible localhost -m setup
localhost | success >> {
  "ansible_facts": {
      "ansible_default_ipv4": {
          "address": "192.168.1.37",
          "alias": "wlan0",
          "gateway": "192.168.1.1",
          "interface": "wlan0",
          "macaddress": "c4:85:08:3b:a9:16",
          "mtu": 1500,
          "netmask": "255.255.255.0",
          "network": "192.168.1.0",
          "type": "ether"
      },
          

Network Facts

For non-Linux systems there are vendor specific modules for fact collection.


$ ansible -m ios_facts routers -c network_cli
student1-rtr1 | SUCCESS => {
    "ansible_facts": {
        "ansible_net_all_ipv4_addresses": [
            "172.17.1.238"
        ],
        "ansible_net_all_ipv6_addresses": [],
        "ansible_net_filesystems": [
            "bootflash:"
        ],
        "ansible_net_gather_subset": [
            "hardware",
            "default",
            "interfaces"
        ],
        "ansible_net_hostname": "ip-172-17-1-238",
        "ansible_net_image": "bootflash:csr1000v-universalk9.16.05.01b.SPA.bin",
          

Variables

Ansible can work with metadata from various sources and manage their context in the form of variables.

  • Command line parameters
  • Plays and tasks
  • Files
  • Inventory
  • Discovered facts
  • Roles

Variable Precedence

The order in which the same variable from different sources will override each other.

  1. extra vars
  2. task vars (only for the task)
  3. block vars (only for tasks in block)
  4. role and include vars
  5. play vars_files
  6. play vars_prompt
  7. play vars
  8. set_facts
  1. registered vars
  2. host facts
  3. playbook host_vars
  4. playbook group_vars
  5. inventory host_vars
  6. inventory group_vars
  7. inventory vars
  8. role defaults

Tasks

Tasks are the application of a module to perform a specific unit of work.

  • file: A directory should exist
  • yum: A package should be installed

There are also tasks for network devices as well

  • ios_facts: collect the version of code running on Cisco IOS/IOS-XE
  • ios_system: configure DNS server(s) on Cisco IOS/IOS-XE
  • nxos_snmp_user: add an SNMP user on Cisco NX-OS
  • eos_command: turn off a port on Arista EOS
  • junos_banner: manage the banner on Juniper Junos OS

Example Tasks in a Play


tasks:
  - name: gather ios_facts
    ios_facts:
    register: version

  - debug:
      msg: "{{version}}"

  - name: Backup configuration
    ios_config:
      backup: yes
          

Plays & Playbooks

Plays are ordered sets of tasks to execute against host selections from your inventory. A playbook is a file containing one or more plays.

Playbook Example


---
- name: backup router configurations
  hosts: routers
  connection: network_cli
  gather_facts: no

  tasks:
    - name: gather ios_facts
      ios_facts:
      register: version

    - debug:
        msg: "{{version}}"

    - name: Backup configuration
      ios_config:
        backup: yes
                  

Human-Meaningful Naming


---
- name: backup router configurations
  hosts: routers
  connection: network_cli
  gather_facts: no

  tasks:
    - name: gather ios_facts
      ios_facts:
      register: version

    - debug:
        msg: "{{version}}"

    - name: Backup configuration
      ios_config:
        backup: yes
          

Host Selector


---
- name: backup router configurations
  hosts: routers
  connection: network_cli
  gather_facts: no

  tasks:
    - name: gather ios_facts
      ios_facts:
      register: version

    - debug:
        msg: "{{version}}"

    - name: Backup configuration
      ios_config:
        backup: yes
          

Tasks


---
- name: backup router configurations
  hosts: routers
  connection: network_cli
  gather_facts: no

  tasks:
    - name: gather ios_facts
      ios_facts:
      register: version

    - debug:
        msg: "{{version}}"

    - name: Backup configuration
      ios_config:
        backup: yes
          

Tags

Tags are useful to be able to run a subset of a playbook on-demand.


tasks:
- name: gather ios_facts
  ios_facts:
  register: version
  tags: debug

- debug:
    msg: "{{version}}"
  tags: debug

- name: Backup configuration
  ios_config:
    backup: yes
  tags: 
    - backup
          

Demo Time:
Network Facts

Lab01 - Using Ansible to gather data from network devices

Workshop:
Network Facts

Lab01 - Using Ansible to gather data from network devices

Variables - Recap

  • host vars - variable specific to one host
  • group vars - variables for all hosts within the group

It is possible, but not required, to configure variables in the inventory file.

Inventory ini file


[junos]
vsrx01 ansible_host=an-vsrx-01.rhdemo.io private_ip=172.16.1.1
vsrx02 ansible_host=an-vsrx-02.rhdemo.io private_ip=172.17.1.1

[junos:vars]
ansible_network_os=junos
ansible_password=Ansible

[ios]
ios01 ansible_host=an-ios-01.rhdemo.io

[ios:vars]
ansible_network_os=ios
ansible_become=yes
ansible_become_method=enable
ansible_become_pass=cisco

Host Variables - hostvars


[junos]
vsrx01 ansible_host=an-vsrx-01.rhdemo.io private_ip=172.16.1.1
vsrx02 ansible_host=an-vsrx-02.rhdemo.io private_ip=172.17.1.1

[junos:vars]
ansible_network_os=junos
ansible_password=Ansible

[ios]
ios01 ansible_host=an-ios-01.rhdemo.io

[ios:vars]
ansible_network_os=ios
ansible_become=yes
ansible_become_method=enable
ansible_become_pass=cisco

Group Variables - groupvars


[junos]
vsrx01 ansible_host=an-vsrx-01.rhdemo.io private_ip=172.16.1.1
vsrx02 ansible_host=an-vsrx-02.rhdemo.io private_ip=172.17.1.1

[junos:vars]
ansible_network_os=junos
ansible_password=Ansible

[ios]
ios01 ansible_host=an-ios-01.rhdemo.io

[ios:vars]
ansible_network_os=ios
ansible_become=yes
ansible_become_method=enable
ansible_become_pass=cisco

Conditionals

Ansible supports the conditional execution of a task based on the run-time evaluation of variable, fact, or previous task result.


- name: configure interface settings
  ios_config:
    lines:
      - description shutdown by Ansible
      - shutdown
    parents: interface GigabitEthernet2
  when: ansible_network_os == "ios"
          

Multi-Platform Playbooks


   - name: run on eos
     include_tasks: tasks/eos.yml
     when: ansible_network_os == eos

   - name: run on ios
     include_tasks: tasks/ios.yml
     when: ansible_network_os == ios

   - name: run on junos
     include_tasks: tasks/junos.yml
     when: ansible_network_os == junos

   - name: run on nxos
     include_tasks: tasks/nxos.yml
     when: ansible_network_os == iosxr
        

Using a config module

Manage configuration on a network platform

- name: configure top level configuration
  ios_config:
    lines: hostname {{ inventory_hostname }}

- name: configure interface settings
  ios_config:
    lines:
      - description test interface
      - ip address 172.31.1.1 255.255.255.0
    parents: interface Ethernet1

- name: configure from a jinja2 template
  ios_config:
    src: config.j2
        

AWS - Network Diagram

As a lab precursor look at the network diagram

Demo Time:
Lab 02 - configs, backups and restores

Workshop:
Lab 02 - configs, backups and restores

Doing More with Playbooks

Here are some more essential playbook features that you can apply:

  • Templates
  • Loops
  • Conditionals
  • Blocks

Templates

Ansible embeds the Jinja2 templating engine that can be used to dynamically:

  • Set and modify play variables
  • Conditional logic
  • Generate files such as configurations from variables

Networking Template Example

Manage configuration on a network platform

---
- name: configure OSPF router-id
  hosts: network
  tasks:
   - name: configure ospf
     nxos_config:
      src: template.j2
        

Loops

Loops can do one task on multiple things, such as create a lot of users, install a lot of packages, or repeat a polling step until a certain result is reached.


---
- hosts: cisco
connection: local
tasks:
  - nxos_snmp_user:
      user: "{{item.user}}"
      group: network-admin
      authentication: sha
      pwd: "{{item.password}}"
    with_items:
      - { user: 'exampleuser', password: 'testPASS123' }
      - { user: 'gerald', password: 'testPASS456' }
      - { user: 'sean', password: 'testPASS789' }
      - { user: 'andrius', password: 'vTECH1234' }
          

Blocks

Blocks cut down on repetitive task directives, allow for logical grouping of tasks and even in play error handling.


- name: Configure Hostname and DNS
  block:
  - ios_config:
      lines: hostname {{ inventory_hostname }}

  - name: configure name servers
    ios_system:
      name_servers:
        - 8.8.8.8
        - 8.8.4.4
  when: ansible_network_os == "ios"
          

Demo Time:
Lab 03 - IP Fabric Templating

Workshop:
Lab 03 - IP Fabric Templating

Roles

Roles are a packages of closely related Ansible content that can be shared more easily than plays alone.

  • Improves readability and maintainability of complex plays
  • Eases sharing, reuse and standardization of automation processes
  • Enables Ansible content to exist independently of playbooks, projects -- even organizations
  • Provides functional conveniences such as file path resolution and default values

Project with Embedded Roles Example


site.yml
roles/
   common/
     files/
     templates/
     tasks/
     handlers/
     vars/
     defaults/
     meta/
   ospf/
     files/
     templates/
     tasks/
     handlers/
     vars/
     defaults/
     meta/
          

Project with Embedded Roles Example


# site.yml
---
- hosts: routers
  roles:
     - common
     - ospf
          

Ansible Galaxy

http://galaxy.ansible.com

Ansible Galaxy is a hub for finding, reusing and sharing Ansible content.

Jump-start your automation project with content contributed and reviewed by the Ansible community.

Next Steps

  • It's easy to get started
    ansible.com/get-started
  • Join the Ansible community
    ansible.com/community
  • Would you like to learn a lot more?
    redhat.com/en/services/training/do407-automation-ansible