Create and use group without restart

Solution 1:

You can use an (ansible.builtin.)meta: reset_connection task:

- name: add user to docker group
  ansible.builtin.user:
    name: USERNAME
    groups: docker
    append: yes
- name: reset ssh connection to allow user changes to affect ansible user
  ansible.builtin.meta:
    reset_connection

Note that you can not use a variable to only run the task when the ansible.builtin.user task did a change as “reset_connection task does not support when conditional”, see #27565.

The reset_connection meta task was added in Ansible 2.3, but remained a bit buggy until excluding v2.5.8, see #27520.

Solution 2:

For Ansible 2 I created a Galaxy role: https://galaxy.ansible.com/udondan/ssh-reconnect/

Usage:

- name: add user to docker group
  user: name=USERNAME groups=docker append=yes
  sudo: true
  notify:
    - Kill all ssh connections

If you immediately need the new group you can either call the module yourself:

- name: Kill own ssh connections
  ssh-reconnect: all=True

Or alternatively fire the handlers when required

- meta: flush_handlers

For Ansible < 1.9 see this answer:

Do you use ssh control sockets? If you have ControlMaster activated in your ssh config, this would explain the behavior. Ansible re-connects for every task, so the user should have the correct role assigned on the next task. Though when you use ssh session sharing, Ansible would of course re-use the open ssh connection and therefore result in not logging in again.

You can deactivate the session sharing in your ansible.cfg:

[ssh_connection]
ssh_args= -S "none"

Since session sharing is a good thing to speed up Ansible plays, there is an alternative. Run a task which kills all ssh connections for your current user.

- name: add user to docker group
  user: name=USERNAME groups=docker append=yes
  sudo: true
  register: user_task

- name: Kill open ssh sessions
  shell: "ps -ef | grep sshd | grep `whoami` | awk '{print \"kill -9\", $2}' | sh"
  when: user_task | changed
  failed_when: false

This will force Ansible to re-login at the next task.