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

+1 vote

An application creates a lot of definitions in /etc/services. To keep services file handy with all these definitions is good practice so that we can just pipe them into /etc/services like this:

cp /etc/services /etc/services.stock
cat /path/to/build/services >> /etc/services

It works, but it's not idempotent i.e. running these commands repeatedly will cause the services file to get appended with the info again.

As I work through our Ansible playbooks, I'm trying to figure out how to do this. I could so something like this:

- command: "cat /path/to/build/services >> /etc/services"

but I don't want it to run every time I run the playbook.

Another option is to do something like this:

- name: add services
    state: present
    insertafter: EOF
    dest: /etc/services
    line: "{{ item }}"
   - line 1
   - line 2
   - line 3
   - line 4
   - ...

It's not that fast, as it does each line individually.

Is there any other way around? Templates are not of that much help.

can anyone help me with this?


Jul 30, 2018 in Ansible by Damon Salvatore
• 5,540 points

1 answer to this question.

0 votes

Here is concept which you can follow.

blockinfile is a native, idempotent module to ensure a specified set of lines is present (absent) in a file.


- name: add services
    state: present
    insertafter: EOF
    dest: /etc/services
    marker: "<!-- add services ANSIBLE MANAGED BLOCK -->"
    content: |
      line 1
      line 2
      line 3

I hope the above information will be helpful for you.

answered Jul 30, 2018 by Atul
• 10,240 points

Related Questions In Ansible

+1 vote
2 answers

Running ansible command on a single server when it is deployed to multiple servers

You can try the run_once attribute: Example from ...READ MORE

answered Jun 13, 2018 in Ansible by DareDev
• 6,850 points
0 votes
1 answer

Is it possible to run commands on ansible host?

If you just trying to run a ...READ MORE

answered Jan 9, 2019 in Ansible by Vijay
0 votes
1 answer

Is it possible to run a playbook with a crontab?

Ofcourse you can run ansible playbook with ...READ MORE

answered Jan 17, 2019 in Ansible by Yesha
0 votes
1 answer

Is it possible to run an Ansible Playbook in python script?

Hey @Cerci, Of course its possible. You ...READ MORE

answered Jan 17, 2019 in Ansible by Nicolas
+13 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 26, 2018 in DevOps & Agile by DragonLord999
• 8,420 points
0 votes
1 answer
0 votes
1 answer

How to use Ansible git module pull a branch with local changes?

You cannot achieve it using the git ...READ MORE

answered Jul 9, 2018 in Ansible by Atul
• 10,240 points
0 votes
1 answer