Ansible 循环遍历结果并查找文件



我正在使用ansible来配置10-20个Linux系统。我有一组工具,我在带有版本的 invetory 文件中定义了这些工具,如下所示:

tools:
- tool: ABC
version: 7.8
- tool: XYZ
version: 8.32.1

现在,在我的播放 yml 文件中,我想遍历它们并拥有必要的安装逻辑。如:

调试工具循环

- name: Find installer files
copy:
src=
with_items:
- "{{ tools }}"
when:
tools.tool == "ABC"

就我而言,{{tools.tool}}/{{tools.version}} 有一个 tgz 文件,我需要在远程位置取消存档。你知道怎么做吗?我试过这些:

- name: Find installer files
vars:
files: {{ lookup("fileglob",'tools/{{item.tool}}/linux/{{item.version}}/*') }}
unarchive:
src: "{{ files }}"
dest: "tools/{{item.tool}}/{{item.version}}/"
with_items:
- "{{ tools }}"
when:
item.tool == "ABC"
- name: Find installer files
debug:
msg: "{{ item}}"
with_items:
- "{{ tools }}"
with_fileglob:
- "tools/{{item.tool}}/linux/{{item.version}}/*"
when:
item.toolchain == "ABC"

但没有一个奏效。感谢您的帮助。

这并不像我假设的目录中有多个文件时您自己的解决方案会中断那么简单。
因此,如果您的目录中只有一个文件,我根本不会使用fileglob而是为其定义一个固定名称,您可以生成已知的工具和版本。

我也经常看到需要这样的事情,但没有找到任何好的解决方案。只有像这样丑陋的事情:

- name: example book
hosts: localhost
become: false
gather_facts: false
vars:
tools:
- tool: ABC
version: 7.8
- tool: XYZ
version: 8.32.1
tools_files: []
tasks:
- name: prepare facts
set_fact:
tools_files: "{{ tools_files + [{'tool': item.tool | string, 'version': item.version | string, 'files': lookup('fileglob', 'tools/' ~ item.tool ~ '/linux/' ~ item.version ~ '/*', wantlist=True)}] }}"
with_items:
- "{{ tools }}"
- name: action loop
debug:
msg: "{{ {'src': item[1], 'dest': 'tools/' ~ item[0].tool ~ '/' ~ item[0].version ~ '/'} }}"
with_subelements:
- "{{ tools_files }}"
- files
when:
item[0].tool == "ABC"

- name: example book
hosts: localhost
become: false
gather_facts: false
vars:
tools:
- tool: ABC
version: 7.8
- tool: XYZ
version: 8.32.1
tools_files: []
tasks:
- name: prepare facts
set_fact:
tools_files: "{{ tools_files + [{'tool': item.tool | string, 'version': item.version | string, 'files': lookup('fileglob', 'tools/' ~ item.tool ~ '/linux/' ~ item.version ~ '/*', wantlist=True)}] }}"
with_items:
- "{{ tools }}"
- name: action loop
debug:
msg: "{{ {'src': item[1], 'dest': 'tools/' ~ item[0].tool ~ '/' ~ item[0].version ~ '/'} }}"
with_items:
- "{{ tools_files | subelements('files') }}"
when:
item[0].tool == "ABC"

也许我错过了一些东西,因为这些东西是一个非常基本的功能(通过一个数组循环生成一个结果数组,能够使用所有可用的函数,而不仅仅是map使用filters,其中一些重要的东西只是不可用或无法使用,因为 map 将 inport 作为第一个参数来过滤总是

(。

这其实很简单。这对我有用:

- name: Find installer files
unarchive:
src: 
"lookup('fileglob','tools/item.tool/linux/item.version/*') }}"
dest: "tools/{{item.tool}}/{{item.version}}/"
with_items:
- "{{ tools }}"
when:
item.tool == "ABC"

最新更新