Installing multiple packages in Ansible

To my surprise I didn't find the simplest solution in all the answers, so here it is. Referring to the question title Installing multiple packages in Ansible this is (using the yum module):

- name: Install MongoDB
  yum:
    name:
      - mongodb-org-server
      - mongodb-org-mongos
      - mongodb-org-shell
      - mongodb-org-tools 
    state: latest
    update_cache: true

Or with the apt module:

- name: Install MongoDB
  apt:
    pkg:
      - mongodb-org-server
      - mongodb-org-mongos
      - mongodb-org-shell
      - mongodb-org-tools 
    state: latest
    update_cache: true

Both modules support inline lists!

The second part of your question is how to integrate specific version numbers into the package lists. No problem - simply remove the state: latest (since using specific version numbers together with state: latest would raise errors) and add the version numbers to the package names using a preceding = like this:

- name: Install MongoDB
  yum:
    name:
      - mongodb-org-server=1:3.6.3-0centos1.1
      - mongodb-org-mongos=1:3.6.3-0centos1.1
      - mongodb-org-shell=1:3.6.3-0centos1.1
      - mongodb-org-tools=1:3.6.3-0centos1.1 
    update_cache: true

You could also optimize further and template the version numbers. In this case don't forget to add quotation marks :)


Make this into an Ansible Role called mongo, resulting in the directory structure:

playbook.yml
roles
|-- mongo
|  |-- defaults
|  |    |-- main.yml
|  |
|  |-- tasks
|  |    |-- main.yml
|  |
|  |-- handlers
|  |    |-- main.yml

Add the required MongoDB packages and version into the default variables file roles/mongo/defaults/main.yml:

mongo_version: 4.0
mongo_packages:
- mongodb-org-server
- mongodb-org-mongos
- mongodb-org-shell
- mongodb-org-tools

Re-write the task in the roles/mongo/tasks/main.yml file:

- name: Install mongodb
  yum:
    name: "{{ item }}-{{ mongo_version }}"
    state: present
  with_items: "{{ mongo_packages }}"
  notify: Restart mongodb

Add your handler logic to restart MongoDB in the file roles/mongo/handlers/main.yml.

Write a Playbook called playbook.yml that calls the role.

---
- hosts: all
  roles:
  - mongo

I think this is best way, but as the package names should not be hard coded, it is preferred to keep in vars/main.yml e.g

mongodb_version: 5
packages:
  - "mongodb-org-shell-{{ mongodb_version }}"
  - "mongodb-org-server-{{ mongodb_version }}"

Call this inside your playbook as

- name: Install mongodb packages
  yum: name={{ item }}
       state=latest
  with_items: "{{ packages}}"

Tags:

Ansible