joesan
joesan

Reputation: 15435

Ansible Run Shell Command Upon Condition in Multiple Hosts

I have the following script that attempts to install a package on a node only when not already installed.

- name: check if linux-modules-extra-raspi is installed # Task 1
  package:
    name: linux-modules-extra-raspi
    state: present
  check_mode: true
  register: check_raspi_module

- name: install linux-modules-extra-raspi if not installed # Task 2
  shell: |
    sudo dpkg --configure -a
    apt install linux-modules-extra-raspi
  when: not check_raspi_module.changed

But the problem here is that if I have a set of hosts, the Task 1 runs for node n1 and registeres check_raspi_module to false and then Task 1 runs for node n2 and then sets it to true because that package is already available in node n2. So how can I throttle this and have the check_raspi_module local to a task and not global like it is now?

Upvotes: 0

Views: 110

Answers (1)

Skull
Skull

Reputation: 117

If you need to install package, you have just to use the first bloc like below. You haven't need to use block of check and install separatly.

Even if your package is installed, Ansible will detect it and not reinstall it. It’s the principe of Ansible The documentation: here

(definition) state: present (mean install if not present)

- name: install if not present if linux-modules-extra-raspi
  ansible.builtin.package:
    name: linux-modules-extra-raspi
    state: present

Upvotes: 1

Related Questions