Wednesday, May 03, 2023

Ansible code to update AWX Ansible Inventory

Ansible code to update AWX Ansible Inventory

Here is the playbook:

---
- name: Update Inventory
  hosts: localhost
  gather_facts: False   roles:
    - role: roles/update_inventor
y

localhost is used for hosts: because the AWX REST API endpoints are accessible from the Ansible master we are running on.


Use that playbook in an AWX Job Template

  • The job template needs to prompt the user for "Inventory" on launch.
Respond with the inventory the hosts you wish to update are in. This will provide the value to the special AWX variable tower_inventory_id. 
  • The job template needs to prompt the user for "Variables" on launch.
Example:
---
update_ati_fqdns:
- host1.example.com
- host2.example.com
ansible_connection: 'local'
  • You will need a survey for your Job Template
    • Admin Username: admin_username
    • Admin User Password: admin_password
    • URL for AWX REST API GROUP endpoint: http://awx.example.com/api/v2/groups
    • update_ati_group: integer
    • Action: pulldown [REMOVE_FROM_GROUP, ADD_TO_GROUP]

Here is the role:


defaults/main.yml --- awx_base_url: "https://awx.example.com"
tasks/main.yml --- - name:   ansible.builtin.include_tasks: test_block_loop.yml   loop: "{{ update_ati_fqdns }}"

tasks/test_block_loop.yml

--- - name: Get Host ID   uri:     url: "{{ awx_base_url }}/api/v2/inventories/{{ tower_inventory_id }}/hosts/?name={{ item }}"     method: GET     user: "{{ admin_username }}"     password: "{{ admin_password }}"     force_basic_auth: yes     validate_certs: no     headers:       Content-Type: "application/json"   register: host_result   failed_when: host_result.status != 200 or host_result.json.count != 1 - name: "Set payload for add."   set_fact:     body: "{ \"id\" : {{ host_result.json.results[0].id | int }} }" - name: "Set payload for disassociate/remove."   set_fact:     body: "{ \"disassociate\" : {{ host_result.json.results[0].id | int }}, \"id\" : {{ host_result.json.results[0].id | int }} }"   when: selected_action == "REMOVE_FROM_GROUP" - name: Update Ansible Tower inventory   uri:     url: "{{ update_ati_groups_api }}/{{ update_ati_group }}/hosts/"     user: "{{ admin_username }}"     password: "{{ admin_password }}"     method: "POST"     body: "{{ body }}"     force_basic_auth: yes     status_code: 204     body_format: json     validate_certs: no