Home > Software design >  How do I combine two commands in one task? | Ansible
How do I combine two commands in one task? | Ansible

Time:09-24

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.

CodePudding user response:

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

  • Related