Ansible systemctl --user 对于另一个用户

Ansible systemctl --user for another user

我正在以非特权用户 ansible 的身份登录另一台计算机,我想让 ansible 为用户 bob 启用 systemd 用户服务。

没有ansible,解决方案是ssh bob@machine然后是systemctl --user enable service

但是,使用ansible,有两个问题:

  1. 如果已经作为另一个非特权用户(ansible)登录,较新版本的 ansible 将拒绝成为非特权用户 bob。
  2. 即使这有效,dbus 也不会启动并且 systemctl 将无法与 systemd 通信(如果我理解正确的话)。

一个非常丑陋的解决方法是执行 shell 命令,让远程主机以 bob 身份通过 ssh 连接到它自己,然后 运行 在那里使用 systemctl raw 命令。

有没有更好的方法来完成这项工作?

两种方案都可行。

1) remote_user: 鲍勃

- hosts: test_01
  become: no
  remote_user: admin
  tasks:
    - command: whoami
      register: result
    - debug:
        var: result.stdout
    - command: whoami
      remote_user: bob
      register: result
    - debug:
        var: result.stdout

给出:

"result.stdout": "admin"
"result.stdout": "bob"

2) pipelining = true 引用自 Becoming an Unprivileged User

Use pipelining. When pipelining is enabled, Ansible doesn’t save the module to a temporary file on the client. Instead it pipes the module to the remote python interpreter’s stdin. Pipelining does not work for python modules involving file transfer (for example: copy, fetch, template), or for non-python modules.

- hosts: test_01
  become: no
  remote_user: admin
  tasks:
    - command: whoami
      register: result
    - debug:
        var: result.stdout
    - command: whoami
      become_user: bob
      become_method: sudo
      become: yes
      register: result
    - debug:
        var: result.stdout

给予

"result.stdout": "admin"
"result.stdout": "bob"

$ grep pipe ansible.cfg 
pipelining = true