1

I currently have a bunch of roles, like:

  • apache2
  • gcc
  • gedit
  • ...etc.

For each of those, I have a task file that looks like this:

---
- name: "Install {{ role_name }}"
  become: true
  package:
    name: "{{ role_name }}"
    state: present

Is there a way to abstract this to a higher level and have a single "Install package" role, and then somehow specify a bunch of specific packages to install per host in a variable or something?

2 Answers 2

2

Is this what you're looking for?

- hosts: all
  vars:
    bunch_of_specific_packages:
      - apache2
      - gcc
      - gedit
  tasks:
    - package:
        name: "{{ item }}"
      loop: "{{ bunch_of_specific_packages }}"
3
  • I think that's close. I would need to restructure it slightly so that the "task" is part of an "install packages" role, and then include that role and a machine-specific list of packages in each top level playbook. However, I'm starting to rethink doing this at all, since it makes it harder to then, say, configure each package in a sensible way.
    – Ryan O.
    Apr 3, 2019 at 19:51
  • On second thought, it would save me a lot of work when the default install is all I need. I could then create full roles for packages that require configuration after installation.
    – Ryan O.
    Apr 3, 2019 at 20:18
  • Having some globally-available packages is handy, but for things you don't need everywhere just embed those package installs in the roles that need them. It might lead to some redundancy, but at least it will be clear which packages are needed by which roles.
    – chicks
    Apr 9, 2019 at 17:48
0

Another way to do this would be to set a role variable in your host_vars file called "role" and assign the role to install that way. You could also use the loop that Vladimir provided to install multiple roles.

tasks:
  - name: "Install Apache"
    become: true
    package:
      name: apache2
      state: latest
    when: role == "apache"

  - name: "Install GCC"
    become: true
    package:
      name: gcc
      state: latest
    when: role == "gcc"

You could also use tags to control what gets run in your play:

tasks:
  - name: "Install Apache"
    become: true
    package:
      name: apache2
      state: latest
    tags:
       - web
  - name: "Install GCC"
    become: true
    package:
      name: gcc
      state: latest
    tags:
       - gcc

And run your playbook setting the tags you require:

ansible-playbook example.yml --tags "web,gcc"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.