I'm setting up a server with Ansible and Docker. I'm currently learning both technologies, so please bear with me if I'm being overly stupid here.
In order to run run Docker commands, the user has to be in the docker user group. So I'm doing this:
- name: Ensure group "docker" exists
become: yes
group:
name: docker
state: present
- name: Add ansible user to docker group
become: yes
user:
name: "{{ansible_user}}"
groups: docker
append: yes
In a later play (but same playbook) I am then doing the following:
- name: build
command: docker-compose build --pull
args:
chdir: /docker
- name: start services
command: docker-compose -f docker-compose.yml up -d
args:
chdir: /docker
This never works on the first run. The "build" task always fails, complaining that it can't find docker (which is due to missing access rights). If I log in manually as the {{ansible_user}}
I can run docker just fine and if I wait long enough (so that Ansible will open a new SSH session, I presume) the playbook also works just fine, which leads me to believe that the {{ansible_user}}
hasn't picked up the new group yet due to Ansible re-using the SSH session for all tasks in the playbook.
So what should I do? I also tried
- name: build
become: yes
become_user: "{{ansible_user}}"
become_method: su
command: docker-compose build --pull
args:
chdir: /docker
so that ansible would enter a new session but this probably fails because I need to enter a password and I don't think there is a way to do that directly in a task.
Any ideas on how to solve this in a non-hacky way? I can't believe that this is such a rare use case that there is no standard way to solve this. Probably I'm just overlooking something.