Hi all
We tend to follow the GPA Good Practices for Ansible - GPA for our Ansible coding standards. GPA states that bracket notation foo['bar']
should be used in lieue of dot notation foo.bar
for variables:
Use bracket notation instead of dot notation for value retrieval (e.g. item['key']
vs. item.key
)
Dot notation will fail in some cases (such as when a variable name includes a hyphen) and it’s better to stay consistent than to switch between the two options within a role or playbook. Additionally, some key names collide with attributes and methods of Python dictionaries such as count
, copy
, title
, and others (refer to the Ansible User Guide for an extended list)
Now I saw that someone in our project used a variable with a hyphen in it let’s call it foo-server
, and he used the following code which works:
block:
- name: blablabla
when: "'foo-server.bar' in ansible_facts.services"
ansible.builtin.service:
name: foo-server
state: stopped
However this does not follow GPA hence I tried the following to improve our coding standards, which oddly and contrary to my expectations does NOT work. And when you quote the entire string in when
, it ALSO DOES NOT WORK.
block:
- name: blablabla
when: foo-server['bar'] in ansible_facts['services']
ansible.builtin.service:
name: foo-server
state: stopped
**Questions:
- Why does my version not work?
- Does this mean that the advice in GPA to use bracket notation rather than dot notation is untrue and that we should definitely reconsider following this guide? Are there other, better best practice guides to improve our Ansible coding standard?**
- Include relevant logs from the issue
-
Confidential environment, but the task failed due to variables not being interpreted properly when using the bracket notation ending the playbook. For example it will only see the part before the hyphen
-
and think that is the variable name, which it isn’t, and that causes failure.- - Include the version(s) of the relevant software tools, libraries, collections etc
ansible [core 2.15.13]
config file = /etc/ansible/ansible.cfg
python version = 3.9.20 (main, Sep 26 2024, 20:59:47) [GCC 8.5.0 20210514 (Red Hat 8.5.0-22)] (/usr/bin/python3.9)
jinja version = 3.1.6
libyaml = True