Merge Append two files into single file and ensure no duplicate entries are found using Ansible

0 votes
I have two files /etc/hosts1 and /etc/hosts2. i need to merge these two files into one file /etc/hosts.

/etc/hosts should have all the contents of /etc/hosts1 and /etc/hosts2 without duplicate entries..

The playbook is expected to be idempotent.
Sep 17, 2020 in Ansible by jp
• 150 points
10,173 views

1 answer to this question.

0 votes

Hi@Jp,

You need to create your own customized scripts. According to your use case, the below playbook may help you.

- hosts: localhost
  gather_facts: no
  tasks:
  - name: Assemble from fragments from a directory
    assemble:
      src: file/
      dest: Mergedfile
  - name: Find uniqe entries
    shell: cat Mergedfile | sort -u | uniq -u > hosts
answered Sep 17, 2020 by MD
• 95,460 points
Could you help with the same examples

file1: /etc/hosts1 file2: /etc/hosts2 needs to be merged as /etc/hosts

Hi@Jp,

Do one thing, create a folder sya Myfolder and cp your hosts files inside this folder. And your ultimate goal is you need a final hosts file inside /etc folder. So modify the above code as shown above.

- hosts: localhost
  gather_facts: no
  tasks:
  - name: Assemble from fragments from a directory
    assemble:
      src: Myfolder/
      dest: Mergedfile
  - name: Find uniqe entries
    shell: cat Mergedfile | sort -u | uniq -u > /etc/hosts

Related Questions In Ansible

+1 vote
1 answer

Is it possible to append a large amount of text to a file using Ansible?

Here is concept which you can follow. blockinfile is ...READ MORE

answered Jul 30, 2018 in Ansible by Atul
• 10,240 points
14,679 views
0 votes
1 answer

Create directories and download files in Ansible using Ansible playbook

Hey @Yash,  you could either use file module ...READ MORE

answered Jan 24, 2019 in Ansible by Cerdin
5,945 views
0 votes
1 answer

How to encrypt and existing file using Ansible Vault?

Hey @Kyraa, to encrypt an existing file ...READ MORE

answered Jan 29, 2019 in Ansible by Kavya
3,456 views
0 votes
1 answer
+15 votes
2 answers

Git management technique when there are multiple customers and need multiple customization?

Consider this - In 'extended' Git-Flow, (Git-Multi-Flow, ...READ MORE

answered Mar 27, 2018 in DevOps & Agile by DragonLord999
• 8,450 points
4,040 views
+2 votes
1 answer
0 votes
1 answer

How to remove duplicate entries from a file using Ansible?

Hi@akhtar, You can use the shell module to do your ...READ MORE

answered Sep 17, 2020 in Ansible by MD
• 95,460 points
4,920 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP