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

How do I combine two commands in one task? | Ansible

So, my problem is that I want to check if nginx is installed on two different OS with different package managers.

 - name: Veryfying nginx installation # RedHat
   command: "rpm -q nginx"
   when: ansible_facts.pkg_mgr in ["yum","dnf","rpm"] #or (ansible_os_family == "RedHat")
   
 - name: Veryfying nginx installation # Debian
   command: "dpkg -l nginx"
   when: ansible_facts.pkg_mgr in ["dpkg", "apt"] #or (ansible_os_family == "Debian")

Can I combine it in one task and how if it is possible? Because I need to register the output result and then use it onwards. Can’t figure it out.

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

>Solution :

An alternative solution is to use the package_facts module, like this:


- hosts: localhost
  tasks:
    - package_facts:

    - debug:
        msg: "Nginx is installed!"
      when: "'nginx' in packages"

But you could also register individual variables for your two tasks, and then combine the result:

- hosts: localhost
  tasks:
    - name: Veryfying nginx installation # RedHat
      command: "rpm -q nginx"
      when: ansible_facts.pkg_mgr in ["yum","dnf","rpm"] #or (ansible_os_family == "RedHat")
      failed_when: false
      register: rpm_check

    - name: Veryfying nginx installation # Debian
      command: "dpkg -l nginx"
      when: ansible_facts.pkg_mgr in ["dpkg", "apt"] #or (ansible_os_family == "Debian")
      failed_when: false
      register: dpkg_check

    - set_fact:
        nginx_result: >-
          {{
          (rpm_check is not skipped and rpm_check.rc == 0) or
          (dpkg_check is not skipped and dpkg_check.rc == 0)
          }}

    - debug:
        msg: "nginx is installed"
      when: nginx_result

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