从ansible中的yaml文件导入变量

Import variables from yaml file in ansible

我正在尝试从 yaml 文件导入变量并在角色中使用它们,但是我正在尝试以一种方式导入变量,即我在角色中导入的任何任务文件也可以使用相同的变量而无需任何问题。因此,简单来说,我正在尝试为多个角色或任务文件可以使用的变量创建一种回购协议,并且可以保留该值。我从文档中找到的代码是:

  include_vars:
    dir: /projects/Variable_files
    files_matching: 
    - default.yml 
    - debian.yml
    name: default_vars

但我收到此错误:

ERROR! 'include_vars' is not a valid attribute for a Play. The error appears to be in '/projects/wordpress.yml': line 2, column 3, but may be elsewhere in the file depending on the exact syntax problem.

缺少破折号 -。正确的语法是

- include_vars:
    dir: /projects/Variable_files
    files_matching: '^(.*).yml$'
    name: default_vars

除此之外,参数files_matching是一个带正则表达式的字符串。例如 ^(.*).yml$ 匹配扩展名为 yml 的所有文件。参见 include_vars

可以使用first_found to select a file from a list. For example, see Generic way to list installed packages using Ansible


尽管参数 files_matching 应该是一个字符串,但列表也可以工作

- include_vars:
    dir: /projects/Variable_files
    files_matching: 
    - default.yml 
    - debian.yml
    name: default_vars