ansible loop with include_variable



我有一个剧本,在任务的include_vars部分下有多个yaml文件,正如你所看到的,我正在逐一单独定义它们。我想知道我是否能把它们穿过环路。

我在这里浏览了谷歌和ansible文档链接,但我没有找到loop的例子,然而,我看到了with_first_found,但我不想要。

我下面的剧本

---
- name: Creating aws host
hosts: localhost
connection: local
become: yes

tasks:
- include_vars: awsvariable.yml
no_log: true
- include_vars: vaults/mysecrets.yml
no_log: true
- include_vars: vaults/mydev.yml
no_log: true
- include_vars: requirements.yml

以下是我正在考虑的

这可行吗?

tasks:
- include_vars: "{{ item }}"
loop:
- awsvariable.yml
- vaults/mysecrets.yml
- vaults/mydev.yml
- requirements.yml
OR
tasks:
- include_vars: ['awsvariable.yml', 'vaults/mysecrets.yml', 'vaults/mydev.yml', 'requirements.yml']
no_log: true

如果我们能更好地将它们以其他方式对齐,请提出建议。

ansible版本:2.9BR.

我看到你已经接近你的答案了,是的,loop应该工作,试着在试运行模式下运行你的游戏,并设置no_log: false,看看你的变量是否正在扩展。

示例:

$ ansible-playbook test_play.yml --check --ask-vault-pass

您的代码

- include_vars: "{{ item }}"
loop:
- 'awsvariable.yml'
- 'vaults/mysecrets.yml'
- 'vaults/mydev.yml'
- 'requirements.yml'
no_log: true

使用dir将所有文件包含在文件夹中。

- name: Include variable files
include_vars:
dir: vars
extensions:
- "yml"

或者,可以同时使用loopwith_items循环遍历文件名并包含它们。

- name: Include variable files
include_vars: "{{ item }}"
with_items:
- "vars/file.yml"
- "vars/anotherfile.yml"

或者使用较新的loop

- name: Include variable files
include_vars: "{{ item }}"
loop:
- "vars/file.yml"
- "vars/anotherfile.yml"

似乎include_vars模块无法使用循环。您可以使用include_task模块在具有单个任务的文件上循环到include_vars:

---
- hosts: localhost
gather_facts: false
vars:
files_to_load: 
- file1.yml
- file2.yml
- file3.yml
tasks:
- include_tasks: include_vars.yml
loop: "{{ files_to_load }}"
loop_control:
loop_var: file_to_load

antinclude_vars.yml文件:

- name: include vars {{ file_to_load }}
include_vars: "{{ file_to_load }}"

更新

关于我尝试过但没有成功的循环语法,以下尝试失败了:

第一:

- include_vars: "{{ item }}"
loop: - "{{ files_to_load }}" 

第二:

- include_vars: "{{ item }}"
loop: 
- "{{ files_to_load }}"

我知道这个语法有效:

- name: Include variable files
include_vars: "{{ item }}"
loop:
- "vars/file.yml"
- "vars/anotherfile.yml"

但就我个人而言,我觉得你需要在任务级别列出循环项目这一事实并不方便。

最新更新