简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM