Ansible Tasks – How to Share Directives in a File

ansible

How can I set directives shared between all tasks in the file, in an Ansible playbook fragment file that only contains tasks?

# ansible/inventory/roles/os_packages/tasks/main.yaml

- name: "APT: Update available packages from Debian repositories"
  gather_facts: false
  become: true
  become_user: root
  apt:
    update_cache: true
- name: "APT: Install required packages"
  gather_facts: false
  become: true
  become_user: root
  apt:
    name:
      - foo
      - bar

Those repeated directives — gather_facts, become, etc. — should be stated one time in that file. But where, since there is (currently?) no file representing the role or play?

# ansible/inventory/roles/os_packages/tasks/main.yaml

# This doesn't work because Ansible is expecting only tasks.
gather_facts: false
become: true
become_user: root

- name: "APT: Update available packages from Debian repositories"
  apt:
    update_cache: true
- name: "APT: Install required packages"
  apt:
    name:
      - foo
      - bar

The file needs to consist only of a sequence of tasks; the “role” level or “play” level don't appear to have an appropriate place in this recommended directory structure.

If the entire playbook was in one file, each play would have its own separate name and I'd set the directives on the play. But these tasks files are being gathered and compiled, and there's no place where the play exists for me to write those directives.

Where should the directives that apply to all tasks in a role get defined?

Best Answer

gather_facts is not meaningful (or possible) to set for anything other than a play, because it only affects the play-level decision of whether to gather facts.

become and become_user are valid block- or task-level keywords, so you can use a block to apply them to a list of tasks (within a role or otherwise):

- become: true
  become_user: root
  block:
    - name: "APT: Update available packages from Debian repositories"
      apt:
        update_cache: true
    - name: "APT: Install required packages"
      apt:
        name:
          - foo
          - bar

Many keywords can also be applied when calling roles:

- hosts: all
  roles:
    - name: foo
      become: true
  tasks:
    - import_role:
        name: bar
      become: true

    - include_role:
        name: baz
        apply:
          become: true