I am trying to use the lookup plugin to lookup the environment variable from inside a lookup function that looks up a file.
So the file name is _hosts.txt and i want the lookup function to replace the ENV with the passed environment variable.
I looked up at the ansible documentation for lookup and still couldnt figure out the error.
Here is the code block:
- name: "Update the /etc/hosts file"
blockinfile:
block: "{{ lookup('file', ' + lookup('env', 'ENV') +_hosts.txt') }}"
dest: "/etc/hosts"
backup: yes
Output:
FAILED! => {"msg": "template error while templating string: expected token ',', got 'env'. String: {{ lookup('file', ' + lookup('env', 'ENV') +_hosts.txt') }}"}
I know its a syntax issue but just cant figure out what it is.
You can activate a custom lookup by either dropping it into a lookup_plugins directory adjacent to your play, inside the plugins/lookup/ directory of a collection you have installed, inside a standalone role, or in one of the lookup directory sources configured in ansible. cfg.
with_fileglob matches all files in a single directory, non-recursively, that match a pattern. It calls Python's glob library. (plus a warning about relative paths with roles).
This module allows setting new variables. Variables are set on a host-by-host basis just like facts discovered by the setup module. These variables will be available to subsequent plays during an ansible-playbook run.
With hostvars , you can access variables defined for any host in the play, at any point in a playbook. You can access Ansible facts using the hostvars variable too, but only after you have gathered (or cached) facts.
Use a helper variable:
- name: "Update the /etc/hosts file"
blockinfile:
block: "{{ lookup('file', filename) }}"
vars:
filename: "{{ lookup('env', 'ENV') }}_hosts.txt"
or you can write it in one line:
block: "{{ lookup('file', lookup('env', 'ENV') + '_hosts.txt' ) }}"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With