Jananath Banuka
Jananath Banuka

Reputation: 3863

How to substitute values to a conf file using Ansible

I have an ansible playbook that has created a file (/tmp/values.txt) in each server with the following content

1.1.1.1
2.2.2.2
3.3.3.3
4.4.4.4
5.5.5.5

And I have a conf file named etcd.conf in the /tmp/etcd.conf with the following content

and I need to substitute the value of each line from /tmp/values.txt, so /tmp/etcd.conf will look like this:

SELF_IP=1.1.1.1
NODE_1_IP=2.2.2.2
NODE_2_IP=3.3.3.3
NODE_3_IP=4.4.4.4
NODE_4_IP=5.5.5.5

Is there a way I can do this? I used the following lookup method but it only works in the controll server

    - name: Create etcd.conf
      template:
        src: etcd.conf.j2
        dest: /tmp/etcd.conf
      vars:
        my_values: "{{ lookup('file', '/tmp/values.txt').split('\n') }}"
        my_vars: [SELF_IP, NODE_1_IP, NODE_2_IP, NODE_3_IP, NODE_4_IP]
        my_dict: "{{ dict(my_vars|zip(my_values)) }}"

Upvotes: 0

Views: 85

Answers (1)

mdaniel
mdaniel

Reputation: 33158

You can use the slurp: task to grab the content for each machine, or use command: cat /tmp/values.txt and then examine the stdout_lines of its register:-ed variable to achieve that same .split("\n") behavior (I believe you'll still need to use that .split call after | b64decode if you use the slurp approach)

What will likely require some massaging is that you'll need to identify the group (which may very well include all) of inventory hostnames for which that command will produce content, and then grab the hostvar out of them to get all values

Conceptually, similar to [ hostvars[hv].tmp_values.stdout_lines for hv in groups[the_group] ] | join("\n"), but it'll be tedious to write out, so I'd only want to do that if you aren't able to get it to work on your own

Upvotes: 1

Related Questions