Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

conditional test on ansible

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 :

  1. pkg_name is a variable. Do not quote it in the brackets
  {{ ansible_facts.packages[pkg_name] }}
  1. 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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading