loading...
Cover image for The Ultimate Guide for Ansible Total Domination

The Ultimate Guide for Ansible Total Domination

courseprobe profile image Course Probe ・9 min read

Ansible is a radically simple IT automation engine that automates cloud provisioning, configuration management, application deployment, intra-service orchestration, and many other IT needs.

Designed for multi-tier deployments since day one, Ansible models your IT infrastructure by describing how all of your systems inter-relate, rather than just managing one system at a time.

It uses no agents and no additional custom security infrastructure, so it’s easy to deploy — and most importantly, it uses a very simple language (YAML, in the form of Ansible Playbooks) that allow you to describe your automation jobs in a way that approaches plain English.

Installing Ansible on Ubuntu

Ubuntu builds are available in a PPA here.

To configure the PPA on your machine and install Ansible run these commands:

    $ sudo apt update
    $ sudo apt install software-properties-common
    $ sudo apt-add-repository --yes --update ppa:ansible/ansible
    $ sudo apt install ansible

Installing Ansible on macOS

The preferred way to install Ansible on a Mac is with pip.

The instructions can be found in Installing Ansible with pip. If you are running macOS version 10.12 or older, then you should upgrade to the latest pip to connect to the Python Package Index securely. It should be noted that pip must be run as a module on macOS, and the linked pip instructions will show you how to do that.

Installing Ansible with pip

Ansible can be installed with pip, the Python package manager. If pip isn’t already available on your system of Python, run the following commands to install it:

    $ curl [https://bootstrap.pypa.io/get-pip.py](https://bootstrap.pypa.io/get-pip.py) -o get-pip.py
    $ python get-pip.py --user

Here are ideas on how you might use Ansible and why you might recommend it to friends and colleagues.

Bootstrap hardware

As a computer geek, I tend to unintentionally collect computers. Sometimes they’re computers I rescue from the rubbish bin, other times they’re computers people give me as payment for helping them transfer their data to their newer computer, and still other times, it’s a small fleet of machines I manage for charity organizations lacking finances for a “real IT guy.” I can attest that anything from two to 200 computers is too many to set up and configure manually.

Ansible doesn’t just automate day-to-day tasks; it can also bootstrap hardware. You can find out how to set this up in two articles:

Automate the cloud

If bootstrapping bare-metal boxes seems arcane to you in the mythical “serverless” age, you might be more interested in managing containers with Ansible. Thanks to the Kubernetes (lovingly abbreviated as K8s) module, you can talk to your Kubernetes cluster through Ansible playbooks. Read more about it in my Ansible and K8s article.+

Of course, Ansible doesn’t talk only to K8s. There are many other cloud-related modules available, including ones for OpenShift, Atomic, Azure, Docker, Podman, and many other components of your open hybrid cloud (or, if you’re not that lucky, your proprietary one).

Build containers

What’s the cloud without containers? Once you’ve got your cloud tasks automated, you’ll be happy to know that Ansible also can help generate the containers you need when delivering your applications or spinning up services. Tomas Tomecek guides you through the process in his Building container images with the Ansible-bender tool article.

Discover modules

The truth of the matter is that there wouldn’t be much to Ansible if it weren’t for its excellent collection of modules. Like third-party libraries for Python or applications for your mobile phone, the technical driver of all the useful and surprisingly easy tricks Ansible is famous for are the parts that other people have already figured out for you.

A complete index of supported modules is available on the Ansible website, but there are a lot of them. If you’re finding it difficult to know where to begin, read Shashank Hegde’s 10 must-know Ansible modules for a thorough overview of the most essential.

Ansible for Windows

If you’re an admin for Linux and Unix systems, Ansible is an easy and pretty natural fit. But when faced with Windows systems, you might be a little intimidated. At this point, Windows doesn’t even ship with Python, much less OpenSSH, so there are obviously some adjustments you’ll have to make.

Don’t panic. Taz Brown and Abner Malivert step you through the setup process and some basic exercises to get you comfortable in Ansible for Windows admins.

Recommended Resources:

DevOps : Ultimate Beginners Guide

SysAdmin Interview Questions

Automating Network Devices with Ansible

Ansible is a great automation tool for system and network engineers, with Ansible we can automate small network to a large scale enterprise network. I have been using Ansible to automate both Aruba, and Cisco switches from my Fedora powered laptops for a couple of years. This article covers the requirements and executing a couple of playbooks.

Configuring Ansible

If Ansible is not installed, it can be installed using the command below

    $ sudo dnf -y install ansible

Once installed, create a folder in your home directory or a directory of your preference and copy the ansible configuration file. For this demonstration, I will be using the following.

    $ mkdir -pv /home/$USER/network_automation
    $ sudo cp -v /etc/ansible.cfg /home/$USER/network_automation
    $ cd /home/$USER/network_automation
    $ sudo chown $USER:$USER ansible.cfg && chmod 0600 ansible.cfg

To prevent lengthy commands from failing, edit the ansible.cfg and append the following lines. We must add the persistent connection and set the desired time in seconds for the command_timeout as demonstrated below. A use case where this is useful is when you are performing backups of a network device that has a lengthy configuration.

    $ vim ansible.cfg
    [persistent_connection]
    command_timeout = 300
    connection_timeout = 30

Requirements

If SELinux is enabled, you will need to install SELinux binding, which is required when using the copy module.

    # Install SELinux bindings
    $ sudo dnf -y install python3-libselinux python3-libsemanage

Creating the inventory

The inventory holds the names of the network assets, and grouping of the assets are in square brackets [], below is a sample inventory.

    [site_a]
    Core_A ansible_host=192.168.122.200
    Distro_A ansible_host=192.168.122.201
    Distro_B ansible_host=192.168.122.202

Group vars can be used to address the common variables, for example, credentials, network operating system, and so on. Ansible document on inventory provides additional details.

Playbook

Playbooks are Ansible’s configuration, deployment, and orchestration language. They can describe a policy you want your remote systems to enforce, or a set of steps in a general IT process. Ansible Playbook

Read Operations

Let us create a simple playbook to run a show command to read the configuration on a few switches.

    1 ---
      2 - name: Basic Playbook
      3   hosts: site_a
      4   connection: local
      5 
      6   tasks:
      7   - name: Get Interface Brief
      8     ios_command:
      9       commands:
     10         - show ip interface brief | e una
     11     register: interfaces
     12 
     13   - name: Print results
     14     debug:
     15       msg: "{{ interfaces.stdout[0] }}

The above images show the differences without and with the debug module respectively.

Let’s break the playbook into three blocks, starting with lines 1 to 4.

  • The three dashes/hyphens starts the YAML document

  • The hosts defines the hosts or host groups, multiple groups are comma-separated

  • Connection defines the methodology to connect to the network devices. Another option is network_cli (recommended method) and will be used later in this article. See IOS Platform Options for more details.

Lines 6 to 11 starts the tasks, we will be using ios_command and ios_config. This play will execute the show command show ip interface brief | e una and save the output from the command into the interfaces variable, with the register key.

Lines 13 to 15, by default, when you execute a show command you will not see the output, though this is not used during automation. It is very useful for debugging; therefore, the debug module was used.

The below video shows the execution of the playbook. There are a couple of ways you can execute the playbook.

  • Passing arguments to the command line, for example, include -u -k to prompt for the remote user credentials
    ansible-playbook -i inventory show_demo.yaml -u admin -k
  • Include the credentials in the host or group vars

    ansible-playbook -i inventory show_demo.yaml

    Never store passwords in plain text. We recommend using SSH keys to authenticate SSH connections. Ansible supports ssh-agent to manage your SSH keys. If you must use passwords to authenticate SSH connections, we recommend encrypting them with Using Vault in Playbooks

Passing arguments to the command line

Credentials in the inventory

If we want to save the output to a file, we will use the copy module as shown in the playbook below. In addition to using the copy module, we will include the backup_dir variable to specify the directory path.

    ---
    - name: Get System Infomation
      hosts: site_a
      connection: network_cli
      gather_facts: no

      vars:
        backup_dir: /home/eramirez/dev/ansible/fedora_magazine

      tasks:
      - name: get system interfaces
        ios_command:
          commands:
            - show ip int br | e una
        register: interface

      - name: Save result to disk
        copy:
          content: "{{ interface.stdout[0] }}"
          dest: "{{ backup_dir }}/{{ inventory_hostname }}.txt"

To demonstrate the use of variables in the inventory, we will use plain text. This method Must not be used in production.

    [site_a]
    Core_A ansible_host=192.168.122.200
    Distro_A ansible_host=192.168.122.201
    Distro_B ansible_host=192.168.122.202
    [all:vars]
    ansible_connection=network_cli
    ansible_network_os=ios
    ansible_user=admin
    ansible_password=fedora
    ansible_become=yes
    ansible_become_password=yes
    ansible_become_method=enable

Write Operations

In the previous section, we saw that we could get information from the network devices; in this section, we will write (add/modify) the configuration on these network devices. To make changes to the network device, we will be using the ios config module.

Let us create a playbook to configure a couple of interfaces in all of the network devices in site_a. We will first take a backup of the current configuration of all devices in site_a. Lastly, we will save the configuration.

    ---
    - name: Get System Infomation
      hosts: site_a
      connection: network_cli
      gather_facts: no

      vars:
        backup_dir: /home/eramirez/dev/ansible/fedora_magazine

      tasks:
      - name: Backup configs
        ios_config:
          backup: yes
          backup_options:
            filename: "{{ inventory_hostname }}_running_cfg.txt"
            dir_path: "{{ backup_dir }}"

      - name: get system interfaces
        ios_config:
          lines:
            - description Raspberry Pi
            - switchport mode access
            - switchport access vlan 100
            - spanning-tree portfast
            - logging event link-status
            - no shutdown
          parents: "{{ item }}"
        with_items:
          - interface FastEthernet1/12
          - interface FastEthernet1/13

      - name: Save switch configuration
        ios_config:
          save_when: modified

Before we execute the playbook, we will first validate the interface configuration. We will then run the playbook and confirm the changes as illustrated below.

Conclusion

Hopefully this guide has given you more insights into Ansible and it’s multiple applications and you can use it on your day to day !!

Source: https://opensource.com/article/20/9/ansible
Automating Network Devices with Ansible - Fedora Magazine
*Ansible is a great automation tool for system and network engineers, with Ansible we can automate small network to a…*fedoramagazine.org


Other Dev posts:

Discussion

pic
Editor guide