Search code examples
ansibleansible-role

Run a subtask of a role in an Ansible playbook breaks relative paths


I am looking for a way to run a role, or a part of a role included in a playbook, from the root of my project.

What I need it to be able to run a part of a role, as a playbook, so that I don't need to run something like (see example below):

ansible-playbook roles/role1/tasks/upgrade.yml

However, I have a hard time figuring out how to fix the problem of the relative paths.

The problem is that if I have nested includes, the path to vars, templates, etc is not correct anymore if I run a part of the role in a playbook, or if I run the role itself.

.
+-- plb_run_role1.yml
+-- plb_upgrade.yml
+-- roles
    +-- role1
        +-- tasks
        |   +-- main.yml
        |   +-- task1.yml
        |   +-- upgrade.yml
        +-- templates
        |   +-- a-template.j2
        +-- vars
            +-- ftp-credentials.yml

Playbook to run the full role1 role. plb_run_role1.yml:

#!/usr/bin/env ansible-playbook

---

- hosts: appservers
  roles:
    - role: role1

Playbook to run just a task of the role1 role. plb_upgrade.yml:

#!/usr/bin/env ansible-playbook

---

- import_playbook: roles/role1/tasks/upgrade.yml

roles/role1/tasks/main.yml:

---

- include_tasks: task1.yml    

The task which is called by the role, but can be also called 'stand-alone'
roles/role1/tasks/task1.yml

    ---             

    - include_vars: ../vars/some-vars.yml           => If I call   ./plb_upgrade.yml                
    - include_vars: some-vars.yml       => If I call   ./plb_run_role1.yml            

    - name: copy the user profile update script
      template:
        src: ../templates/a-template.j2   => If I call   ./plb_upgrade.yml                
        src: a-template.j2   => If I call   ./plb_run_role1.yml            
        dest: '/etc/a-template'

roles/role1/tasks/upgrade.yml:

---

- include_tasks: set_iptables.yml

Is there a way to run a role, of part of a role and have the path correctly resolved?


Solution

  • There is a very simple way to run a part of a role (ansible 2.4+).

    import_role task can execute a specific tasklist from a role:

    - name: Run foo from role bar
      import_role:
        name: bar
        tasks_from: foo
    

    The role 'bar' should have 'tasks/foo.yaml' to be executed.

    See more details in the import_role description: https://docs.ansible.com/ansible/2.4/import_role_module.html