---
- name: "Set some VARs"
  set_fact:
    idx_tmpl_state: "{{ idx_tmpl.idx_tmpl_state | default('present') }}"
    api_object: '_index_template'
  tags:
    - always

- name: "Check if index template already exists"
  uri:
    url: "https://{{ elastic_api_endpoint }}/{{ api_object }}/{{ idx_tmpl.name }}"
    method: GET
    status_code: [200,404]
    user: "{{ elastic_admin_username }}" 
    password: "{{ elastic_admin_password }}"
    force_basic_auth: yes 
    headers:
      Content-Type: application/json
    validate_certs: no
  register: check_index_exists
  tags:
    - always

- name: "Create Index template"
  uri:
    url: "https://{{ elastic_api_endpoint }}/{{ api_object }}/{{ idx_tmpl.name }}"
    method: PUT
    status_code: [200]
    user: "{{ elastic_admin_username }}" 
    password: "{{ elastic_admin_password }}"
    force_basic_auth: yes 
    body: "{{ idx_tmpl.template | to_json }} "
    headers:
      Content-Type: application/json
    validate_certs: no
  when:
    - idx_tmpl_state == 'present'
    - check_index_exists.status in [404]
  tags:
    - always

- name: "Delete Index template"
  uri:
    url: "https://{{ elastic_api_endpoint }}/{{ api_object }}/{ idx_tmpl.name }}"
    method: DELETE
    status_code: [200]
    user: "{{ elastic_admin_username }}" 
    password: "{{ elastic_admin_password }}"
    force_basic_auth: yes 
    body: "{{ idx_tmpl.template }} "
    headers:
      Content-Type: application/json
    validate_certs: no
  when:
    - idx_tmpl_state == 'absent'
    - check_index_exists.status in [200]

  tags:
    - always
