简体   繁体   English

将变量列表定义为 ansible playbook 中的文件

[英]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?有人可以帮助我找到在文件中声明所有变量并在 ansible playbook 中定义文件路径的最佳方法吗? Here's my ansible-playbook这是我的 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这些是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变量文件应该是 YAML 或 JSON 格式,以便 Ansible 加载它
  2. Such variables files are loaded with vars_files directive or include_vars task, rather than vars此类变量文件使用vars_files指令或include_vars任务加载,而不是vars

So a YAML file named /root/dir.yml :所以一个名为/root/dir.yml的 YAML 文件:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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