Ansible remote_user 对比 ansible_user

Ansible remote_user vs ansible_user

问题很简单:Ansible中的ansible_user(之前的ansible_ssh_user)和remote_user有什么区别,除了第一个是if配置文件设置的,而后者是一个是在戏剧/角色中设置的?它们与 -u / --user 命令行选项有什么关系?

他们似乎是一样的。看这里:

https://github.com/ansible/ansible/blob/c600ab81ee/lib/ansible/playbook/play_context.py#L46-L55

# the magic variable mapping dictionary below is used to translate
# host/inventory variables to fields in the PlayContext
# object. The dictionary values are tuples, to account for aliases
# in variable names.

MAGIC_VARIABLE_MAPPING = dict(
   connection       = ('ansible_connection',),
   remote_addr      = ('ansible_ssh_host', 'ansible_host'),
   remote_user      = ('ansible_ssh_user', 'ansible_user'),
   port             = ('ansible_ssh_port', 'ansible_port'),

此外,当我们想在ansible主机文件中指定默认SSH用户时使用ansible_user,而[=29=中使用remote_user ]剧本上下文。

来自https://github.com/ansible/ansible/blob/c600ab81ee/docsite/rst/intro_inventory.rst

ansible_user The default ssh user name to use.

这是在 ansible hosts 文件中使用 ansible_user 的示例:

[targets]

localhost              ansible_connection=local
other1.example.com     ansible_connection=ssh        ansible_user=mpdehaan
other2.example.com     ansible_connection=ssh        ansible_user=mdehaan

remote_user和ansible_user的一个区别:
当您 运行 角色与剧本中的不同用户时,例如:

- name: Apply user configuration to user root 
  hosts: all
  remote_user: root
- name: Apply user configuration to user murphy
  hosts: all
  remote_user: murphy

然后您可以使用 "when: ansible_user == .." 而不是 "when: remote_user == .." 为不同的用户执行条件任务。例如:

- name: Add user murphy to wheel group
  user:
    name: murphy
    groups: wheel
    append: yes
  when: ansible_user == "root"