问题
Can we use conditionals in "vars:" section of a playbook, I am aware of set_fact in tasks ,but I want to know we could use in section like below:
---
- hosts: "{{ host1 }}"
vars:
var1: "{{ passed_var1 }}"
var2: "<conditionally assign value based on {{ var1 }}"
回答1:
You can do something like:
---
- name: Test Play
hosts: local
gather_facts: false
vars:
var1: hola
var2: "{{ 'foo' if var1 else '' }}"
tasks:
- name: debug var1
debug:
var: var1
- name: debug var2
debug:
var: var2
You will get:
PLAY [Test Play] ***************************************************************
TASK [debug1] ******************************************************************
ok: [localhost] => {
"var1": "hola"
}
TASK [debug1] ******************************************************************
ok: [localhost] => {
"var2": "foo"
}
Another Example:
---
- name: Test Play
hosts: local
gather_facts: false
vars:
var1: hola
var2: "{{ 'foo' if var1 == 'hola' else '' }}"
tasks:
- name: debug var1
debug:
var: var1
- name: debug var2
debug:
var: var2
来源:https://stackoverflow.com/questions/49959811/use-conditionals-in-vars-ansible