include tasks from another role in ansible playbook

前端 未结 3 1240
我在风中等你
我在风中等你 2021-01-30 09:57

I\'m designing a kind of playbook lib with individual tasks

so in the usual roles repo, I have something like:

roles
├── common
│   └── tasks
│       ├──         


        
相关标签:
3条回答
  • 2021-01-30 10:33

    Using include_role: with option tasks_from is a good idea. However this still includes parts of the role. For example it loads role vars and meta dependencies. If apply is used to apply tags to an included file, then same tags are applied to meta dependencies. Also, the ansible output lists as the included role's name in its output, which is confusing.

    It is possible to dynamically locate a role and include a file using first_found. One can find the role path searching DEFAULT_ROLES_PATH and load a file from tasks folder. Ansible uses the same variable when sarching a role, so long as the role is in a path that Ansible can find, then the file will be loaded.

    This method is as dynamic as using include_role with option tasks_from

    Example:

    - name: Include my_tasks.yml from my_ansible_role
      include_tasks: "{{lookup('first_found', params)}}"
      vars:
        params:
          files: my_ansible_role/tasks/my_tasks.yml
          paths: "{{ lookup('config', 'DEFAULT_ROLES_PATH') }}"
    
    0 讨论(0)
  • 2021-01-30 10:45

    Yes, Ansible doesn't really like tasks as individual components. I think it wants you to use roles, but I can see why you wouldn't want to use roles for simple, reusable tasks.

    I currently see two possible solutions:

    1. Make those task-files into roles and use dependencies

    Then you could do something like this in e.g. custom_stuff_workflow

    dependencies:
      - { role: login }
    

    See: https://docs.ansible.com/playbooks_roles.html#role-dependencies

    2. Use include with "hardcoded" paths to the task files

    - include: ../../common/tasks/login.yml
    

    That worked pretty well in a short test playbook I just did. Keep in mind, you can also use parameters etc. in those includes.

    See: http://docs.ansible.com/ansible/latest/playbooks_reuse.html

    I hope I understood that question correctly and this helps.

    0 讨论(0)
  • 2021-01-30 10:56

    Just incase someone else bumps into this, version 2.2 of Ansible now has include_role.You can now do something like this.

    ---
    - name: do something
      include_role:
        name: common
        tasks_from: login
    

    Check out the documentation here.

    0 讨论(0)
提交回复
热议问题