Home > other >  Ansible target template with group name?
Ansible target template with group name?

Time:10-31

I was wondering how could I target specific template for the group. Let's say I have invetory with following groups:

[group_1]
server_1
server_2
server_3

[group_2]
server_4
server_5
server_6

[group_3]
server_7
server_8
server_9

And then template directory containing files as follows:

├── templates
│   ├── group1_config.yml.j2
│   ├── group2_config.yml.j2
│   └── group3_config.yml.j2

What would be convenient way to get config by the group for correct hosts?

One way I was thinking that could I target them by having variable in template file name like:

{{ group_names }}.config.yml.j2

probably not ok like that :)

Any ideas?

Thanks!

CodePudding user response:

Use special variable group_names. It keeps the List of groups the current host is part of. In your case, all hosts are members of one group only. But the names of the template do not use the exact name of the groups. Let's take only the number from the name of the group and create the name of the template, e.g.

- hosts: all
  gather_facts: false
  tasks:
    - debug:
        msg: "{{ inventory_hostname }} group{{ group_names[0][-1] }}_config.yml.j2"

gives (abridged)

  msg: server_1 group1_config.yml.j2
  msg: server_2 group1_config.yml.j2
  msg: server_3 group1_config.yml.j2
  msg: server_4 group2_config.yml.j2
  msg: server_5 group2_config.yml.j2
  msg: server_6 group2_config.yml.j2
  msg: server_7 group3_config.yml.j2
  msg: server_8 group3_config.yml.j2
  msg: server_9 group3_config.yml.j2

CodePudding user response:

Could this be the answer:

- name: Copy a version of named.conf that is dependent on the OS. setype obtained by doing ls -Z /etc/named.conf on original file
  ansible.builtin.template:
    src: named.conf_{{ ansible_os_family }}.j2
    dest: /etc/named.conf
    group: named
    setype: named_conf_t
    mode: 0640
  • Related