Ansible默认过滤器

时间:2019-01-09 12:51:52

标签: python ansible yaml

如何强制默认过滤器尝试找到变量的值,直到找不到值?

在我的代码中 {{netplanadditionalip4 | default('netplanadditionalip3')}}“ 如果没有变量,则打印 netplanadditionalip3 ,但我需要默认过滤器,请尝试netplanadditionalip2 netplanadditionalip1等,这可能吗?

- name: debug1
  debug:
    msg: "{{netplanadditionalip1 | default ('ansible_host')}}"

- name: debug2
  debug:
    msg: "{{netplanadditionalip2 | default('netplanadditionalip1') }}"

- name: debug3
  debug:
    msg: "{{netplanadditionalip3 | default('netplanadditionalip2') }}"

- name: debug4
  debug:
    msg: "{{netplanadditionalip4 | default('netplanadditionalip3') }}"

1 个答案:

答案 0 :(得分:0)

那又怎么样呢?

---
- name: Default Filter Sequence
  hosts: localhost
  connection: local
  gather_facts: true

  vars:

    netplanadditionalip1: 10.100.10.1
    netplanadditionalip2: 10.100.10.2
    netplanadditionalip3: 10.100.10.3

  tasks:

  - name: Fact of Ansible Host
    set_fact:
      my_host: "{{ ansible_host | default () }}"

  - name: debug1
    debug:
      msg: "{{ netplanadditionalip1 | default(my_host) }}"

  - name: debug2
    debug:
      msg: "{{ netplanadditionalip2 | default(item) }}"
    with_items:
      - "{{ netplanadditionalip1 | default( my_host ) }}"

  - name: debug3
    debug:
      msg: "{{ netplanadditionalip3 | default(item) }}"
    with_items:
      - "{{ netplanadditionalip2 | default( netplanadditionalip1 ) | default( my_host ) }}"

  - name: debug4
    debug:
      msg: "{{ netplanadditionalip4 | default(item) }}"
    with_items:
      - "{{ netplanadditionalip3 | default( netplanadditionalip2 ) | default( netplanadditionalip1 ) | default( my_host ) }}"