Please bear with me for a basic question but I'm very new to Ansible and trying to create my first playbook for Windows servers. I have a scenario where I need to set the value of a variable based on a condition, if the server name contains 'Z', use one value, else use a different value. Is this syntax correct? Thank you!
vars:
my_variable: "{{ 'value_if_contains_Z' if 'Z' in inventory_hostname else 'default_value' }}"
Please bear with me for a basic question but I'm very new to Ansible and trying to create my first playbook for Windows servers. I have a scenario where I need to set the value of a variable based on a condition, if the server name contains 'Z', use one value, else use a different value. Is this syntax correct? Thank you!
vars:
my_variable: "{{ 'value_if_contains_Z' if 'Z' in inventory_hostname else 'default_value' }}"
Share
Improve this question
asked Mar 14 at 21:24
user18610347user18610347
1331 silver badge8 bronze badges
1
- This question is similar to: How to pass different value in different condition of the same variable in Ansible? or Conditionally define variable in Ansible or How to use IF ELSE in YAML with variable?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – U880D Commented Mar 15 at 0:00
1 Answer
Reset to default 1For a not optimal structured inventory file example.ini
(annot.: see also How to build your inventory)
[locations]
usazure.example
caazure.example
usgcp.example
cagcp.example
usaws.example
caaws.example
a minimal example playbook
---
- hosts: locations
become: false
gather_facts: false
vars:
platform: "{{ 'azure' if inventory_hostname_short is search('z') else 'other' }}"
tasks:
- debug:
var: platform
will result into an output of
TASK [debug] ***************
ok: [usazure.example] =>
platform: azure
ok: [caazure.example] =>
platform: azure
ok: [usgcp.example] =>
platform: other
ok: [cagcp.example] =>
platform: other
ok: [usaws.example] =>
platform: other
ok: [caaws.example] =>
platform: other
An other syntax will produce the same results
platform: "{{ 'azure' if 'z' in inventory_hostname_short else 'other' }}"