将其放入group_vars/all
:
default_environment:
HOME2: "{{ ansible_env.HOME }}"
在任务中使用来定义环境时:
environment:
"{{ default_environment }}"
我明白了:
The field 'environment' has an invalid value, which includes an undefined variable. The error was: {u'HOME2': u'{{ ansible_env.HOME }}'}: 'ansible_env' is undefined
exception type: <class 'ansible.errors.AnsibleUndefinedVariable'>
有没有办法根据当前的远程环境变量定义组变量,在这种情况下为$HOME
?
编辑:每个请求,可重现的案例:
test.yml
- name: Test
hosts: hosts1
become: true
become_user: user1
environment:
"{{ default_environment }}"
tasks:
- debug:
msg: "{{ ansible_env }}"
group_vars /所有
default_environment:
HOME2: "{{ ansible_env.HOME }}"
使用ansible-plyabook test.yml
运行时输出
PLAY [Test] ********************************************************************************************************************************************************************************************************************************
TASK [Gathering Facts] *********************************************************************************************************************************************************************************************************************
fatal: [host1]: FAILED! => {}
MSG:
The field 'environment' has an invalid value, which includes an undefined variable. The error was: {u'HOME2': u'{{ ansible_env.HOME }}'}: 'ansible_env' is undefined
exception type: <class 'ansible.errors.AnsibleUndefinedVariable'>
exception: {u'HOME2': u'{{ ansible_env.HOME }}'}: 'ansible_env' is undefined
to retry, use: --limit @/work/ansible/test.retry
PLAY RECAP *********************************************************************************************************************************************************************************************************************************
host1 : ok=0 changed=0 unreachable=0 failed=1
答案 0 :(得分:0)
错误消息是:
&#39; ansible_env&#39;未定义
你没有收集事实。
在您尝试收集事实之前运行游戏,而不声明environment
:
- name: Test
hosts: hosts1
become: true
become_user: user1
- name: Test
hosts: hosts1
become: true
become_user: user1
gather_facts: false
environment:
"{{ default_environment }}"
tasks:
- debug:
msg: "{{ ansible_env }}"