I am trying to check if a specific package is installed or not using ansible, here’s my tasks
- name: check whether a package called {{ pkg_name }} is installed or not
ansible.builtin.debug:
msg: "{{ ansible_facts.packages['pkg_name'] }} is installed
when: "pkg_name in ansible_facts.packages"
pkg_name is variable defined my me, I’ve tried different combinations with ansible_facts like:
"{{ ansible_facts.packages['pkg_name'] }} is installed"
"{{ ansible_facts.packages.{{ pkg_name }} }} is installed"
but none of the method works however if I simply put the string instead of variable it works fine ie.
ansible_facts.packages['httpd']
what is the correct syntax to check with variable?
also confirm can I pass array to it to check multiple packages at the same time
>Solution :
- pkg_name is a variable. Do not quote it in the brackets
{{ ansible_facts.packages[pkg_name] }}
- Do not quote the condition
when: pkg_name in ansible_facts.packages
Example of a complete playbook for testing
shell> cat pb.yml
- hosts: foo
tasks:
- package_facts:
manager: auto
- debug:
msg: "{{ ansible_facts.packages[item].0.name }} is installed."
when: item in ansible_facts.packages
loop:
- openssh
- http
gives
shell> ansible-playbook pb.yml
PLAY [foo] ************************************************************************************
TASK [package_facts] **************************************************************************
ok: [foo]
TASK [debug] **********************************************************************************
ok: [foo] => (item=openssh) =>
msg: openssh is installed.
skipping: [foo] => (item=http)
PLAY RECAP ************************************************************************************
foo: ok=2 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0