We want to hear from you! Help us gain insights into the state of the Ansible ecosystem.
Take the Ansible Project Survey 2024

Command Module Deep Dive for Networks

Command Module Deep Dive for Networks

Enterprise customers often ask the Ansible Network team about the most common use cases for network automation. For this blog post I want to talk about one of the most used (and most versatile) set of network modules: the command modules. The command modules let you run networking commands with Ansible, the same way a network engineer would type them on the command line. With Ansible, though, the output doesn't just fly by the terminal window to be lost forever; it can be stored and used in subsequent tasks. It can also be captured in variables, parsed for use by other tasks, and stored in host variables for future reference. Today we're going to cover basic use of the network command modules, including retaining command output with the register parameter. We'll also cover scaling to multiple network devices with hostvars and adding conditional requirements with the wait_for parameter and three related parameters: interval, retries, and match. The takeaway from this blog post is that any repeatable network operations task can be automated. Ansible is more than configuration management, it allows network operators the freedom to decouple themselves from routine tasks and save themselves time.

There are command modules for a variety of platforms, including all the modules supported under the network offering:

Network Platform *os_command Module
Arista EOS eos_command
Cisco IOS / IOS-XE ios_command
Cisco IOS-XR iosxr_command
Cisco NX-OS nxos_command
Juniper Junos junos_command
VyOS vyos_command

Basic Command Module Usage

Here is a simple playbook using eos_command to run show version:

---
- name: COMMAND MODULE PLAYBOOK
  hosts: eos
  connection: network_cli

  tasks:
   - name: EXECUTE ARISTA EOS COMMAND
     eos_command:
       commands: show version
     register: output

   - name: PRINT OUT THE OUTPUT VARIABLE
     debug:
       var: output

There are two tasks; the first task uses eos_command with a single parameter called commands. Since I am only running one command I can just type show version on the same line as commands. If I had more than one command, I would list each one on a separate line below the commands: parameter. In this example I use the register keyword to save the output of the show version command. You can use the register parameter at the task level with any Ansible task. The register parameter defines a variable to store the output of the task for use in subsequent tasks. In my playbook the variable is called output.

The second task uses the debug module to print out the content of the variable output, from the previous task. In this case I will see the same output I would have seen if I'd typed "show version" at the command line directly on the EOS device. My playbook prints this output in the terminal window where I ran the playbook. The Ansible debug module is great for checking variables.

Below is the output from running the playbook:

PLAY [eos] *************************************************************************

TASK [execute Arista eos command] **************************************************
ok: [eos]

TASK [print out the output variable] ***********************************************
ok: [eos] => {
    "output": {
        "changed": false,
        "failed": false,
        "stdout": [
            "Arista vEOS\nHardware version:    \nSerial number:       \nSystem MAC address:  0800.27ec.005e\n\nSoftware image version: 4.20.1F\nArchitecture:           i386\nInternal build version: 4.20.1F-6820520.4201F\nInternal build ID:      790a11e8-5aaf-4be7-a11a-e61795d05b91\n\nUptime:                 1 day, 3 hours and 23 minutes\nTotal memory:           2017324 kB\nFree memory:            1111848 kB"
        ],
        "stdout_lines": [
            [
                "Arista vEOS",
                "Hardware version:    ",
                "Serial number:       ",
                "System MAC address:  0800.27ec.005e",
                "",
                "Software image version: 4.20.1F",
                "Architecture:           i386",
                "Internal build version: 4.20.1F-6820520.4201F",
                "Internal build ID:      790a11e8-5aaf-4be7-a11a-e61795d05b91",
                "",
                "Uptime:                 1 day, 3 hours and 23 minutes",
                "Total memory:           2017324 kB",
                "Free memory:            1111848 kB"
            ]
        ]
    }
}

PLAY RECAP *************************************************************************
eos                        : ok=2    changed=0    unreachable=0    failed=0

You can see in the output above that both tasks were executed successfully. The first task with the default verbosity has no output, it simply returns the host the task was executed on, eos, with ok and the color green to indicate success. The second task, using the debug module, returns output from the command that was executed. You see the same information in two different formats:

  • stdout
  • stdout_lines

The stdout returns everything a human operator would have seen on the command line in one large string. The stdout_lines returns a list of strings, making the information easier to read. Each item is a separate line that was returned from the command.

Here is the output to see what that looks like:

Arista EOS command line output

eos>show vers
Arista vEOS
Hardware version:
Serial number:
System MAC address: 0800.27ec.005e
Software image version: 4.20.1F
Architecture: i386
Internal build version: 4.20.1F-6820520.4201F
Internal build ID: 790a11e8-5aaf-4be7-a11a-e61795d05b91
Uptime: 1 day, 3 hours and 56 minutes
Total memory: 2017324 kB
Free memory: 1116624 kB

Ansible stdout_lines

"stdout_lines": [
    [
          "Arista vEOS",
          "Hardware version:",
          "Serial number:",
          "System MAC address: 0800.27ec.005e",
          "",
          "Software image version: 4.20.1F",
          "Architecture: i386",
          "",
          "Internal build version: 4.20.1F-6820520.4201F",
          "Internal build ID: 790a11e8-5aaf-4be7-a11a-e61795d05b91",
          "",
          "Uptime: 1 day, 3 hours and 23 minutes",
          "Total memory: 2017324 kB",
          "Free memory: 1111848 kB"
        ]

Engineers and folks familiar with JSON and YAML have already noticed another interesting detail: stdout_lines begins with two opening brackets

"stdout_lines": [
            [

The two opening brackets show that stdout_lines actually returned a list of lists of strings. If we modify our debug task slightly we use this feature to view selections from the output. Since the output only has one list within the list, that entire sub-list is referenced as list zero, or the first list. Let's look at a single line from the return value. I want to grab the System MAC Address for our test. Looking above at the output, the System MAC address is returned in the fourth line, which corresponds to line 3 (since computers start counting from 0). This means we want to grab line 3 of list 0, which corresponds to output.stdout_lines[0][3].

- name: print out a single line of the output variable
  debug:
  var: output.stdout_lines[0][3]

The debug task returns exactly what we need:

TASK [print out a single line of the output variable] ******************************
ok: [eos] => {
    "output.stdout_lines[0][3]": "System MAC address:  0800.27ec.005e"
}

Why would we want that first list to be zero and what is the use case for having multiple lists? It is possible to run multiple commands with one command task.Here is a playbook with three commands:

---
- hosts: eos
  connection: network_cli
  tasks:
    - name: execute Arista eos command
      eos_command:
        commands:
          - show version
          - show ip int br
          - show int status
      register: output

    - name: print out command
      debug:
        var: output.stdout_lines

The output from output now looks like this:

"output.stdout_lines": [
    [
        "Arista vEOS",
        "Hardware version:    ",
        "Serial number:       ",
        "System MAC address:  0800.27ec.005e",
        "",
        "Software image version: 4.20.1F",
        "Architecture:           i386",
        "Internal build version: 4.20.1F-6820520.4201F",
        "Internal build ID:      790a11e8-5aaf-4be7-a11a-e61795d05b91",
        "",
        "Uptime:                 1 day, 4 hours and 20 minutes",
        "Total memory:           2017324 kB",
        "Free memory:            1111104 kB"
    ],
    [
        "Interface              IP Address        Status    Protocol      MTU",
        "Ethernet1              172.16.1.1/24      up         up          1500",
        "Management1            192.168.2.10/24    up         up          1500"
    ],
    [
        "Port  Name    Status       Vlan    Duplex  Speed  Type     Flags",
        "Et1           connected  routed    full    unconf EbraTestPhyPort   ",
        "Et2           connected    1       full    unconf EbraTestPhyPort   ",
        "Et3           connected    1       full    unconf EbraTestPhyPort   ",
        "Ma1           connected  routed   a-full a-1G   10/100/1000"
    ]
]

List zero corresponds to the show version command, list one corresponds to the show ip int br command and list two corresponds to the show int status command. The list number directly corresponds to the order the command was run in.

Arista EOS Command Relevant List
show version output.stdout_lines[0]
show ip int br output.stdout_lines[1]
show int status output.stdout_lines[2]

Scaling Command Module Use: Host Variables

So what happens if we run on two or more network devices at the same time?

diagram of Ansible running multiple network devices

The variable output is saved uniquely as a host variable per inventory host.  If I had three switches and ran this playbook against them, I would have an output variable for each unique host.  For a demonstration we will grab the IP address from the show ip int br command above for the Ethernet1 port for just one of the switches, switch03.  The show ip int br corresponds to the second command we run, and the ethernet1 interface shows up in the 2nd line so we know we want stdout_lines[1][1].  To reference vars about a specific host we use the keyword hostvars and do a dictionary lookup on the host we want.

This is what the debug task will look like:

- name: debug hostvar
  debug:
    var: hostvars["switch03"].output.stdout_lines[1][1]

And the output matches what we would expect:

TASK [debug hostvar] ***************************************************************
ok: [switch03] => {
    "hostvars["switch03"].output.stdout_lines[1][1]": "Ethernet1              172.16.1.3/24      up         up              1500"
}

By default a task will use variables specific to that host, but when using hostvars you can directly reference other host variables.

Conditions in Command Module Tasks: wait_for

The wait_for parameter applies conditional logic directly after a command is run. This means within the same task you can decide to purposely fail if output does not match a desired state. By default, with the above tasks, when there is no wait_for parameter specified the task is only run one time. However, if the wait_for parameter is specified the task is run until the condition is met or the maximum retries (the default is 10 retries) is hit. If I turn on command logging I can easily see this with a playbook specifically meant to fail for demonstration purposes:

---
- hosts: eos
  connection: network_cli
  tasks:
    - name: execute Arista eos command
      eos_command:
        commands:
          - show int status
        wait_for:
          - result[0] contains DURHAM

This playbook will run show int status 10 times, because it will never find the word DURHAM in the output of show int status.

A show logging command shows me the command was indeed run 10 times:

Mar 24 20:33:52 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=17 start_time=1521923632.5 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status
Mar 24 20:33:53 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=18 start_time=1521923633.71 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status
Mar 24 20:33:54 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=19 start_time=1521923634.81 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status
Mar 24 20:33:55 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=20 start_time=1521923635.92 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status
Mar 24 20:33:56 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=21 start_time=1521923636.99 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status
Mar 24 20:33:58 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=22 start_time=1521923638.07 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status
Mar 24 20:33:59 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=23 start_time=1521923639.22 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status
Mar 24 20:34:00 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=24 start_time=1521923640.32 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status
Mar 24 20:34:01 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=25 start_time=1521923641.4 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status
Mar 24 20:34:02 eos Aaa: %ACCOUNTING-6-CMD: admin vty6 192.168.2.1 stop task_id=26 start_time=1521923642.47 timezone=UTC service=shell priv-lvl=15 cmd=show interfaces status

Here we can look at a real world example. For this playbook everything is configured to bring up an OSPF adjacency with another device, except the ip ospf area command. We will apply the command and then use the wait_for parameter to make sure the adjacency comes up (indicated by FULL). If full is not found within 10 retries the task will fail.

---
- hosts: eos
  connection: network_cli
  tasks:
    - name: turn on OSPF for interface Ethernet1
      eos_config:
        lines:
          - ip ospf area 0.0.0.0
        parents: interface Ethernet1

    - name: execute Arista eos command
      eos_command:
        commands:
          - show ip ospf neigh
        wait_for:
          - result[0] contains FULL

Execute the playbook with the ansible-playbook command:

  ansible-playbook ospf.yml

PLAY [eos] *********************************************************************************************

TASK [turn on OSPF for interface Ethernet1] *******************************************************
changed: [eos]

TASK [execute Arista eos command] ****************************************************************
ok: [eos]

PLAY RECAP ******************************************************************************************
eos                    : ok=2    changed=1    unreachable=0    failed=0

Checking on the command line confirms the playbook ran successfully:

eos#show ip ospf neigh
Neighbor ID     VRF      Pri State             Dead Time   Address         Interface
2.2.2.2         default  1   FULL/DR           00:00:33    172.16.1.2      Ethernet1

In addition to contains we can use:

  • eq: Equal
  • neq: Not equal
  • gt: Greater than
  • ge: Greater than or equal
  • lt: Less than
  • le : Less than or equal

There are also three parameters that can be used in conjunction with wait_for. All of these are documented on the individual module pages:

Parameter Description
interval Time between each command retry
retries The number of times we retry the task until we fail (or the condition is met)
match Match all of your conditionals or just any of them

Let's quickly elaborate on the match parameter:

- name: execute Arista eos command
  eos_command:
    commands:
      - show ip ospf neigh
    match: any
    wait_for:
      - result[0] contains FULL
      - result[0] contains 172.16.1.2

With match: any set, the task will succeed if the result contains either FULL or 172.16.1.2. With match: all (which is the default), both must be true before the task can successfully pass. It is far more likely if you have multiple conditionals that you want them all met versus just one of them to be true.

Looking for a use-case where you might want to use match: any? Imagine that you want to confirm internet access to and from a datacenter. For this particular data center you have five ISPs (Internet Service Providers), and five discrete BGP connections between your data center and those ISPs. An Ansible Playbook could check all five BGP connections and continue on if any of them are up and working, rather than all five. Just remember that any implies OR versus all which implies and.

Parameter Description
match: any Implicit OR, any conditional can be met
match: all Implicit AND, all conditionals must be met

Negative Conditions: Handling Inverse Logic

Sometimes you are looking for absences or other negative conditions in command output. It's tempting to use the neq comparison for any negative scenario, but it's not always the right choice. If you want the inverse logic of contains (output from this command should not contain this) consider using the register keyword to store the output followed by a when statement on a subsequent task. If you want to stop the playbook if conditions are not met, consider simply using the fail module or assert module where you can fail on purpose. The neq shown above only makes sense if you can grab an exact value (if you can get key-value pairs or JSON) versus getting a string or list of strings. Otherwise you are going to be doing exact string compares.

Going Further

Read the documentation on Working with Command Output in Network Modules here.  

The more specific conditionals like ge, le, etc. can work really well on JSON output from certain networking platforms as shown in the example in the documentation.




Connect Ansible Tower and Jenkins in under 5 minutes

Connect Ansible Tower and Jenkins in under 5 minutes

We often hear from customers that they are using Jenkins in some capacity or another. And since I'm a consultant, I'm lucky to hear first hand what our customers are using and how they need to integrate Ansible Tower. There has always been a way to integrate the Ansible Tower and Jenkins using tower-cli, but I thought there could be a neater, closer to native, way of doing it.

So here we go. I've recorded this short screencast to show you just how easy it is:

The screencast is not currently available. You can find helpful material in the links below or on the Ansible community forum: https://forum.ansible.com/tag/awx

Below you will find a few links from the video and a link to how to try Ansible Tower.

plugins.jenkins.io/ansible-tower

wiki.jenkins.io/display/JENKINS/Ansible+Tower+Plugin




Windows Package Management

Windows Package Management

Welcome to the third installment of our Windows-centric Getting Started Series!

In the previous post we covered how you can use Ansible and Ansible Tower to help manage your Active Directory environment. This post will go into how you can configure some of those machines on your domain. Most of this post is going to be dominated by specific modules. Ansible has a plethora of Windows modules that can be found here. As time is not a flat circle, I can't discuss all of them today but only a few that are widely used.

MSIs and the win_package Module

So you got your domain up, you have machines added to it, now let's install some stuff on those machines. I do have a few notes before moving forward in regards to the modules we'll be discussing. The module win_msi is deprecated and will be removed in Ansible 2.8 (current version as of this post is 2.5). In its place you can use win_package which I will be using throughout this post.

Alright, back to installing stuff. The win_package module is the place to be. It is used specifically for .msi and .exe files that need to be installed or uninstalled. These files can also be sourced locally, from a URL or from a network resource.

The parameters within the module add a lot of flexibility. As of Ansible 2.5, you can now list your arguments and the module will escape the arguments as necessary. However, it is recommended to use a string when dealing with MSI packages due to the unique escaping issues with MsiExec.

Below are a few examples of how you can use the win_package module. The first one shows how to install Visual C++ and list arguments:

- name: Install Visual C thingy with list of arguments instead of a string
  win_package:
    path:
http://download.microsoft.com/download/1/6/B/16B06F60-3B20-4FF2-B699-5E9B7962F9AE/VSU_4/vcredist_x64.exe
    product_id: '{CF2BEA3C-26EA-32F8-AA9B-331F7E34BA97}'
    arguments:
    - /install
    - /passive
    - /norestart

Above, we see that the product ID is listed. While Ansible can and does extract the ID from the MSI when it's local, we don't want to force the host to download the MSI if it's not necessary. When you supply the product ID, Ansible can quickly check to see if the package is already installed without downloading a potentially huge MSI from the internet first. You can install without the product ID. An example of this can be found below: 

- name: Install Remote Desktop Connection Manager locally omitting the product_id
  win_package:
    path: C:\temp\rdcman.msi
    state: present

As I stated earlier, you can also download from a network share and specify the credentials needed to access that share. The example below shows it in action, installing 7-zip from a network resource: 

- name: Install 7zip from a network share specifying the credentials
  win_package:
    path: \\domain\programs\7z.exe
    product_id: 7-Zip
    arguments: /S
    state: present
    user_name: DOMAIN\User
    user_password: Password

Windows Package Management and Chocolatey

Unlike most Linux distros, Windows does not have a built-in package manager. Windows does have the Windows App Store but I don't think that a whole lot of those products are making their way into data centers.

There is, however, a community project called Chocolatey that provides a full package management experience for Windows users. It helps take away some of the pain that comes with managing raw setup.exe and .msi files. And wouldn't you know, we have a module for it!

But before we get into talking about the module, let's talk a little bit more about Chocolatey. A good comparison for people who might be Mac users, Chocolatey is similar to that of Homebrew. Chocolatey is designed to easily work with all aspects of managing Windows software (installers, zip archives, runtime binaries, internal and 3rd party software) using a packaging framework that understands both versioning and dependency requirements.

The Chocolatey module is similar in use as its *nix counterparts, simple and powerful. It does have a soft requirement in regards to the version. And what I mean by soft requirement is that it needs v. 0.10.5 to run but if Chocolatey doesn't see that version, it will update it for you. And to add some more sugar to that dessert, if Chocolatey is not present on the machine, the module will install it for you as well before going through with its assigned tasks.

To get started with the module, one of the easiest examples could be installing a lightweight CLI tool. Let's use git because people's workflows are all the same, right?

- name: Install git
  win_chocolatey:
    name: git
    state: present

All joking aside, it is that easy to install git. It is just as easy to install a different version of something as well if you need to have a specific version of something. Let's say you need Notepad++, version 6.6. It would look something like this: 

- name: Install notepadplusplus version 6.6
  win_chocolatey:
    name: notepadplusplus
    version: '6.6'

One key thing to note when you're stating a version: make sure to enter it as a string (see the two tick marks around 6.6). Reason being is that if it is not entered as a string, it's considered a YAML float. Many valid version numbers don't translate properly into a float and yield the same result (eg, '6.10' != '6.1' for most versioning schemes, but 6.10 as a float will become 6.1), so it's a good habit to always quote version numbers to ensure that they're not re-formatted.

Some packages might require an interactive user logon to make an installation. To pass the correct credentials, you can use become to achieve this. The example below shows an installation of a package that requires the use of become. Note that you can become: System and it will not require you to supply a password.

- name: Install a package that requires 'become'
  win_chocolatey:
    name: officepro2013
  become: yes
  become_user: Administrator
  become_method: runas

The win_chocolatey module is strong and powerful but in some scenarios will not work without become. There is no easy way to find out if a package requires become so the best course is to try it without and use become if that fails. 

Packages and Chocolate Bars in Windows Automation

To wrap up this blog post, we covered a couple of ways you can automate the installation of packages for your Windows environment. Whether you are all in on using Chocolatey or need to install some packages, Ansible has the power to do all of that and more for you, in a simple and easy-to-read format.

In our next and final post of the Getting Started with Windows Automation series, we will talk about Security and Updates in Windows using Ansible!




Connecting to a Windows Host

Connecting to a Windows Host

Welcome to the first installment of our Windows-specific Getting Started series!

Would you like to automate some of your Windows hosts with Red Hat Ansible Tower, but don't know how to set everything up? Are you worried that Red Hat Ansible Engine won't be able to communicate with your Windows servers without installing a bunch of extra software? Do you want to easily automate everyone's best friend, Clippy?

Ansible-Windows-Clippy

We can't help with the last thing, but if you said yes to the other two questions, you've come to the right place. In this post, we'll walk you through all the steps you need to take in order to set up and connect to your Windows hosts with Ansible Engine.

Why Automate Windows Hosts?

A few of the many things you can do for your Windows hosts with Ansible Engine include:

  • Starting, stopping and managing services
  • Pushing and executing custom PowerShell scripts
  • Managing packages with the Chocolatey package manager

In addition to connecting to and automating Windows hosts using local or domain users, you'll also be able to use runas to execute actions as the Administrator (the Windows alternative to Linux's sudo or su), so no privilege escalation ability is lost.

What's Required?

Before we start, let's go over the basic requirements. First, your control machine (where Ansible Engine will be executing your chosen Windows modules from) needs to run Linux. Second, Windows support has been evolving rapidly, so make sure to use the newest possible version of Ansible Engine to get the latest features!

For the target hosts, you should be running at least Windows 7 SP1 or later or Windows Server 2008 SP1 or later. You don't want to be running something from the 90's like Windows NT, because this might happen:

Ansible-Windows-90s

Lastly, since Ansible connects to Windows machines and runs PowerShell scripts by using Windows Remote Management (WinRM) (as an alternative to SSH for Linux/Unix machines), a WinRM listener should be created and activated. The good news is, connecting to your Windows hosts can be done very easily and quickly using a script, which we'll discuss in the section below.

Step 1: Setting up WinRM

What's WinRM? It's a feature of Windows Vista and higher that lets administrators run management scripts remotely; it handles those connections by implementing the WS-Management Protocol, based on Simple Object Access Protocol (commonly referred to as SOAP). With WinRM, you can do cool stuff like access, edit and update data from local and remote computers as a network administrator.

The reason WinRM is perfect for using with Ansible Engine is because you can obtain hardware data from WS-Management protocol implementations running on non-Windows operating systems (in this specific case, Linux). It's basically like a translator that allows different types of operating systems to work together.

So, how do we connect?

With most versions of Windows, WinRM ships in the box but isn't turned on by default. There's a Configure Remoting for Ansible script you can run on the remote Windows machine (in a PowerShell console as an Admin) to turn on WinRM. To set up an https listener, build a self-signed cert and execute PowerShell commands, just run the script like in the example below (if you've got the .ps1 file stored locally on your machine):

Ansible-Windows-Powershell

Note: The win_psexec module will help you enable WinRM on multiple machines if you have lots of Windows hosts to set up in your environment.

For more information on WinRM and Ansible, check out the Windows Remote Management documentation page.

Step 2: Install Pywinrm

Since pywinrm dependencies aren't shipped with Ansible Engine (and these are necessary for using WinRM), make sure you install the pywinrm-related library on the machine that Ansible is installed on. The simplest method is to run pip install pywinrm in your Terminal.

Step 3: Set Up Your Inventory File Correctly

In order to connect to your Windows hosts properly, you need to make sure that you put in ansible_connection=winrm in the host vars section of your inventory file so that Ansible Engine doesn't just keep trying to connect to your Windows host via SSH.

Also, the WinRM connection plugin defaults to communicating via https, but it supports different modes like message-encrypted http. Since the "Configure Remoting for Ansible" script we ran earlier set things up with the self-signed cert, we need to tell Python, "Don't try to validate this certificate because it's not going to be from a valid CA." So in order to prevent an error, one more thing you need to put into the host vars section is: ansible_winrm_server_cert_validation=ignore

Just so you can see it in one place, here is an example host file (please note, some details for your particular environment will be different):

[win]
172.16.2.5
172.16.2.6

[win:vars]
ansible_user=vagrant
ansible_password=password
ansible_connection=winrm
ansible_winrm_server_cert_validation=ignore

Step 4: Test Connection

Let's check to see if everything is working. To do this, go to your control node's terminal and type ansible [host_group_name_in_inventory_file] -i hosts -m win_ping. Your output should look like this:

Ansible-Windows-Screen-Grab

Note: The win_ prefix on all of the Windows modules indicates that they are implemented in PowerShell and not Python.

Troubleshooting WinRM

Because WinRM can be configured in so many different ways, errors that seem Ansible Engine-related can actually be due to problems with host setup instead. Some examples of WinRM errors that you might see include an HTTP 401 or HTTP 500 error, timeout issues or a connection refusal. To get tips on how to solve these problems, visit the Common WinRM Issues section of our Windows Setup documentation page.

Conclusion

You should now be ready to automate your Windows hosts using Ansible, without the need to install a ton of additional software! Keep in mind, however, that even if you've followed the instructions above, some Windows modules have additional specifications (e.g., a newer OS or more recent PowerShell version). The best way to figure out if you're meeting the right requirements is to check the module-specific documentation pages.

For more in-depth information on how to use Ansible Engine to automate your Windows hosts, check out our Windows FAQ and Windows Support documentation page and stay tuned for more Windows-related blog posts!




Using Ansible to Mitigate Network Vulnerabilities

Using Ansible to Mitigate Network Vulnerabilities

Even Networks Aren't Immune

Just like with Windows and Linux servers, networking devices can be exploited by vulnerabilities found in their operating systems. Many IT organizations do not have a comprehensive strategy for mitigating security vulnerabilities that span multiple teams (networking, servers, storage, etc.). Since the majority of network operations is still manual, the need to mitigate quickly and reliably across multiple platforms consisting of hundreds of network devices becomes extremely important.

In Cisco's March 2018 Semiannual Cisco IOS and IOS XE Software Security Advisory Bundled Publication, 22 vulnerabilities were detailed. While Red Hat does not report or keep track of individual networking vendors CVEs, Red Hat Ansible Engine can be used to quickly automate mitigation of CVEs based on instructions from networking vendors.

In this blog post we are going to walk through CVE-2018-0171 which is titled "Cisco IOS and IOS XE Software Smart Install Remote Code Execution Vulnerability." This CVE is labeled as critical by Cisco, with the following headline summary:

"...a vulnerability in the Smart Install feature of Cisco IOS Software and Cisco IOS XE Software could allow an unauthenticated, remote attacker to trigger a reload of an affected device, resulting in a denial of service (DoS) condition, or to execute arbitrary code on an affected device."

Gathering Information from Networks

Users leverage Ansible modules to access devices, retrieve information, execute commands and handle systems using specific keywords. One of the first things a CVE requires is collection of inventory. To mitigate a CVE, the networking platform and specific version of code is required. CVE-2018-0171 affects the IOS and IOS-XE network operating systems and Ansible can obtain this information easily. Let's use the ios_facts module which returns key-value pairs for use in subsequent tasks. For example: ansible_net_model returns the model, and ansible_net_image returns the image file the device is running. For a full list see the ios_facts module documentation page.

- name: gather facts for ios platforms
  ios_facts:
    gather_subset: all

- name: output facts to terminal window
  debug:
    msg: >
      Device {{ansible_net_hostname}}, model
{{ansible_net_model}}, running {{ansible_net_version}}

When executing the playbook we get nice output like this:

ok: [rtr1] => {
    "msg": "Device rtr1, model CSR1000V, running 16.05.02\n"
}
ok: [rtr2] => {
    "msg": "Device rtr2, model CSR1000V, running 16.05.02\n"
}
ok: [switch] => {
    "msg": "Device c3850-1, model WS-C3850-24T, running 16.06.01\n"
}

This allows us to quickly grab useful information about our network, and check it against Cisco Security Advisory. In a demo on the GitHub network-automation project we show how to use network facts to quickly build a nice HTML report.

The vulnerability CVE-2018-0171 specifies that to see if a device is vulnerable we must run the show vstack config command. In my network, I have three devices running IOS-XE, two are CSR1000V devices, and one device is a 3850. The two CSR devices don't have the command, while the 3850 switch does. To make my playbook robust enough to handle errors when a command doesn't exist, I can use the ignore_errors parameter. Otherwise, the playbook would fail and exit when a target network node doesn't have the ability to use that command. Alternatively, I could run the playbook only on switches by using a limit. For this example, let's assume we are running the Cisco 3850 which has the show vstack config command.

- name: run show vstack config
    ios_command:
      commands:
        - show vstack config
    register: showvstack

In the playbook above I used the register: showvstack. The showvstack is a user defined term (I chose it, it is not reserved). By registering this I can use the output from the show vstack config later in the playbook. We can use the debug module to look at the showvstack variable to see how it's formatted:

ok: [switch] => {
    "showvstack": {
        "changed": false,
        "failed": false,
        "stdout": [
            "Capability: Director | Client\n Oper Mode: Disabled\n Role: NA\n Vstack Director IP address: 0.0.0.0\n\n *** Following configurations will be effective only on director ***\n Vstack default management vlan: 1\n Vstack start-up management vlan: 1\n Vstack management Vlans: none\n Join Window Details:\n\t Window: Open (default)\n\t Operation Mode: auto (default)\n Vstack Backup Details:\n\t Mode: On (default)\n\t Repository:"
        ],

<<rest of output removed for brevity>>

There is a stdout and a stdout_lines. To read more on the common return values refer to the documentation. Next, we will use my new favorite module, the assert module. This enables us to check if given expressions are true, failing the task if they are not. Cisco provides two outputs that we need to check for in the result of the show vstack config command:

switch1# show vstack config
Role: Client (SmartInstall enabled)

or

switch2# show vstack config
Capability: Client
Oper Mode: Enabled
Role: Client

We can use the assert module to check the text we saved in the showvstack variable:

- name: Check to make sure Cisco's Smart Install Client Feature is not enabled (1/2)
  assert:
    that:
      - "'SmartInstall enabled' not in showvstack.stdout"
      - "'Role' not in showvstack.stdout"
      - "'Client' not in showvstack.stdout"

Each line in the assert module that is added means there is an implicit AND, meaning all three need to be true for the task to pass.

Similarly we can check the second statement:

- name: Check to make sure Cisco's Smart Install Client Feature is not enabled (1/1)
  assert:
    that:
      - "'Oper Mode' not in showvstack.stdout"
      - "'Enabled' not in showvstack.stdout"
      - "'Role' not in showvstack.stdout"
      - "'Client' not in showvstack.stdout"

For this particular CVE it lists that there are no workarounds available. On some CVEs we could use the ios_command or ios_config modules to mitigate the CVE based on the instructions the vendor provided. For this particular CVE it links to the documentation on how to disable vstack using the command no vstack which could be sent using the ios_command module. It also recommends for older releases to block traffic on TCP port 4786, which could be pushed using the ios_config module. Since no workaround is provided on the CVE, a network operator needs to make an educated decision based on their environment. Alternatively, for CVE-2018-0150 there is a workaround provided, and the ios_config could simply send no username cisco to mitigate the CVE.

Red Hat Ansible Engine and Red Hat Ansible Tower can be used to help network operators and administrators scale repetitive tasks like checking these dozens of CVEs and make sure their network is safe from vulnerabilities. On the server side, when system administrators are using Red Hat Insights, they can automatically generate playbooks for Red Hat Enterprise Linux to help with vulnerabilities and proactively identify threats to security, performance, and stability. Ansible can be the common way to execute tasks across your entire IT infrastructure.