user855443
user855443

Reputation: 2948

ansible - how to put a simple role into a single file (at least for documentation)

I break my playbooks in roles which can be used for different setups. most of these roles are quite simple (few lines in tasks, perhaps a variable or a template).

I would prefer to have a role in a single file or at least print as a single file. The current distribution for roles into many files (not all are empty by default) makes documentation difficult.

I tried to insert a file exampleRole.yml with a single task (playbook-like) in roles but it is ignored when I execute the playbook with it without an error message.

--- 
tasks:
  - name: print to stdout
    action: command echo "hello"

How to write a role in a single file? Or at least a suggestion how to print a role in a single file for better documentation?

I like ansible and roles are helpful - but how to document them? To write good read-me files is not an option, as documentatin separated from code is always out-of-date!

Upvotes: 1

Views: 1505

Answers (2)

Vladimir Botka
Vladimir Botka

Reputation: 68344

Q: "How to write a role in a single file?"

A: ansible-playbook does not check the structure of a role. A single task works fine. For example

shell> tree roles/minimal/
roles/minimal/
└── tasks
    └── main.yml

1 directory, 1 file
shell> cat roles/minimal/tasks/main.yml 
- debug:
    msg: Hello
shell> cat pb.yml
- hosts: localhost
  roles:
    - minimal

give (abridged)

shell> ansible-playbook pb.yml
   ...
ok: [localhost] => 
  msg: Hello

ansible-playbook will not complain if the role is an empty directory. There are other restrictions e.g. ansible-galaxy. As as hint, see roles directory inside collections.

Upvotes: 3

Jiří Baum
Jiří Baum

Reputation: 6940

You can't; Ansible requires that each role have the directory structure.

You can, however, write a task list in a single file (without subdirectories), then include it using include_tasks. This can be done either in the playbook or within a role, letting you organise the tasks without setting up a whole new role.

You can also then apply a when clause to the include_tasks (rather than to each individual task), or use a Jinja substitution for the filename, like include_tasks: "name_{{ ansible_facts.os_family | lower }}.yml"

Upvotes: 4

Related Questions