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

define variable list as a file in ansible playbook

有人可以帮我找到在文件中声明所有变量并在 ansible 剧本中定义文件路径的最佳方法吗?这是我的 ansible-playbook

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

这些是里面的内容dir.txt

username=test1
password=mypassword

当我运行这个的时候,我遇到了一个错误

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

预期输出是通过此方法打印变量 任何帮助将不胜感激

您的代码无法运行的原因有两个。

  1. 变量文件应为 YAML 或 JSON 格式以便 Ansible 加载它
  2. 此类变量文件使用 vars_files 指令或 include_vars 任务加载,而不是 vars

所以一个名为 /root/dir.yml:

的 YAML 文件
username: test1
password: mypassword

可以在剧本中使用,例如:

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

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