1

I can't seem to get the register to works with cli_command and looping of multiples commands. Any suggestions?

-

name:  Run show commands
  hosts:
    - all
  connection: network_cli
  gather_facts: no

  vars:
     shcmd:
       - show bgp sum | match 3356
       - show config protocols bgp group Level3

  tasks:

    - name: create report directory if needed
      set_fact:
        report_dir: "{{ user_data_path }}/reports"

    - name: confirm report directory
      file:
        path: "{{ report_dir }}"
        state: directory

    - name: Run commands
      cli_command:
          command: "{{item}}"
      register: "showcmds"
      with_items: "{{shcmd}}"

    - debug:
        msg: "{{ showcmds.stdout_lines }}"
        with_items: "{{shcmd}}"

1 Answer 1

2

There are a couple of things here:

  1. The indent of "with_items" on the debug module is wrong, it should the same level as the "debug" word.

  2. More importantly, in this case the "with_items" variable on the debug is wrong. When you added "register" to the cli_command module, you actually said "collect the output from every iteration and return the whole lot". Therefore, you need to iterate over the variable you created with "register", not the variable you passed into the command itself. Something like below (I'm not at a computer atm so this will need to be checked):

    - debug:
        msg: "{{ item.stdout_lines }}"
      with_items: "{{ showcmds }}"

edit: OK, sounds like this specific module doesn't return stdout_lines. Try running the debug with just "{{ showcmds }}" and without the "with_items" to get the actual structure of the variable.

2
  • with_items: - "show configuration protocols bgp group Level3 | display set | match export" - "show configuration protocols bgp group Level3-1 | display set | match export" - debug: msg: "{{ item.stdout_lines }}" with_items: "{{ showcmds }}"
    – chester
    Jul 26, 2021 at 13:43
  • REsults in an error. TASK [debug] ********************************************************************************************************** fatal: [stn4-llpb-01]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible.utils.unsafe_proxy.AnsibleUnsafeText object' has no attribute 'stdout_lines'\n\nThe error appears to be in '/home/aa78103/ansible/show.yaml': line 51, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n - debug:\n ^ here\n"}
    – chester
    Jul 26, 2021 at 13:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.