如何运行基于可视值的ansible任务

时间:2019-06-13 07:48:27

标签: ansible ansible-facts

我正在尝试根据键中元素的数量创建一项任务。

我的输入将像下面的json输入

“ srcaddr”:“ IP_192.168.10.10,IP_192.168.10.12”

或json数组

“ srcaddr”:['IP_192.168.10.10','IP_192.168.10.12']

  - name: ADD IPv4 IP ADDRESS GROUP
    chkr_fwobj_address:
      ipv4: "group"
      group_name: "ansibleIPv4Group1"
      group_members: "{{ srcaddr }}"
      adom: "{{ adom }}"
    when: "{{ srcaddr |length > 1}}"

我想在元素的数量超过一个时执行上述任务,其中一个任务将创建一个组并将成员添加到该组中。如果我们只有一个元素,那么组创建任务将被忽略

1 个答案:

答案 0 :(得分:1)

何时条件不应扩展。正确的语法是

when: srcaddr|length > 1

下面的戏

- hosts: localhost
  vars:
    srcaddr1: ['IP_192.168.10.10']
    srcaddr2: ['IP_192.168.10.10', 'IP_192.168.10.12']
  tasks:
    - debug:
        msg: There is more then 1 address in the list srcaddr1.
      when: srcaddr1|length > 1
    - debug:
        msg: There is more then 1 address in the list srcaddr2.
      when: srcaddr2|length > 1

给予:

PLAY [localhost] *******************************************************

TASK [debug] ***********************************************************
skipping: [localhost]

TASK [debug] **********************************************************
ok: [localhost] => {
    "msg": "There is more than 1 address in the list srcaddr2."
}

PLAY RECAP *************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0

注意:srcaddr: 'IP_192.168.10.10'的长度是字符串的长度。 srcaddr: [ 'IP_192.168.10.10' ]的长度是列表的长度。