set_fact创建包含商品的列表

时间:2019-04-08 18:37:19

标签: ansible ansible-2.x

我有一个调用API的任务,并且在变量中注册了o / p;

- name: Get Object storage account ID
  uri:
    url: 'https://api.softlayer.com/rest/v3.1/SoftLayer_Network_Storage_Hub_Cleversafe_Account/getAllObjects.json?objectFilter={"username":{"operation":"{{ item }}"}}'
    method: GET
    user: abxc
    password: 66c94c447a6ed8a0cf058774fe38
    validate_certs: no
  register: old_existing_access_keys_sl
  with_items: '{{ info["personal"].sl_cos_accounts }}'

old_existing_access_keys_sl持有:

"old_existing_access_keys_sl.results": [
 {
            "json": [
                {
                    "accountId": 12345, 
                    "id": 70825621, 
                    "username": "xyz-11"
                }
            ]
},
{
            "json": [
                {
                    "accountId": 12345, 
                    "id": 70825621, 
                    "username": "abc-12"
                }
            ]
}

我想列出id以便进一步处理,尝试了以下任务,但这不起作用:

- name: Create a list of account ids
  set_fact: 
    admin_usernames = "{{ item.json[0].id | list }}"
  with_items: old_existing_access_keys_sl.results

我不确定这是否可能。我也尝试过:

    - name: create a list
      set_fact:
         foo: "{% set foo = [] %}{% for i in old_existing_access_keys_sl.results %}{{ foo.append(i) }}{% endfor %}"

foo总是以空白和字符串形式出现:


TASK [result] *****************************************************************************************************************************************
ok: [localhost] => {
    "foo": ""
}

1 个答案:

答案 0 :(得分:1)

给出示例数据,您可以使用json_query过滤器提取ID列表,如下所示:

---
- hosts: localhost
  gather_facts: false
  vars:
    old_existing_access_keys_sl:
      results:
        [
          {
            "json": [
              {
                "accountId": 12345,
                "id": 70825621,
                "username": "xyz-11"
              }
            ]
          },
          {
            "json": [
              {
                "accountId": 12345,
                "id": 70825621,
                "username": "abc-12"
              }
            ]
          }
        ]
  tasks:
    - debug:
        var: old_existing_access_keys_sl|json_query('results[*].json[0].id')

这将输出:

TASK [debug] **********************************************************************************************************************************************************************************
ok: [localhost] => {
    "old_existing_access_keys_sl|json_query('results[*].json[0].id')": [
        70825621, 
        70825621
    ]
}

如果要将它们存储在新变量中,可以将debug任务替换为set_fact

    - set_fact:
        admin_ids: "{{ old_existing_access_keys_sl|json_query('results[*].json[0].id') }}"

更新

要获取字典列表,只需更改json_query表达式:

- debug:
    var: "old_existing_access_keys_sl|json_query('results[*].json[0].{id: id, username: username}')"

有关更多信息,请参见jmespath website,以获取文档和示例。