Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

define variable list as a file in ansible playbook

Can someone help me in finding the best way to declare all variables inside a file and define the file path in ansible playbook? Here’s my ansible-playbook

---
- hosts: myhost
  vars:
    - var: /root/dir.txt
  tasks:
    - name: print variables
      debug:
        msg: "username: {{ username }}, password: {{ password }}"

These are the contents inside dir.txt

username=test1
password=mypassword

When I run this, I am facing an error

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

TASK [print variables] *********************************************************************************************************
fatal: [121.0.0.7]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'username' is undefined\n\nThe error appears to be in '/root/test.yml': line 6, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n  tasks:\n    - name: print variables\n      ^ here\n"}

Expected output is to print the variables by this method
Any help would be appreciated

>Solution :

There are two reasons why your code won’t work.

  1. A variables file should be in YAML or JSON format for Ansible to load it
  2. Such variables files are loaded with vars_files directive or include_vars task, rather than vars

So a YAML file named /root/dir.yml:

username: test1
password: mypassword

Can be used in a playbook like:

---
- hosts: myhost
  vars_files:
    - /root/dir.yml

  tasks:
    - name: print variables
      debug:
        msg: "username: {{ username }}, password: {{ password }}"
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading