---
- name: Convert CSV groups into a list
  set_fact:
    r_inv_group_consolidate: |
      [
      {% for csv_host in r_csv_hosts %}
        "{{ csv_host.tower_group }}",
      {% endfor %}
      ]


- name: Create inventory group in Tower
  uri:
    method           : POST
    force_basic_auth : yes
    url_username     : "{{ __tower_user}}"
    url_password     : "{{ __tower_pass}}"
    url              : "{{ __tower_url }}/api/v2/groups/"
    status_code      :
      - 200
      - 201
    headers:
      Content-type   : application/json
    body:
      name           : "{{ lv_tower_group }}"
      inventory      : "{{ r_inv_id.id | default(r_inventory.json.id) }}"
    body_format      : json
    return_content   : no
    validate_certs   : no
  ignore_errors      : yes
  register           : r_inv_group
  loop               : "{{ r_inv_group_consolidate | unique }}"
  loop_control       :
    loop_var         : lv_tower_group
    label            : "{{ lv_tower_group }}"
  when               :
    - "r_inv_group_list | selectattr('name', '==', lv_tower_group) | map(attribute='id') | flatten | length < 1"


- name: Re-fetch inventory group info from Tower
  import_tasks : tasks/fetch_inv_group_list.yml
  when         :
    - r_inv_group.results | rejectattr('skipped', 'defined')


...
