Ansible:切换到用户并显示其名称

Ansible : Switch to a user and display its name

我的远程主机服务器下有两个用户:firas,michel

在我的剧本中,我连接为 "firas" 并尝试使用 "michel"[=36 执行一些任务=] 用户

(因此,为了断言,我试图显示每次 运行 任务的用户”)。

我的主机文件如下所示:

[myHost]
server1

[myHost:vars]
ansible_user=firas

我的任务如下:

- name: switch to user michel and run whoami
  shell: whoami
  remote_user: michel 
  register: username_michel 
  when:
    - ansible_host in groups['myHost']

- debug:
   msg: "user supposed to be michel is ; {{username_michel.stdout}}"
  when:
    - ansible_host in groups['myHost']

- name: switch to user firas and run whoami
  shell: whoami
  remote_user: firas
  register: username_firas
  when:
    - ansible_host in groups['myHost']

- debug:
   msg: "user supposed to be adi is ; {{username_firas.stdout}}"
  when:
    - ansible_host in groups['myHost']

-> 但奇怪的是,像这样:我总是获得用户 "firas" 作为活动用户

而且切换用户似乎不是 运行

有什么想法吗?

您在清单 ansible_user=firas 中定义的连接变量优先于任务中的 remote_user: michel 声明。删除它。

根据 Possible Misunderstanding 中的解释:

As documented http://docs.ansible.com/ansible/playbooks_variables.html#variable-precedence-where-should-i-put-a-variable, the connection variables have precedence over directives, this is done as host connection information is considered more 'specific' than play connection information. You can still override this from the play by setting the connection variable (as you would any variable).