Hi all,
I’ve just started learning Ansible and I have a question about checking for defined variables in included tasks. I’m writing an infrastructure role as a part of my test project configuration. Currently, the role only creates infrastructure users by including a “create infrastructure user” task and looping over a users variable containing a list of usernames and associated SSH public keys:
My main.yml tasks for the role:
`
- name: Create infrastructure users
include_tasks: user.yml
vars:
username: “{{ item.username }}”
ssh_key: “{{ item.ssh_key }}”
loop: “{{ users }}”
`
My user.yml tasks:
`
-
name: “Create infrastructure user {{ username }}”
user:
name: “{{ username }}”
state: present
groups: -
sudo
append: yes -
name: “Set SSH key for {{ username }}”
authorized_key:
user: “{{ username }}”
key: “{{ ssh_key }}”
when: ssh_key is defined
`
Now, if a user doesn’t have an ssh_key defined, I would expect the authorized_key task not to run. However, I get the following error message:
`
The conditional check ‘ssh_key is defined’ failed. The error was: error while evaluating conditional (ssh_key is defined): ‘dict object’ has no attribute ‘ssh_key’
The error appears to have been in ‘/home/bozho/projects/vault/roles/infrastructure/tasks/user.yml’: line 9, column 3, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: “Set SSH key for {{ username }}”
^ here
We could be wrong, but this one looks like it might be an issue with
missing quotes. Always quote template expression brackets when they
start a value. For instance:
with_items:
- {{ foo }}
Should be written as:
with_items:
- “{{ foo }}”
`
If I rewrite the when condition as:
`
when: dict.ssh_key is defined
`
everything works as expected (i.e. the tasks is skipped for users with no ssh_key set.
Is this the expected behaviour? I would expect task parameters to be handled as variables.
Thank you!
``