Pravin RC
Pravin RC

Reputation: 1

How can i capture the failed items only from list of items and display output

I am trying to write Ansible to list only the failed commands from the list of commands

here is the code

---
- name: Verify sudo access
  become: true
  become_user: "{{ install_user }}"
  shell: sudo -l | grep "{{ item }}"
  register: systemctl_result
  loop:
    - /usr/bin/mv
    - /usr/bin/olcenctl
    - /usr/bin/yum
  when: ansible_hostname in groups['operator']
  ignore_errors: true

- name: Print result
  debug:
   var: systemctl_result['results']

/usr/bin/yum is not in sudo list and it fails and I want to capture only the failed command in the output.

Upvotes: 0

Views: 74

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68004

Your problem can be simplified. The become, sudo, ... stuff is not relevant. What you want is to list failed items in the iteration. Use ignore_errors: true to take care of rc: 1 returned by failed grep. For example,

    - shell: "echo ABC | grep {{ item }}"
      register: out
      ignore_errors: true
      loop:
        - A
        - B
        - X

Then, put the below declaration into the vars

    failed_items: "{{ out.results|
                      selectattr('failed')|
                      map(attribute='item')|
                      list }}"

gives what you want

failed_items:
  - X

Example of a complete playbook for testing

- hosts: localhost

  vars:

    failed_items: "{{ out.results|
                      selectattr('failed')|
                      map(attribute='item')|
                      list }}"

  tasks:

    - shell: "echo ABC | grep {{ item }}"
      register: out
      ignore_errors: true
      loop:
        - A
        - B
        - X

    - debug:
        var: failed_items

Upvotes: 2

Related Questions