在ansible中,如何获取运行ansible的用户名的变量?

时间:2014-10-15 23:56:47

标签: variables username ansible ansible-playbook

我正在编写一个部署过程,该过程采用运行ansible脚本的用户名(例如tlau),并根据该用户名和当前日期/时间在远程系统上创建部署目录(例如tlau-deploy- 2014-10-15-16:52)

您会认为这在ansible事实中可用(例如LOGNAME或SUDO_USER),但这些都设置为“root”或用于ssh到远程系统的部署ID。这些都不包含本地用户,即当前正在运行ansible进程的用户。

如何编写运行ansible进程的用户名并在我的playbook中使用它?

6 个答案:

答案 0 :(得分:75)

如果gather_facts(默认情况下为playbooks启用),则会有一个名为ansible_user_id的内置变量,它提供正在运行任务的用户名。然后,您可以在{{ ansible_user_id }}的其他任务或模板中使用此变量。这将为您节省运行任务以注册该变量的步骤。

请参阅:http://docs.ansible.com/playbooks_variables.html#information-discovered-from-systems-facts

答案 1 :(得分:55)

如果您指的是主机系统上的用户名,我想您可以运行本地操作:

- name: get the username running the deploy
  become: false
  local_action: command whoami
  register: username_on_the_host

- debug: var=username_on_the_host

在此示例中,whoami命令的输出在名为" username_on_the_host"的变量中注册,用户名将包含在username_on_the_host.stdout中。

(此处不需要调试任务,它只是演示变量的内容)

答案 2 :(得分:30)

我在所有模板中都添加了以下内容:

# Placed here by {{ lookup('env','USER') }} using Ansible, {{ ansible_date_time.date }}.

当模板化时显示为:

# Placed here by staylorx using Ansible, 2017-01-11.

如果我使用{{ ansible_user_id }}并且我已成为root,那么该变量表示“root”,而不是我想要的大部分时间。

答案 3 :(得分:0)

这将从远程系统中读取用户名,因为不能保证本地和远程系统上的用户名相同。可以在SSH配置中更改名称。

- name: Run whoami without become.
  command: whoami
  changed_when: false
  become: false
  register: whoami

- name: Set a fact with the user name.
  set_fact:
    login_user: "{{ whoami.stdout }}"

答案 4 :(得分:0)

如果您想让在 ansible 塔中运行模板的用户,您可以在您的剧本中使用此 var {{tower_user_name}},但它仅在手动执行时定义

tower_user_name :启动此作业的 Tower 用户的用户名。这不适用于回调或计划作业。

检查此文档 https://docs.ansible.com/ansible-tower/latest/html/userguide/job_templates.html

答案 5 :(得分:0)

这似乎对我有用(ansible 2.9.12):

- name: get the non root remote user
  set_fact:
    remote_regular_user: "{{ ansible_env.SUDO_USER or ansible_user_id }}"

您也可以简单地将其设置为变量 - 例如在您的group_vars/all.yml中:

remote_regular_user: "{{ ansible_env.SUDO_USER or ansible_user_id }}"