Different variable values based on hostname (3 hosts)

I have a template tasks like

- name: template 'etcd.env'
  ansible.builtin.template:
    src: ../templates/templates/etcd.env.j2
    dest: "{{ etcd_bin_dir }}/.etcd.env"
    owner: "{{ ansible_become_user }}"
    group: "{{ ansible_become_user }}"
    mode: '0600'
  become: true

the template is:

ETCD_NAME="{{ etcd_name }}"
ETCD_INITIAL_ADVERTISE_PEER_URLS="http://{{ ansible_default_ipv4.address }}:2380"
ETCD_INITIAL_CLUSTER_STATE="new"
ETCD_ADVERTISE_CLIENT_URLS="http://{{ ansible_default_ipv4.address }}:2379"
  • I send this to 3 hosts.
  • The value for "{{ etcd_name }}" should be different based on the hostname (identified by inventory_hostname, or anisble_hostname) of the target?

how to I set this up?

3 x set_fact with a when condtion for each host comes to mind, but I have a feeling having heard people mentionen set_fact not being really ansible-ish.

setting up a host_var_dict was also thrown at me, but I do not quite get how this practically would look like.

what I need is
etcd_host0: rd5428.dbinfra.internaletcd_name: etcd_0
etcd_host1: rd5429.dbinfra.internaletcd_name: etcd_1
etcd_host2: rd5230.dbinfra.internaletcd_name: etcd_2

any hint how to approach this?

the hostnames would be set into variable like
etcd0_host: d5428.dbinfra.internal
inside a vars file loaded into the play.

1 Like

Call me dense, but not simply use host variables in your inventory?

it is a dynamic inventory with potentially different machines per execution. So I was thinking of putting this inside the playbook/tasksfile.

In that case, I don’t have any idea. I’m only using static inventories.

But maybe someone else comes up with a solution.

I have never heard this. I use set_fact all the time, including for this type of if statements.

The other option is to use vars:, either at the playbook level or the task level

I use tags on my instances and map than in different group_vars via dynamic inventories.
Maybe this helps you.

On my proxmox dynamic inventory

want_facts: true
keyed_groups:
  - key: proxmox_tags_parsed
    separator: ""

So tag ubuntu on instances load all group_vars/ubuntu.yml

And on aws ec2 inventory

filters:
  instance-state-name:
    - running
  tag:ansible_group:
    - ubuntu
    - oraclelinux
    - opnsense
keyed_groups:
  - key: tags['ansible_group']
    separator: ''
  - key: tags['infra_system']
    separator: ''
  - key: placement.availability_zone
    separator: ''

the tag infra_system: dns results in loading group_vars/dns.yml

maybe this helps…