Ansible - include vars file from remote host
Asked Answered
C

3

10

I would like to include variables from a file on the remote host, rather than the control machine Ansible is running on.

For example I have a file /var/database_credentials.yml (on my webserver)

What's the best way to add variables from that file to hostvars so that I can use them in a template?

The include_vars module only takes files from the control machine. I could use the fetch module but that seems like an unnecessary step.

Chase answered 15/2, 2016 at 13:10 Comment(0)
V
3

It should not be hard to integrate that with /etc/ansible/facts.d.

You can store JSON files, INI files or executable scripts in that directory and the content/output will be available as server facts after the setup module was executed.

I'm not sure it will take YAML. You might be lucky and it'll work to simply add a symlink to your file /var/database_credentials.yml. (YAML is not mentioned in the docs but it would be strange if YAML is not supported since pretty much everything in Ansible is based on YAML) If not, you can create a script in the language you prefer which reads that file and outputs a JSON object.

See Local Facts (Facts.d) in the docs.

Veterinary answered 15/2, 2016 at 13:24 Comment(2)
Great thank you! That looks like exactly what I neededChase
It doesn't support YAML but ini file format works fine for meChase
O
0

You can register the remote file to a local variable, then parse it with from_yaml.

- name: "Read yml file"
  ansible.builtin.shell: "cat /var/database_credentials.yml"
  register: result
  
- name: "Parse yml into variable"
  set_fact:
    database_credentials: "{{ result.stdout | from_yaml }}"
Oppidan answered 6/11, 2022 at 20:50 Comment(0)
R
0

My solution using the slurp module:

- slurp:
     src: /etc/patroni/patroni.yml
  register: patroni_status
- set_fact:
     patroni_fact:
       "{{ patroni_status['content'] | b64decode | from_yaml }}"
Repute answered 24/7, 2024 at 9:14 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.