From d0acd84ef8d9c731e303e7587886546ea664956e Mon Sep 17 00:00:00 2001
From: Mark Goddard <mark@stackhpc.com>
Date: Sun, 6 Aug 2017 17:46:18 +0000
Subject: [PATCH] Fix issue with adding user to docker group

In order to activate the group membership for the user it is necessary
to log out and back in again. Ansible typically uses the SSH Control
Persist feature which will keep the user logged in between successive
tasks. This change stops the control persist connection when the user
has been added to the docker group.

The method for determining the path to the control socket is a little
more hard coded than it should be, but no other method could be found
for determining the socket's path.
---
 ansible/roles/docker/tasks/main.yml | 21 ++++++++++++++++++++-
 1 file changed, 20 insertions(+), 1 deletion(-)

diff --git a/ansible/roles/docker/tasks/main.yml b/ansible/roles/docker/tasks/main.yml
index 6892c8a26..f9413ad5b 100644
--- a/ansible/roles/docker/tasks/main.yml
+++ b/ansible/roles/docker/tasks/main.yml
@@ -4,8 +4,28 @@
     name: "{{ ansible_user_id }}"
     groups: docker
     append: yes
+  register: group_result
   become: True
 
+# After adding the user to the docker group, we need to log out and in again to
+# pick up the group membership. We do this by removing the SSH ControlPersist
+# connection.
+- name: Drop the persistent SSH connection to activate the new group membership
+  local_action:
+    module: shell ssh -O stop {{ cp_hostname }} -o ControlPath={{ cp_path }}
+  register: socket_removal
+  failed_when:
+    - socket_removal|failed
+    - "'No such file or directory' not in socket_removal.stderr"
+  with_items: "{{ play_hosts }}"
+  run_once: True
+  when: group_result|changed
+  vars:
+    cp_hostname: "{{ hostvars[item].ansible_host|default(inventory_hostname) }}"
+    cp_username: "{{ hostvars[item].ansible_user }}"
+    cp_port: "{{ hostvars[item].ansible_ssh_port|default('22') }}"
+    cp_path: "~/.ansible/cp/ansible-ssh-{{ cp_hostname }}-{{ cp_port }}-{{ cp_username }}"
+
 - name: Ensure Docker daemon is started
   service:
     name: docker
@@ -16,7 +36,6 @@
   command: docker info
   register: docker_info
   changed_when: False
-  become: True
 
 - name: Fail when loopback-mode containers or images exist
   fail: