- name: Get secrets for SNMP manager
  set_fact:
    manager: '{{ lookup("passwordstore", "host/"+snmp_manager.name, returnall=true, missing="empty") | from_yaml }}'

- name: Generate SNMP passwords
  delegate_to: localhost
  command: 'snmpv3-hashgen --yaml --user {{ manager.snmp_user }} --auth {{ manager.snmp_pass }} --priv {{ manager.snmp_pass }} --hash sha1 --engine {{ snmp_engine_id }}'
  check_mode: false
  changed_when: false
  register: snmp_config

- name: Get SNMP password hash
  set_fact:
    snmp_hashes: '{{ (snmp_config.stdout | from_yaml).snmpv3.hashes }}'

- name: Get switch facts
  cisco.ios.ios_facts:
    gather_subset: config

- name: Get SNMP users
  set_fact:
    snmp_current: "{{ ansible_net_config | split('\n') | select('match', '^snmp-server user '+manager.snmp_user+' public v3') }}"
    snmp_target: "snmp-server user {{ manager.snmp_user }} public v3 encrypted auth sha {{ snmp_hashes.auth }} priv {{ snmp_hashes.priv[:32] }} "

- name: Remove existing SNMP user to reset password
  when: 'snmp_current and snmp_target is not in snmp_current'
  block:
    - name: Remove SNMP user
      ansible.netcommon.cli_config:
        config: 'no snmp-server user {{ manager.snmp_user }} public v3'
      notify: write config

    - set_fact:
        snmp_current: false

- name: Create SNMP user
  when: 'not snmp_current'
  ansible.netcommon.cli_config:
    config: '{{ snmp_target }}'
  notify: write config