I'm using Ansible to build inventories dynamically according to several parameters.
I get raw info from our CMDB's API, then use set_fact
to format a list of FQDNs.
Those FQDNs always follow the same formula, so it looks easy, but Ansible only seems to apply the templating to the first item.
The code:
- name: populate list of all hosts
set_fact:
all_hosts: '{{ all_hosts [ "{{item.value.fields.friendlyname | lower}}" "." "{{item.value.fields.friendlyname[:3]|lower}}" ".sncoia.lan" ] }}'
loop: "{{ hostname.json.objects | dict2items }}"
when:
- item.value.fields.friendlyname | length == 12
- debug: var=all_hosts
The result (abridged for brevity):
TASK [debug] **********************************************************************************************************************************************************************************
ok: [localhost] => {
"all_hosts": [
"devlappaps03.dev.sncoia.lan",
"{{item.value.fields.friendlyname | lower}}.{{item.value.fields.friendlyname[:3]|lower}}.sncoia.lan",
"{{item.value.fields.friendlyname | lower}}.{{item.value.fields.friendlyname[:3]|lower}}.sncoia.lan",
CodePudding user response:
Given the data for testing
hostname:
json:
objects:
foo:
fields:
friendlyname: devlappaps03
bar:
fields:
friendlyname: devlappaps02
baz:
fields:
friendlyname: devlappaps01
Properly concatenate the FQDN. For example
- set_fact:
all_hosts: "{{ all_hosts|d([]) [_fqdn] }}"
loop: "{{ hostname.json.objects|dict2items }}"
when: item.value.fields.friendlyname|length == 12
vars:
_fqdn_list:
- "{{ item.value.fields.friendlyname|lower }}"
- "{{ item.value.fields.friendlyname[:3]|lower }}"
- "sncoia.lan"
_fqdn: "{{ _fqdn_list|join('.') }}"
gives
all_hosts:
- devlappaps03.dev.sncoia.lan
- devlappaps02.dev.sncoia.lan
- devlappaps01.dev.sncoia.lan