I want to conditionally define a variable in an Ansible playbook like this:
my_var: \"{{ \'foo\' if my_condition}}\"
My example, after https://stackoverflow.com/a/43403229/5025060:
vars:
sudoGroup: "{{ 'sudo' if ansible_distribution == 'Ubuntu' else 'wheel' }}"
Because of the different sudo conventions used by Ubuntu versus other platforms, here I am telling Ansible to set a variable named sudoGroup
to sudo
if the platform is Ubuntu, otherwise set it to wheel
.
Later in my playbook, I combine the variable with Ansible's user
module to add either sudo
or wheel
to an account's secondary groups depending on the OS Ansible is running on:
- name: Add or update bob account
user:
name: bob
uid: 3205
groups: "{{ sudoGroup }}"
append: yes
NOTES:
{{ variable }}
are required in the user: groups:
definition above.sudoGroup
as above in my playbook's global vars:
section, Ansible configures it at run time (based on ansible_distribution
) for each target I define in my hosts:
section.