Installing packages with Ansible

Installing packages with Ansible

Installing software packages using Ansible

Installing software packages with Ansible is easy. There are three Ansible modules that can help.

  • apt (Debian, Ubuntu, etc)
  • yum (Fedora, CentOS, etc)
  • package (Not OS Specific)

In this tutorial, we are going to go over using apt and package. If you are on a Fedora-based system you can follow along but keep in mind some of the syntax may be different.

APT Module

Inventory and Playbook for APT module

Here is our inventory file

 hosts
[servers]
node3 ansible_host=10.1.1.53

And our playbook with a single task:

 playbook-apt-install.yml
---
- name: Playbook to run apt install commands
  become: true
  hosts: all

  tasks:
  - name: ensure NMAP is installed.
    apt:
      name: nmap
      state: present
      update_cache: true

To summarize, our inventory file has a single server in it named node3 and our playbook is set to install the application "nmap".

Here are the key take aways on whats defined in the playbook under "apt"

  • name: This is the name of the package you want to control
  • state: The state the package can be in. absent, latest, present are the most commonly used options.
  • update_cache: This is "apt update", it updates your repository cache.

Running the Playbook

To run our playbook run the following command:

ansible-playbook playbook-copyfiles.yml -i hosts -K

And that's all! It will go out to all your servers in the inventory file and install your package.

Package Module

Switching to Package instead of using APT

To illustrate how similar the package module, here is a playbook using it. Notice that the only difference is we omitted the "update_cache" option.

 playbook-package-install.yml
---
- name: Playbook to run apt install commands
  become: true
  hosts: all

  tasks:
  - name: ensure NMAP is installed.
    package:
      name: nmap
      state: present

Going forward

Real world Scenario

In the real world, likely your playbooks will use both APT, YUM and PACKAGE modules. All you need to do is build some templating into your playbooks. Ansible can discover your operating system type and run the appropriate task for it.