Tes*_*Lau 64 variables username ansible ansible-playbook
我正在编写一个部署过程,该过程采用运行ansible脚本的用户名(例如tlau),并根据该用户名和当前日期/时间在远程系统上创建部署目录(例如tlau-deploy-2014-10 -15-16:52).
您可能认为这在ansible事实中可用(例如LOGNAME或SUDO_USER),但这些都设置为"root"或用于ssh到远程系统的部署ID.这些都不包含本地用户,即当前正在运行ansible进程的用户.
如何编写运行ansible进程的用户名并在我的playbook中使用它?
Ton*_*aro 92
如果您gather_facts(默认情况下为playbooks启用),则会设置一个被调用的内置变量,该变量ansible_user_id提供正在运行任务的用户名.然后,您可以在其他任务或模板中使用此变量{{ ansible_user_id }}.这将为您节省运行任务以注册该变量的步骤.
请参阅:http://docs.ansible.com/playbooks_variables.html#information-discovered-from-systems-facts
Ram*_*nte 59
如果你的意思是主机系统上的用户名,我想你可以运行一个本地操作:
- name: get the username running the deploy
become: false
local_action: command whoami
register: username_on_the_host
- debug: var=username_on_the_host
Run Code Online (Sandbox Code Playgroud)
在此示例中,whoami命令的输出在名为"username_on_the_host"的变量中注册,用户名将包含在username_on_the_host.stdout.
(此处不需要调试任务,它只是演示变量的内容)
sta*_*orx 37
我在所有模板中都添加了以下内容:
# Placed here by {{ lookup('env','USER') }} using Ansible, {{ ansible_date_time.date }}.
Run Code Online (Sandbox Code Playgroud)
模板化时显示为:
# Placed here by staylorx using Ansible, 2017-01-11.
Run Code Online (Sandbox Code Playgroud)
如果我使用{{ ansible_user_id }}并且我已成为root,那么该变量表示"root",而不是我想要的大部分时间.
tsh*_*lif 13
这似乎对我有用(ansible 2.9.12):
- name: get the non root remote user
set_fact:
remote_regular_user: "{{ ansible_env.SUDO_USER or ansible_user_id }}"
Run Code Online (Sandbox Code Playgroud)
您也可以简单地将其设置为变量 - 例如在您的group_vars/all.yml:
remote_regular_user: "{{ ansible_env.SUDO_USER or ansible_user_id }}"
Run Code Online (Sandbox Code Playgroud)
这将从远程系统读取用户名,因为不能保证本地和远程系统上的用户名相同。可以在 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 }}"
Run Code Online (Sandbox Code Playgroud)