How to run only one task in ansible playbook?

You should use tags: as documented in https://docs.ansible.com/ansible/latest/user_guide/playbooks_tags.html


If you have a large playbook it may become useful to be able to run a specific part of the configuration without running the whole playbook.

Both plays and tasks support a “tags:” attribute for this reason.

Example:

tasks:

    - yum: name={{ item }} state=installed
      with_items:
         - httpd
         - memcached
      tags:
         - packages

    - template: src=templates/src.j2 dest=/etc/foo.conf
      tags:
         - configuration

If you wanted to just run the “configuration” and “packages” part of a very long playbook, you could do this:

ansible-playbook example.yml --tags "configuration,packages"

On the other hand, if you want to run a playbook without certain tasks, you could do this:

ansible-playbook example.yml --skip-tags "notification"

You may also apply tags to roles:

roles:
  - { role: webserver, port: 5000, tags: [ 'web', 'foo' ] }

And you may also tag basic include statements:

- include: foo.yml tags=web,foo

Both of these have the function of tagging every single task inside the include statement.


FWIW with Ansible 2.2 one can use include_role:

playbook test.yml:

- name: test
  hosts:
    - 127.0.0.1
  connection: local
  tasks:
    - include_role:
        name: test
        tasks_from: other

then in roles/test/tasks/other.yml:

- name: say something else
  shell: echo "I'm the other guy"

And invoke the playbook with: ansible-playbook test.yml to get:

TASK [test : say something else] *************
changed: [127.0.0.1]

There is a way, although not very elegant:

  1. ansible-playbook roles/hadoop_primary/tasks/hadoop_master.yml --step --start-at-task='start hadoop jobtracker services'
  2. You will get a prompt: Perform task: start hadoop jobtracker services (y/n/c)
  3. Answer y
  4. You will get a next prompt, press Ctrl-C

Tags:

Ansible