Search code examples
ansible

Installing multiple packages in Ansible


I have this task in Ansible:

- name: Install mongodb
  yum:
    name:
    - "mongodb-org-{{ mongodb_version }}"
    - "mongodb-org-server-{{ mongodb_version }}"
    - "mongodb-org-mongos-{{ mongodb_version }}"
    - "mongodb-org-shell-{{ mongodb_version }}"
    - "mongodb-org-tools-{{ mongodb_version }}"
    state: present
  notify: Restart mongodb

Is there a way I can indicate the version without having to use a loop like this? What is a more "elegant" way of writing this?

- name: Install mongodb
  yum:
    name: "{{ item }}-{{ mongodb_version }}"
    state: present
    loop:
    - mongodb-org-server
    - mongodb-org-mongos
    - mongodb-org-shell
    - mongodb-org-tools
  notify: Restart mongodb

Solution

  • 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