Reputation: 4501
Put this in group_vars/all
:
default_environment:
HOME2: "{{ ansible_env.HOME }}"
When using in a task to define environment:
environment:
"{{ default_environment }}"
I get this:
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'>
Is there a way to define a group variable based on the current remote environment variables, $HOME
in this case?
EDIT: Per request, reproducible case:
test.yml
- name: Test
hosts: hosts1
become: true
become_user: user1
environment:
"{{ default_environment }}"
tasks:
- debug:
msg: "{{ ansible_env }}"
group_vars/all
default_environment:
HOME2: "{{ ansible_env.HOME }}"
Output when run with 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
Upvotes: 3
Views: 4508
Reputation: 68479
The error message is:
'ansible_env' is undefined
You did not gather the facts.
Run a play before the one you try to gather facts only, without declaring the 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 }}"
Upvotes: 3