如何在Ansible中批量下载文件并读取配置生成循环变量
Ansible批量下载文件:读取文件列表并循环执行get_url任务
一、读取config.txt生成fileList变量
你可以通过两种方式将config.txt中的文件名列表转为Ansible可用的fileList变量:
方法1:直接用lookup插件定义变量
在playbook的vars部分直接读取文件内容并处理成干净的列表:
vars: fileList: "{{ lookup('file', 'config.txt').splitlines() | map('trim') | select('ne', '') | list }}"
lookup('file', 'config.txt'):读取控制节点当前工作目录下的config.txt内容splitlines():按换行符分割成列表map('trim'):去除每个文件名前后的空格select('ne', ''):过滤掉空行(避免因文件空行导致无效循环)
方法2:用slurp模块读取目标主机上的文件
如果config.txt存放在目标主机而非控制节点,用slurp模块读取并处理:
- name: 读取目标主机上的config.txt ansible.builtin.slurp: src: /path/to/config.txt # 替换为目标主机上的实际路径 register: config_content - name: 生成fileList变量 ansible.builtin.set_fact: fileList: "{{ (config_content.content | b64decode).splitlines() | map('trim') | select('ne', '') | list }}"
- slurp返回的内容是base64编码格式,需用
b64decode解码后再处理
二、修改get_url任务实现批量下载
将原任务中的硬编码路径改为动态引用循环变量item,让每个文件名对应一次下载操作:
- name: 批量下载文件 ansible.builtin.get_url: url: "http://example.com/path/{{ item }}" dest: "/etc/{{ item }}" mode: '0440' loop: "{{ fileList }}"
loop: "{{ fileList }}":遍历fileList中的每个文件名{{ item }}:循环过程中代表当前迭代的文件名,自动替换到url和dest路径中
完整示例playbook
--- - name: 批量下载文件任务 hosts: your_target_hosts # 替换为你的目标主机组/主机名 vars: fileList: "{{ lookup('file', 'config.txt').splitlines() | map('trim') | select('ne', '') | list }}" tasks: - name: 批量下载文件到/etc目录 ansible.builtin.get_url: url: "http://example.com/path/{{ item }}" dest: "/etc/{{ item }}" mode: '0440' loop: "{{ fileList }}"
内容的提问来源于stack exchange,提问作者george jiang
相关产品推荐
相关产品推荐

