我正在使用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"
但没有一个有效。感谢您的帮助。
这实际上很简单。这对我有用:
- 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"
并不是那么简单,因为如果目录中有多个文件,您自己的解决方案就会中断。因此,如果您在目录中只有一个文件,那么我将完全不使用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作为第一个参数来始终进行过滤)。