I am trying to get a when
condition to match a string value in a list of strings in Ansible. I’m defining my list variables in the all
host inventory group. I call these list variables from many of play, playbooks and roles.
all:
vars:
ubuntu_18.04_codenames:
- 'bionic'
- 'tara'
- 'tessa'
- 'tina'
- 'tricia'
ubuntu_20.04_codenames:
- 'focal'
- 'ulyana'
- 'ulyssa'
- 'uma'
- 'una'
ubuntu_22.04_codenames:
- 'jammy'
- 'vera'
- 'vanessa'
- 'Victoria'
I define my task’s when condition like this:
- name: "Adding Docker 20.04 APT repository"
apt_repository:
repo: deb https://download.docker.com/linux/ubuntu focal stable
when: 'ansible_lsb.codename in ubuntu_20.04_codenames'
I get the error:
FAILED! => {"msg": "The conditional check ‘ansible_lsb.codename in ubuntu_22.04_codenames’ failed. The error was: template error while templating string: expected token ‘end of statement block’, got ‘integer’. String: {% if ansible_lsb.codename in ubuntu_22.04_codenames %} True {% else %} False {% endif %}. expected token ‘end of statement block’, got ‘integer’
I’m using ansible_lsb.codname
with my list variable ubuntu_20.04_codenames
. I keep on getting syntax errors, no matter what I try.
2
Answers
Please take note first about Creating valid variable names as your current example would result into
A minimal example playbook using
contains
test – does the list contain this elementwill result into an output of
If interested into reproducing the mentioned syntax error message, just change the condition to
containing an invalid variable name. It will result into
Because the
.
as a meaning in Ansible — namely it helps access an attribute of a dictionary — using it in a top level variable is going to give you a little but of trouble.If you where in a subdirectory, i.e.:
You could just get away using the array notation:
But, since you are are the top level of variables, you will have to resort to using the
vars
lookup:Given the inventory:
And the task:
This yields: