2

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?

Community
  • 1
  • 1
jdoestackoverflow
  • 607
  • 1
  • 7
  • 15
  • 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 '16 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. – jdoestackoverflow Dec 23 '16 at 09:37

2 Answers2

4

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.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303
  • 1
    Note that this [doesn't](https://stackoverflow.com/a/24598849/3332686) correctly load template files. So `roles/foo/tasks/bar.yml` can't find its templates in `roles/foo/templates/baz.j2`. – proc Jun 20 '21 at 13:25
  • @proc Sure. Search path is somewhat mystical in Ansible. When you start heavily `include` / `import` it becomes difficult to understand: https://docs.ansible.com/ansible/latest/user_guide/playbook_pathing.html – gavenkoa Jun 23 '21 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.

Cedric Morent
  • 1,719
  • 1
  • 14
  • 25