Serial behaviour based on tags in an Ansible playbook

Viewed 58

I run a playbook, which contains a role, and executes so it runs once against the first server in the host file, it then executes against 25% of servers in the host file, finally, it executes against the rest of the servers.

What I want to achieve is:

  • If I run the playbook without any tags or task1, it should run against all servers in one go.
  • If I run the playbook with tags task2 it runs the playbook in batches (as per the serial).

At the moment, it will always run in batches regardless.

I have the following playbooks:

Playbook:

- hosts: all
  serial:
    - 1
    - "25%"
    - "100%"

  roles:
    - playbook2

playbook2 role:

- name: task 1
  shell: [do something]
  tags: task1

- name: task 2
  shell: [do more]
  tags: task2
1 Answers

You can template serial and omit it based on the content of the tags, and the special variable ansible_run_tags.

Your serial parameter, then should be

serial: "{{ ['1', '25%', '100%'] if 'task2' in ansible_run_tags else omit }}"

Given the playbook:

- hosts: _nodes
  gather_facts: no
  serial: "{{ ['1', '25%', '100%'] if 'task2' in ansible_run_tags else omit }}"

  tasks:
    - debug:
      tags:
        - task2

    - debug:
      tags:
        - task2

When run with no tags, on three hosts it will yield:

PLAY [_nodes] ***********************************************************

TASK [debug] ************************************************************
ok: [node2] => 
  msg: Hello world!
ok: [node3] => 
  msg: Hello world!
ok: [node1] => 
  msg: Hello world!

TASK [debug] ************************************************************
ok: [node2] => 
  msg: Hello world!
ok: [node3] => 
  msg: Hello world!
ok: [node1] => 
  msg: Hello world!

When run with --tags task2, it will, then, yield:

PLAY [_nodes] ***********************************************************

TASK [debug] ************************************************************
ok: [node2] => 
  msg: Hello world!

TASK [debug] ************************************************************
ok: [node2] => 
  msg: Hello world!

PLAY [_nodes] ***********************************************************

TASK [debug] ************************************************************
ok: [node3] => 
  msg: Hello world!

TASK [debug] ************************************************************
ok: [node3] => 
  msg: Hello world!

PLAY [_nodes] ***********************************************************

TASK [debug] ************************************************************
ok: [node1] => 
  msg: Hello world!

TASK [debug] ************************************************************
ok: [node1] => 
  msg: Hello world!
Related