---
#
# Summary: Auto generate (or update) the Ansible inventory file with all servers (Name and Moid or each discovered server)
#
# The hosts group used is provided by the group variable or defaulted to 'Intersight'.
# You can specify a specific host (or host group) on the command line:
#   ansible-playbook ... -e group=<your host group>
#   e.g., ansible-playbook server_profiles.yml -e group=TME_Demo
#
# This playbook only runs once (and not for each server in the inventory), but the hosts group is used to get API key info
#
- hosts: "{{ group | default('Intersight') }}"
  connection: local
  gather_facts: false
  vars:
    # Create an anchor for api_info that can be used throughout the file
    api_info: &api_info
      api_private_key: "{{ api_private_key }}"
      api_key_id: "{{ api_key_id }}"
      api_uri: "{{ api_uri | default(omit) }}"
      validate_certs: "{{ validate_certs | default(omit) }}"
      state: "{{ state | default(omit) }}"
    # Change filepath if you want to update a different inventory file
    filepath: "{{ inventory_file }}"
    # Change host_group if you want to use another group name for your servers in the created inventory
    host_group: Intersight_Servers
  tasks:
    # Enclose tasks in a block that is only run once
    - block:
        # Find all servers
        - cisco.intersight.intersight_info:
            <<: *api_info
            server_names:
          register: all_results
        # Place the servers in a group in the file
        - debug:
            msg: Inventory filepath "{{ filepath }}"
        - lineinfile:
            path: "{{ filepath }}"
            line: "[{{ host_group }}]"
            create: true
        # Update servers in the file
        - lineinfile:
            path: "{{ filepath }}"
            insertafter: "^\\[{{ host_group }}\\]"
            regexp: "^{{ item.Name }} serial={{ item.Serial }} "
            # Each line of the inventory has the following:
            # Name server_moid=<Moid value> model=<Model value> boot_policy=<policy from tag> | 'na'
            line: "{{ item.Name }} serial={{ item.Serial }} server_moid={{ item.Moid }} model={{ item.Model }}"
            create: true
          # Ansible and jmespath contains have type differences, so to/from_json used
          loop: "{{ all_results.intersight_servers | json_query(platform_query) | to_json | from_json | json_query(model_query) }}"
          loop_control:
            label: "{{ item.Name }}"
          vars:
            # Filter for IMC and C-Series only (no HX)
            platform_query: "[?PlatformType=='IMC']"
            model_query: "[?contains(Model, 'HX')]"
          when: all_results.intersight_servers is defined
      delegate_to: localhost
      run_once: true
