大网数据广告活动
服务器运维问答

How to merge two files into single file using ansible in remote server

· 52CE 我爱测

I need to merge two files without duplicate entries in it. is there any way i can achieve it through ansible modules. Ex i have two files /etc/hosts1 and /etc/hosts2. I need to have one /etc/hosts file with all entries present in…

问题原文

原帖链接 · celcoprab · CC BY-SA 4.0

I need to merge two files without duplicate entries in it. is there any way i can achieve it through ansible modules. Ex i have two files /etc/hosts1 and /etc/hosts2. I need to have one /etc/hosts file with all entries present in both /etc/hosts1 and /etc/hosts2 without duplicate entries. How can i achieve this. An example would be appreciated

- name: Merge two files
  assemble:
    src: /etc/hosts1
    dest: /etc/hosts2

The above assemble module fails

已采纳解答

原帖链接 · Gerald Schneider · CC BY-SA 4.0

This works. It reads the contents of all files and reduces the resulting array of lines to unique values. Then a new file with those lines is created.

- hosts: localhost
  gather_facts: no
  vars:
    hostsfiles:
      - /tmp/hosts1
      - /tmp/hosts2
  tasks:
  - name: read files
    command: awk 1 {{ hostsfiles | join(' ') }}
    register: hosts_contents
  - name: create hosts file
    copy:
      dest: /tmp/hosts
      content: "{{ hosts_contents.stdout_lines | unique |join('\n') }}"

I'm using awk 1 instead of cat to add potentially missing line breaks to the end of the source files.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2020-09-16)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 4.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。