将角色包括在角色中?

是否可以在角色中重用角色?我的意思不是通过在一个角色的 meta/main.yml 文件中定义一个依赖项,而是通过 包括直接在任务/main.yml 中定义另一个角色的角色?

例如,我在角色手册中定义了几个基本角色,在角色中定义了一些更高级的角色。 我希望高级别的角色除了一些特定的任务之外还包括一些基本的角色。

playbooks/


rolebooks/
some_role/
      

roles/
webtier/
tasks/
main.yml

在剧本/角色/网络/任务/main.yml 中:

    - shell: echo 'hello'
- { role: rolebooks/some_role }
- shell: echo 'still busy'

谢谢

63574 次浏览

AFAIK, you can't. This is what dependencies are for.

If you want to avoid dependencies (because, for instance, you want 'role X' to run between two tasks), you can do this in the playbook itself if you think the tasks are related :

roles/webtier/tasks/main.yml:

- shell: echo 'hello'
- include: webtier.yml
- shell: echo 'role done'

All in all, it depends on what you're trying to do exactly. But in your example, 'still busy' seems to imply that the rolebooks/some_role is still running, which is not possible (there is no concurrency here).

Obviously, you can also sequence roles in a master playbook (which is probably what you do already) :

- name: Polite foo stuff
hosts: foo_hosts
roles:
- say_hello
- rolebooks/some_role
- say_bye


- name: Unpolite foo stuff
hosts: !foo_hosts
roles:
- rolebooks/some_role

You can't, but you can do something kind of similar.

For a layout of:

roles/
...
common/tasks/main.yml
nginx/tasks/main.yml
...

In nginx/tasks/main.yml, you can call your common task:

- name: Call the 'common' role to do some general setup
include: ../../common/tasks/main.yml

Note that because you're not using the typical import structure, you might run into some "weirdness" like role default variables not being accessible unless you included the role in the standard fashion earlier.

Old question BUT for the record: use Ansible 2.2+ and you're good to go with include_role. Exactly for this very purpose... see documentation here.

Check out import_role as well... see documentation here