ansiblecisco

Ansible Cisco configuration compliance check for invalid users


I am attempting to validate a Cisco configuration with Ansible. I want to be able to tell whether any users have been configured other than the valid ones.

Valid users: username admin, username readonly

Invalid users: username secretbackdoor

I have tried to create a list of users, then flag any which are not valid. The code i have so far is as follows:

---
- hosts: cisco
  gather_facts: no

  tasks:

- name: show run
  ios_command:
    commands:
     - show run
  register: cisco_show_run

    - name: list_cisco_usernames
  set_fact: cisco_usernames="{{ cisco_show_run.stdout[0] | regex_findall('username (\S+)', multiline=True) }}"

- name: print usernames
  debug:
    msg: {{ item }}
  with_items: "{{ cisco_usernames }}"

This will print out the three users. Not sure where to go next.


Solution

  • "Set Theory Filters" might be next option. For example

    - hosts: localhost
      vars:
        valid_users: [admin, readonly]
        invalid_users: [secretbackdoor]
        cisco_usernames: [admin, readonly, secretbackdoor]
    
      tasks:
    
        - name: Display users not in valid_users
          debug:
            msg: Not among valid users {{ not_valid }}
          when: not_valid|length > 0
          vars:
            not_valid: "{{ cisco_usernames|difference(valid_users) }}"
    
        - name: Display users in invalid_users
          debug:
            msg: Among invalid users {{ not_valid }}
          when: not_valid|length > 0
          vars:
            not_valid: "{{ cisco_usernames|intersect(invalid_users) }}"
    

    gives (abridged)

    ok: [localhost] => 
      msg: Not among valid users ['secretbackdoor']
    
    ok: [localhost] => 
      msg: Among invalid users ['secretbackdoor']