I'm trying to create an object in which a field depends of another, imagine the group_vars/all file contains something like:
people_names:
- first_name: tom
last_name: hardy
full_name: " {{ first_name}} {{ last_name}} "
The task is very simple, I'm trying to debug this:
- name: Test jinja2template
template:
src: test.j2
dest: test.conf
And the test.j2 would be something like:
{% for person in people_names %}
person_full_name = person.full_name
{% endfor %}
Is this even possible in Ansible/Jinja?
To build this I'm running the command:
ansible-playbook jinja2test.yml --check --diff --connection=local
When I run this I get the error AnsibleUndefinedVariable
for the last_name
.
Q: "Create an object in which a field depends on another."
A: It's not possible. See for example #8603. Create the dictionary with full names if you need it. For example
vars:
people_names:
- first_name: tom
last_name: hardy
tasks:
- set_fact:
people_full_names: "{{ people_full_names|default([]) +
[item|combine({'full_name': full_name})] }}"
loop: "{{ people_names }}"
vars:
full_name: "{{item.first_name}} {{ item.last_name }}"
- debug:
var: people_full_names
gives
"people_full_names": [
{
"first_name": "tom",
"full_name": "tom hardy",
"last_name": "hardy"
}
]