如何用blockinfile或其他方法将多文件内容按文件名分隔合并到单文件
多文件合并并添加Block标记的Ansible实现方法
方法1:blockinfile结合循环(保留非Ansible管理内容场景)
利用blockinfile的标记唯一性,给每个文件的块标记带上文件名,避免内容被覆盖,同时支持保留目标文件中其他非Ansible管理的内容。
示例Playbook:
- name: Merge files with unique block markers hosts: localhost vars: source_files: - /tmp/file1.txt - /tmp/file2.txt dest_file: /tmp/merged_file tasks: - name: Insert each file's content with block markers ansible.builtin.blockinfile: path: "{{ dest_file }}" marker: "ANSIBLE MANAGED BLOCK {{ item | basename }}" block: "{{ lookup('file', item) }}" create: yes loop: "{{ source_files }}"
source_files:定义所有待合并的源文件路径列表lookup('file', item):读取单个源文件的内容marker:用文件名作为标记的一部分,确保每个文件的内容块独立create: yes:目标文件不存在时自动创建
方法2:template模块生成合并文件(全管理内容场景)
如果合并文件无需保留非Ansible管理的内容,用模板一次性生成更高效。
- 创建模板文件
merge_files.j2:
{% for file_path in source_files %} ANSIBLE MANAGED BLOCK {{ file_path | basename }} {{ lookup('file', file_path) }} ANSIBLE MANAGED BLOCK {{ file_path | basename }} {% endfor %}
- Playbook调用模板:
- name: Generate merged file via template hosts: localhost vars: source_files: - /tmp/file1.txt - /tmp/file2.txt dest_file: /tmp/merged_file tasks: - name: Render merged file ansible.builtin.template: src: merge_files.j2 dest: "{{ dest_file }}" mode: '0644'
模板通过循环遍历所有源文件,按要求格式输出标记和内容,一次性生成最终合并文件。
方法3:shell模块快速实现(非幂等场景)
如果不需要Ansible的幂等性保证,直接用Shell命令快速完成:
- name: Merge files with shell command hosts: localhost vars: source_files: "/tmp/file1.txt /tmp/file2.txt" dest_file: /tmp/merged_file tasks: - name: Execute merge script ansible.builtin.shell: | > {{ dest_file }} for file in {{ source_files }}; do echo "ANSIBLE MANAGED BLOCK $(basename $file)" >> {{ dest_file }} cat $file >> {{ dest_file }} echo "ANSIBLE MANAGED BLOCK $(basename $file)" >> {{ dest_file }} done
注意:该方法每次执行都会覆盖目标文件,仅适合一次性执行的场景。
内容的提问来源于stack exchange,提问作者Raj87
相关产品推荐
相关产品推荐

