-name:"add group: 'docker'" group: name:docker state:present -name:addingexistingusertogroupdocker user: name:'{{ item }}' groups:docker append:yes with_items: -root -"{{ ansible_ssh_user | default('root') }}" # if use ansible_connection=local, the var ansible_ssh_user will not defined when:ansible_ssh_userisdefined ... 启动docker
-name:performdockerlogin environment: PATH:"{{ bin_dir }}:{{ ansible_env.PATH }}" shell:dockerlogin {{ REGISTRY_DOMAIN }}:{{REGISTRY_PORT}}-uxxx-pxxx # 非 root 执行-u xxx -b --become-method=sudo 的时候 登录 -name:performdockerloginforansible_ssh_user shell:dockerlogin {{ REGISTRY_DOMAIN }}:{{REGISTRY_PORT}}-uxxx-pxxx become:yes become_user:"{{ ansible_ssh_user }}" when: # if use ansible_connection=local, the var ansible_ssh_user will not defined -ansible_ssh_userisdefined -ansible_ssh_user!='root'
但是执行完测试同学在非 root 用户 docker pull 报错没权限
解决过程
查看了下执行日志,并没有执行 perform docker login for ansible_ssh_user。找个干净环境单独执行下面 task 调试:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
-hosts: -all tasks: -name:test shell:dockerlogin {{ REGISTRY_DOMAIN }}:{{REGISTRY_PORT}}-uxxx-pxxx when: # if use ansible_connection=local, the var ansible_ssh_user will not defined -ansible_ssh_userisdefined -ansible_ssh_user!='root' -name:test2 shell:dockerlogin {{ REGISTRY_DOMAIN }}:{{REGISTRY_PORT}}-uxxx-pxxx become:yes become_user:"{{ ansible_ssh_user }}" when: # if use ansible_connection=local, the var ansible_ssh_user will not defined -ansible_ssh_userisdefined -ansible_ssh_user!='root'
$ id uid=1000(xxx) gid=1000(xxx) groups=1000(xxx),1001(docker)
最后改了下前面加下 id 命令调试看出眉目:
1 2 3 4 5 6 7 8 9 10
... -name:test2 shell:| id;dockerlogin {{ REGISTRY_DOMAIN }}:{{REGISTRY_PORT}}-uxxx-pxxx become:yes become_user:"{{ ansible_ssh_user }}" when: # if use ansible_connection=local, the var ansible_ssh_user will not defined -ansible_ssh_userisdefined -ansible_ssh_user!='root'
突然意识到是 ansible 配置的 ssh 会话持久导致的,删掉会话持久的文件路径后是可以的,但是这样不人性化。搜了下 ansible reload user group 找到了有个老哥和我一样的问题,但是里面的:
1 2
-name:resetsshconnection meta:reset_connection
执行会报错:
1
[WARNING]: Reset is not implemented for this connection
后面自己解决了该问题,使用 su -c 不使用 become ,同时发现偶尔 ansible_ssh_user 莫名奇妙会消失,在之前就 set_facts 下 ansible_ssh_user 到另一个变量 HOST_USER (下面代码没改,如果遇到了就提前自行 set_facts 下):
1 2 3 4 5 6 7
-name:test2 shell:| su -c 'docker login {{ REGISTRY_DOMAIN }}:{{ REGISTRY_PORT }} -u xxx -p xxx' ansible_ssh_user when: # if use ansible_connection=local, the var ansible_ssh_user will not defined - ansible_ssh_user is defined - ansible_ssh_user != 'root'