Ansible 运行 delegate_to 远程机器上不同用户的任务

Ansible run delegate_to task on remote machine as different user

我想在远程主机上设置一个 cron 条目,但以不同的用户身份连接到主机。

# task
- name: Cron to ls at a specific time
  cron:
    name: "perform a listing"
    weekday: "6"
    minute: "5"
    hour: "3"
    job: "/bin/ls -lR /mnt/*/"
  delegate_to: "{{ my_remote_machine }}"

问题 这是云中实例的启动脚本。
该脚本以 root 身份运行,因此将尝试以 root 身份连接到 {{ my_remote_machine }}
root 在大多数云实例上显然默认禁用。
因此,我无法使用 become_user 关键字。

我还有其他选择吗?

只需将给定任务的 remote_user 更改为您可以在委派主机上连接的任务。这是一个伪剧本,可以为您提供基础知识。

注意:如果使用 ansible_connection: local 定位主机(例如默认隐式 localhost),remote_user 将被忽略并默认为用户在控制器上启动剧本。

---
- name: Play mixing several hosts and users
  hosts: some_host_or_group
  # Play level remote_user. In short, this is used if not overridden in task.
  # See documentation for finer grained info (define in inventory, etc...)
  remote_user: root  

  tasks:
    - name: Check who we are on current host
      command: id -a
      register: who_we_are_current
    - debug:
        var: who_we_are_current.stdout

    - name: Show we can be someone else on delegate
      command: id -a
      # Task level remote_user: overrides play
      remote_user: johnd
      delegate_to: "{{ my_remote_machine }}"
      register: who_whe_are_delegate
    - debug:
        var: who_whe_are_delegate.stdout

    - name: And of course, this works with your real task as well
      cron:
        name: "perform a listing"
        weekday: "6"
        minute: "5"
        hour: "3"
        job: "/bin/ls -lR /mnt/*/"
      remote_user: johnd
      delegate_to: "{{ my_remote_machine }}"