Ansible - How to use lookup in remote servers

Viewed 2460

I have a file called values.txt on each of the server in the directory /tmp/values.txt and it has some values. And I have a jinja template and I am substituting some values from the the values.txt

But the problem is, when i use the lookup command it looks in the controller server and not the remote servers

Here's what I tried:

- name: Create /etc/systemd/system/etcd.service
  template:
    src: etcd.service.j2
    dest: /etc/systemd/system/etcd.service
  vars:
    value_from_file: "{{ lookup('file', '/tmp/values.txt').split('\n') }}"
    vars_from_jinja: [SELF_NAME, SELF_IP, NODE_1_NAME, NODE_1_IP, NODE_2_NAME, NODE_2_IP, NODE_3_NAME, NODE_3_IP, NODE_4_NAME, NODE_4_IP]
    my_dict: "{{ dict(vars_from_jinja|zip(value_from_file)) }}" 

How can I can this task remotely? Or is there another workaround to substitute the values to the jinja template?

PS: I can't fetch the values.txt to the controller because the content of values.txt in each server is slightly different from the other.

Can someone please help me?

2 Answers

The lookup find the file (or stream) on the controller. If you file is on the remote node, you can't use the lookup

Lookup plugins are an Ansible-specific extension to the Jinja2 templating language. You can use lookup plugins to access data from outside sources (files, databases, key/value stores, APIs, and other services) within your playbooks. Like all templating, lookups execute and are evaluated on the Ansible control machine. Ansible makes the data returned by a lookup plugin available using the standard templating system. You can use lookup plugins to load variables or templates with information from external sources.

try the cat file instead:

- name: read the values.txt
  shell: cat /tmp/values.txt
  register: data

- name: Create /etc/systemd/system/etcd.service
  template:
    src: etcd.service.j2
    dest: /etc/systemd/system/etcd.service
  vars:
    value_from_file: "{{ data.stdout_lines }}"
    vars_from_jinja: [ SELF_NAME, SELF_IP, NODE_1_NAME, NODE_1_IP, NODE_2_NAME, NODE_2_IP, NODE_3_NAME, NODE_3_IP, NODE_4_NAME, NODE_4_IP ]
    my_dict: "{{ dict(vars_from_jinja|zip(value_from_file)) }}"

Use slurp:

- name: read remote values.txt
  register: values
  ansible.builtin.slurp:
    src: /tmp/values.txt

- name: Create /etc/systemd/system/etcd.service
  template:
    src: etcd.service.j2
    dest: /etc/systemd/system/etcd.service
  vars:
    value_from_file: "{{ (values.content | b64decode).split('\n') }}"
    vars_from_jinja: [SELF_NAME, SELF_IP, NODE_1_NAME, NODE_1_IP, NODE_2_NAME, NODE_2_IP, NODE_3_NAME, NODE_3_IP, NODE_4_NAME, NODE_4_IP]
    my_dict: "{{ dict(vars_from_jinja|zip(value_from_file)) }}" 
Related