Working with module ios_command in ansible

Hello everybody) In this post I will show you how to work with ansible module ios_command.

What is ios_command module do? It sends a show command to an IOS device and returns the result of the command.

The ios_command module does not support sending commands in configuration mode. For this, a separate module is used – ios_config.

Before sending the command itself, the module:

  • performs SSH authentication
  • switches to enable mode
  • executes the terminal length 0 command so that the output of show commands is displayed in full rather than page by page.

An example of using the ios_command module (playbook 1_ios_command.yml):

---
- name: Run show commands on routers
  hosts: all
  gather_facts: false
  
  tasks:
    - name: run sh ip int br
      ios_command:
        commands: show ip int br
      register: sh_ip_int_br_result

    - name: Debug registered var
      debug: var=sh_ip_int_br_result.stdout_lines

and file group_vars/all.yml with connection variables:

ansible_connection: network_cli
ansible_network_os: ios
ansible_user: cisco
ansible_password: cisco
ansible_become: yes
ansible_become_method: enable
ansible_become_pass: cisco1

The ios_command module expects a parameter commands.

Commands – list of commands to be sent to the device.

Playbook execution result:

$ ansible-playbook ios_command.yml

Running multiple commands module ios_command

The ios_command module allows you to execute multiple commands.

Playbook ios_command.yml executes several commands and gets their output:

---
- name: Run show commands on routers
  hosts: all
  gather_facts: false

  tasks:
    - name: run show commands
      ios_command:
        commands:
          - show ip int br
          - sh ip route
      register: show_result

- name: Debug registered var
  debug: var=show_result.stdout_lines

The first task specifies two commands, so the syntax should be slightly different – the commands should be specified as a list, in YAML format.

$ ansible-playbook ios_command.yml

Both commands completed

If multiple commands are passed to the module, the result of the commands being executed is in the stdout and stdout_lines variables in the list. The output will be in the order in which the commands are described in the task. Due to this, for example, you can display the result of the first command by specifying:

- name: Debug registered var
  debug: var=show_result.stdout_lines[0]

Leave a Reply

Your email address will not be published. Required fields are marked *