我正在编写一个部署过程,该过程采用运行ansible脚本的用户名(例如tlau),并根据该用户名和当前日期/时间在远程系统上创建部署目录(例如tlau-deploy-2014-10 -15-16:52) .
您会认为这在ansible事实中可用(例如LOGNAME或SUDO_USER),但这些都设置为“root”或用于ssh到远程系统的部署ID . 这些都不包含本地用户,即当前正在运行ansible进程的用户 .
如何编写运行ansible进程的用户名并在我的playbook中使用它?
如果你的意思是主机系统上的用户名,我想你可以运行一个本地操作:
- 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 中 .
whoami
username_on_the_host.stdout
(此处不需要调试任务,它只是演示变量的内容)
如果 gather_facts (默认情况下为playbooks启用),则会设置一个名为 ansible_user_id 的内置变量,该变量提供正在运行任务的用户名 . 然后,您可以在其他任务或模板中使用此变量 {{ ansible_user_id }} . 这将为您节省运行任务以注册该变量的步骤 .
gather_facts
ansible_user_id
{{ ansible_user_id }}
见:http://docs.ansible.com/playbooks_variables.html#information-discovered-from-systems-facts
我在所有模板中都添加了以下内容:
# 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 回答
如果你的意思是主机系统上的用户名,我想你可以运行一个本地操作:
在此示例中,
whoami
命令的输出在名为"username_on_the_host"的变量中注册,用户名将包含在username_on_the_host.stdout
中 .(此处不需要调试任务,它只是演示变量的内容)
如果
gather_facts
(默认情况下为playbooks启用),则会设置一个名为ansible_user_id
的内置变量,该变量提供正在运行任务的用户名 . 然后,您可以在其他任务或模板中使用此变量{{ ansible_user_id }}
. 这将为您节省运行任务以注册该变量的步骤 .见:http://docs.ansible.com/playbooks_variables.html#information-discovered-from-systems-facts
我在所有模板中都添加了以下内容:
模板化时显示为:
如果我使用
{{ ansible_user_id }}
并且我已成为root,那么该变量表示"root",而不是我想要的大部分时间 .