--- - name: "Initialize VARs" set_fact: api_path: '/s/{{ es_space }}/api/saved_objects' es_object_type: 'index-pattern' indexpattern_exists: False elastic_indexpattern_cleaned: {} - name: "Get all indexpatterns in elasticsearch" delegate_to: localhost uri: url: "https://{{ api_endpoint }}{{ api_path }}/_find?per_page=10000&type=index-pattern" method: GET status_code: [200] user: "{{ elastic_admin_username }}" password: "{{ elastic_admin_password }}" force_basic_auth: yes register: all_indexpatterns become: false - name: "Lookup index pattern object if exists" set_fact: lookup_indexpattern_object: '{{ all_indexpatterns.json | community.general.json_query(querystr1) | first | community.general.json_query(indexpattern_query) }}' vars: querystr1: "[saved_objects[*]]" indexpattern_query: "[?attributes.title=='{{ elastic_indexpattern.attributes.title }}']" - name: "Set switch VAR" set_fact: indexpattern_exists: True when: - lookup_indexpattern_object | length > 0 - name: "Drop not needed key from dict" set_fact: elastic_indexpattern_cleaned: "{{ elastic_indexpattern_cleaned | combine({item.key: item.value}) }}" with_dict: '{{ elastic_indexpattern }}' when: - item.key not in ['elastic_state'] - name: "Create {{ es_object_type }} <<{{ elastic_indexpattern.attributes.title }}>>" delegate_to: localhost uri: url: "https://{{ api_endpoint }}{{ api_path }}/{{ es_object_type }}" method: POST status_code: [200] user: "{{ elastic_admin_username }}" password: "{{ elastic_admin_password }}" force_basic_auth: yes headers: Content-Type: application/json kbn-xsrf: true body_format: json body: '{{ elastic_indexpattern_cleaned | to_json }}' become: false when: - not indexpattern_exists - elastic_indexpattern.elastic_state == 'present' - name: "Update {{ es_object_type }} <<{{ elastic_indexpattern.attributes.title }}>>" delegate_to: localhost uri: url: 'https://{{ api_endpoint }}{{ api_path }}/{{ es_object_type }}/{{ lookup_indexpattern_object[0]["id"] }}' method: PUT status_code: [200] user: "{{ elastic_admin_username }}" password: "{{ elastic_admin_password }}" force_basic_auth: yes headers: Content-Type: application/json kbn-xsrf: true body_format: json body: '{{ elastic_indexpattern_cleaned | to_json }}' become: false when: - indexpattern_exists - elastic_indexpattern.elastic_state == 'present' - name: "DELETE {{ es_object_type }} <<{{ elastic_indexpattern.attributes.title }}>>" delegate_to: localhost uri: url: 'https://{{ api_endpoint }}{{ api_path }}/{{ es_object_type }}/{{ lookup_indexpattern_object[0]["id"] }}' method: DELETE status_code: [200] user: "{{ elastic_admin_username }}" password: "{{ elastic_admin_password }}" force_basic_auth: yes headers: Content-Type: application/json kbn-xsrf: true become: false when: - indexpattern_exists - elastic_indexpattern.elastic_state == 'absent'