Search code examples
ansibleansible-2.xsensu

Ansible - automate the deletion of hosts in Sensu


I'm working with Ansible's inventory file and the sensu-cli (interactes with Sensu's API)

Once a server is removed from inventory that server still sticks around until it's manually deleted with an API call.

This workflow works but it's not ideal in anyway.

The last task will delete all servers. Any server that has the sensu-client installed will reach out to the Sensu master and readd itself. Which isn't cool at all.

The idea here is to delete ONLY the servers not in the inventory file.

- name: Get a list hosts in Sensu
  shell: sensu-cli client list -f json | jq -r .[].name
  register: sensu_hosts

- name: Get a list of Ansible hosts
  set_fact:
    sensu_ansible_hosts: "{{ hostvars[item]['inventory_hostname'] }}"
  with_items: groups['all']

- name: Delete clients not in inventory
  shell: sensu-cli client delete {{ item }}
  with_items: sensu_hosts.stdout_lines
  when: item not in sensu_ansible_hosts

Solution

  • Try this:

    - name: Get a list hosts in Sensu
      shell: sensu-cli client list -f json | jq -r .[].name
      register: sensu_hosts
    
    - name: Delete clients not in inventory
      shell: sensu-cli client delete {{ item }}
      with_items: "{{ sensu_hosts.stdout_lines | difference( groups['all'] ) }}"