Ansible loop with json and with_items for array

ansible

I am trying to set up some elasticsearch roles using the api with ansible and when I run my code I seem to get this below rather than the expected

Incorrect
"indices" : [
{
"names" : [
"docker-, logstash-, .kibana"
],
"privileges" : [
"read view_index_metadata"
],

expected outcome when I view the role

    "indices" : [
  {
    "names" : [
      "docker*",
      "springxd-*",
      "logstash-*"
    ],

I am using an ansible loop

  - name: Setup Special kibana Roles for Spaces which are later mapped to LDAP
uri:
  url: "https://{{ ansible_fqdn }}:9200/_xpack/security/role/{{ item.role_name }}"
  method: PUT
  user: '{{ vault_elastic_user }}'
  password: '{{ vault_elastic_pass }}'
  body: '{ "indices": [ { "names": [ "{{ item.index_names }}" ], "privileges": [ "{{ item.privileges }}" ], "field_security" : { "grant" : [ "*" ] } } ] }'
  body_format: json
  validate_certs: no
  headers:
    Content-Type: "application/json"
with_items:
  - { role_name: app_components_role, index_names: 'docker-*, logstash-*, .kibana, springxd-*', privileges: 'read, view_index_metadata' }

Any idea how to make the get the right outcome?

Thanks in advance

Best Answer

If your value here, your 'index_names' doesn't have any quotes. Ansible isn't going to magically add them, at least not when you are j ust using 'index_names' as a string.

with_items:
  - { role_name: app_components_role, index_names: 'docker-*, logstash-*, .kibana, springxd-*', privileges: 'read, view_index_metadata' }

Maybe adjust your item to look like this?

with_items:
  - { role_name: app_components_role, index_names: '"docker-*", "logstash-*", ".kibana", "springxd-*"', privileges: '"read", "view_index_metadata"' }

Or maybe this if yoiu also want to make it more readable.

with_items:
  - role_name: app_components_role
    index_names: '"docker-*", "logstash-*", ".kibana", "springxd-*"'
    privileges: '"read", "view_index_metadata"'

Or if you want to go with the even better readability adjust to something like this maybe.

uri:
  ...
  body: |
    { "indices": [ 
      { "names": {{ item.index_names | to_json }},
        "privileges": {{ item.privileges | to_json }}, 
        "field_security" : { "grant" : [ "*" ] }
      } ]
    }
  ...
with_items:
  - role_name: app_components_role
    index_names:
    - docker-*
    - logstash-*
    - .kibana
    - springxd-*
    privileges:
    - read
    - view_index_metadata