12

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.

MadMonkey
  • 275
  • 2
  • 7

2 Answers2

19

I am not certain if it will work for you, but I suggest you try adding a reset_connection.

- name: reset ssh connection
  meta: reset_connection

There is an example here.

You may want to add this as a handler, and notify it from your user/group modification tasks. Then also add a meta: flush_handlers so the connection would only be reset if required.

Zoredache
  • 128,755
  • 40
  • 271
  • 413
0

I used the meta: reset_connection, but it not work for me.

So I use the su -c comamnd, I test it works:


- name: perform docker login for ansible_ssh_user
  shell: |
    su -c ' docker login xxx:5000 -u xxxx -p xxxxx ' {{ ansible_ssh_user }}
  # become: yes
  # become_user: "{{ ansible_ssh_user }}"
  when: 
    # if use ansible_connection=local, the var ansible_ssh_user will not defined
    - ansible_connection != 'local'
    - ansible_ssh_user is defined
    - ansible_ssh_user != 'root'
张馆长
  • 101
  • 2