Ansible playbook to install software fails if already present

  • 1 year ago
Comment

1 / 1

To create an Ansible playbook that installs software only if it's not already present, you can use the when conditionals to check whether the software is already installed. Here's an example playbook that installs the nginx package on an Ubuntu server only if it's not already installed:

yaml
---
- name: Install Nginx web server
hosts: web_servers
become: true
vars:
package_name: nginx
tasks:
- name: Check if Nginx is already installed
command: dpkg-query -W -f='${Status}' {{ package_name }} | grep -q 'ok installed'
register: nginx_installed
ignore_errors: true

- name: Install Nginx package if not already installed
apt:
name: "{{ package_name }}"
state: present
when: nginx_installed.rc != 0

In the above playbook, we define the package_name variable to store the name of the package we want to install. The dpkg-query command is used to check whether Nginx is already installed by querying the Debian package database. The result is stored in the nginx_installed variable, which we check in the when conditional of the apt task.

If nginx_installed.rc != 0 (meaning that the package is not already installed), the apt task installs the nginx package.

You can modify this playbook to install other packages or software using the appropriate package manager and commands for your target platform. The when conditional can be used to check for the presence of the package using the appropriate command or query for the package manager.

With this playbook, you can ensure that software is only installed if it's not already present on the target system.