6

I have this inventory file

inventory/hosts_elk

[elk-client-0]
10.11.22.22

Now I have a template, and I want to do this

elk_server.yml.j2

elk_server = {{ elk-client-0 }}

But that doesn't work, that is the value for {{ elk-client-0 }} does NOT get substituted.

What is the correct syntax so when the template gets laid out on the server, the resulting file looks like

elk_server = 10.11.22.22
Chris F
  • 14,337
  • 30
  • 94
  • 192

3 Answers3

8

The magic syntax is

elk_server: {{ groups['elk-client-0'][0] }}
Chris F
  • 14,337
  • 30
  • 94
  • 192
0

I think you're looking for inventory_hostname and/or ansible_hostname http://docs.ansible.com/ansible/playbooks_variables.html

wilkesybear
  • 528
  • 3
  • 9
  • Maybe, but that page doesn't show how to use it in a template. – Chris F Apr 21 '17 at 16:23
  • does `elk_server = {{ inventory_hostname }}` work for you? – wilkesybear Apr 21 '17 at 16:26
  • No. Note the host I'm running the Ansible playbook is NOT elk-client-0, but another host that needs to connect to elk-client-0. So I need to replace the IP for elk-client-0 from the inventory file in resulting file. – Chris F Apr 21 '17 at 16:33
0

in terms of ansible inventory, elk-client-0 is a host group, accessible via groups.<name>. Specifically, you want to find the 1st (or last?) host in the inventory, of specific hostgroup, so in the template you can do:

elk_server = {{groups.elk-client-0|random}}

This as of "now" will always return 1 item. but when your host group grows, it will roll the dice. If you need to either take always first, last, just use those filters.

mvk_il
  • 940
  • 8
  • 11
  • Also, I am usually avoiding to add '-' characters in hostgroup names. b/c e.g. in AWS the dynamic inventory script `ec2.py` does "normalization" to host group names, converting everything into '_' (spaces, '-', etc.), – mvk_il Apr 21 '17 at 16:58
  • Thanks, but that didn't work either, that is, I just see elk_serer = {{groups.elk-client-0|random}} in the resulting file, so the variable was not found. – Chris F Apr 21 '17 at 17:08