3

How can I run a single task from an Ansible playbook and the handler that gets notified when that task completes successfully, while skipping all other tasks in the relevant playbook?

Currently I execute the following:

ansible-playbook --start-at-task "task1" --step -K -i hosts playbook.yml

and then press Ctrl+c after the task has finished. This will also skip the handler however.

I know I can add a tag to the task and use that, as in How to run only one task in ansible playbook?, but I would prefer being able to do this without adding a tag. Is that possible?

2
  • Can you elaborate exactly why you want to avoid adding a tag? Because one can think of several methods, but they all would be more cumbersome than adding a tag.
    – techraf
    Dec 22, 2016 at 13:21
  • 1
    Simply because it seems too cumbersome. Also, given that there is a direct option to skip previous tasks, it would seem to make sense for there to also be a direct option to skip later tasks. Based on the answers here this seems not to be the case however, so I'm tempted to accept the answer of Cedric Morent. Dec 23, 2016 at 9:37

2 Answers 2

5

It is possible to run a separate role (from roles/ dir):

ansible -i stage.yml -m include_role -a name=create-os-user localhost

and a separate task file:

ansible -i stage.yml -m include_tasks -a file=tasks/create-os-user.yml localhost

If you externalize tasks from role to root tasks/ directory (reuse is achieved by import_tasks: ../../../tasks/create-os-user.yml) you can run it independently from playbook/role.

2
  • 1
    Note that this doesn't correctly load template files. So roles/foo/tasks/bar.yml can't find its templates in roles/foo/templates/baz.j2.
    – proc
    Jun 20, 2021 at 13:25
  • @proc Sure. Search path is somewhat mystical in Ansible. When you start heavily include / import it becomes difficult to understand: docs.ansible.com/ansible/latest/user_guide/…
    – gavenkoa
    Jun 23, 2021 at 13:24
2

There's currently nothing coming with ansible-playbook to allow you to run a single task, like --task. Thus, to me, the tag along with the --tags option is your best solution here.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.