Ansible 循环和数组

Ansible Loop & Array

我需要循环一个名称列表以在查询本身中使用它。循环后,我想从查询本身收集信息并将其存储在数组中。我设法将它存储在一个数组中,但每当我重新 运行 程序时,它都会一次又一次地添加相同的值。

我的数据:

    priv: [admin, monitor]
    data:
      - {name: admin, locked: 'no', uid: 0}
      - {name: monitor, locked: 'no', uid: 102}

这是我的代码:

    - name: Test Informationk 
      set_fact: 
        info2: "{{ data|json_query(jmesquery) + info2|default([]) }}"
        cacheable: yes
      vars: 
        jmesquery: "[?name=='{{ item }}'].[name,locked,uid]"
      loop: "{{ priv }}"

这是我的输出:

    - - monitor
        'no'
        102
    - - admin
        'no'
        0
    - - monitor
        'no'
        102
    - - admin
        'no'
        0
    - - monitor
        'no'
        102
    - - admin
        'no'
        0

每次我重新运行程序时,它都会不断添加和添加。现有数据应该只有2项。

问:"每当我re-run程序时,它会一次又一次地添加相同的值。"

答:你设置cacheable: yes。引用自 cacheable:

This actually creates 2 copies of the variable, a normal 'set_fact' host variable with high precedence and a lower 'ansible_fact' one that is available for persistence via the facts cache plugin.

如果您不想缓存变量,请将其禁用。如果您想详细了解发生了什么,请在 set_fact 前面放置一个调试,例如下面的剧本

- hosts: localhost
  vars:
    priv: [admin, monitor]
    data:
      - {name: admin, locked: 'no', uid: 0}
      - {name: monitor, locked: 'no', uid: 102}
  tasks:
    - debug:
        var: info2
    - set_fact:
        info2: "{{ data|json_query(jmesquery) + info2|default([]) }}"
        cacheable: false
      vars:
        jmesquery: "[?name=='{{ item }}'].[name,locked,uid]"
      loop: "{{ priv }}"
    - debug:
        var: info2

给予

TASK [debug] *******************************************************
ok: [localhost] => 
  info2: VARIABLE IS NOT DEFINED!

TASK [set_fact] ****************************************************
ok: [localhost] => (item=admin)
ok: [localhost] => (item=monitor)

TASK [debug] *******************************************************
ok: [localhost] => 
  info2:
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0

如果你在set_fact中同时设置了cacheable: true和下面的配置(我猜你一定已经设置了缓存)

shell> cat ansible.cfg
[defaults]
fact_caching = jsonfile
fact_caching_connection = /tmp/ansible_cache.json

...

然后您会看到该列表在每个连续的 运行 剧本中递增

TASK [debug] ***************************************************
ok: [localhost] => 
  info2:
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0

TASK [set_fact] ***********************************************
ok: [localhost] => (item=admin)
ok: [localhost] => (item=monitor)

TASK [debug] **************************************************
ok: [localhost] => 
  info2:
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0
  - - monitor
    - 'no'
    - 102
  - - admin
    - 'no'
    - 0

查看缓存

shell> cat /tmp/ansible_cache.json/localhost 
{
    "info2": [
        [
            "monitor",
            "no",
            102
        ],
        [
            "admin",
            "no",
            0
        ]
    ]
}