Ansible Task – Running One Task from Role

ansibleansible-playbook

I tried to run playbook with role and only few task from it.
F.e.
I have playbook

# setup.yaml

- hosts: all
  tasks:
    - include_role:
        name: system
      tags: setup

and role "system" with tasks:

# roles/system/tasks/main.yaml

- name: Test ping
  import_tasks: ping.yaml
  tags: test
- name: Create ansible user
  import_tasks: create_user_ansible.yaml
  tags: setup
====================================================
# roles/system/tasks/ping.yaml   
                                                                                                            
- name: test_ping
  ping: 
====================================================
# roles/system/tasks/create_user_ansible.yaml  
                                                                                              
- name: Creating ansible user
  tags: setup
  user:
    name: ansible
    password: '<hash>'
    groups: adm
    state: present
    shell: /bin/bash
    system: no
    createhome: yes
    home: /home/ansible

When I run command

ansible-playbook -i inventories/setup setup.yaml

both of tasks (ping.yaml and create_user_ansible.yaml) running
But when I run

ansible-playbook -i inventories/setup setup.yaml --tags setup

it works, like I need.

So, my question:

Is this that behavior, that Ansible developers design, or I made mistake in my playbook, and there are some way, to run only few tasks from role without using --tags in command line?

Best Answer

This is the default behavior of Ansible. As shown in the documentation:

By default, Ansible runs as if --tags all had been specified.

If you want a play to not run when you didn't specify any tags, you can add the special tag never to it. Again an example from the docs:

Another special tag is never, which will prevent a task from running unless a tag is specifically requested.

Example:

tasks:
  - debug: msg="{{ showmevar }}"
    tags: [ never, debug ]

In this example, the task will only run when the debug or never tag is explicitly requested.