Home > Mobile >  define variable list as a file in ansible playbook
define variable list as a file in ansible playbook

Time:11-09

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

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

CodePudding user response:

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 }}"
  • Related