![Ansible 使用 json 和 with_items 循环来获取数组吗?](https://linux22.com/image/736273/Ansible%20%E4%BD%BF%E7%94%A8%20json%20%E5%92%8C%20with_items%20%E5%BE%AA%E7%8E%AF%E6%9D%A5%E8%8E%B7%E5%8F%96%E6%95%B0%E7%BB%84%E5%90%97%EF%BC%9F.png)
我正在尝试使用 ansible 的 api 设置一些 elasticsearch 角色,当我运行我的代码时,我似乎得到了下面的内容,而不是预期的
不正确的“索引”:[{“名称”:[“docker-, logstash-, .kibana” ], “特权” : [ “读取 view_index_metadata” ],
当我看到角色时预期的结果
"indices" : [
{
"names" : [
"docker*",
"springxd-*",
"logstash-*"
],
我正在使用 ansible 循环
- 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' }
知道如何才能得到正确的结果吗?
提前致谢
答案1
如果您的值在此处,则“index_names”没有任何引号。 Ansible 不会神奇地添加它们,至少在您仅将“index_names”用作字符串时不会。
with_items:
- { role_name: app_components_role, index_names: 'docker-*, logstash-*, .kibana, springxd-*', privileges: 'read, view_index_metadata' }
也许可以调整你的物品让它看起来像这样?
with_items:
- { role_name: app_components_role, index_names: '"docker-*", "logstash-*", ".kibana", "springxd-*"', privileges: '"read", "view_index_metadata"' }
或者也许这样,如果你还想使它更具可读性。
with_items:
- role_name: app_components_role
index_names: '"docker-*", "logstash-*", ".kibana", "springxd-*"'
privileges: '"read", "view_index_metadata"'
或者,如果您想要更好的可读性,也许可以调整为这样的内容。
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