-1

I know how to replace strings in the file with the ansible replace module. What I am looking at is replacing a specific line.

I have a file that has the same string in several places and I only want to replace one instance of it.

Is there a way to just replace the X instance or give it a specific line to replace?

closed as unclear what you're asking by thrig, Jeff Schaller, Thomas, sebasth, msp9011 Sep 2 '18 at 21:34

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    1) What have you tried? 2) Provide a sample of the file. – Nasir Riley Sep 1 '18 at 15:49
1

Is there a way to just replace the X instance or give it a specific line to replace?

If it were me, I'd use the shell module and a standard sed invocation to change at a specific line. In the example below, I am using sed to change only the fourth line.

---
- hosts: all 
  tasks:
    - name: "Run sed via ansible"
      shell: sed -i '4s/bike/car/' /home/maulinglawns/slask/sed_example

Example of file before ansible playbook:

cat sed_example 
bike plane
bike plane
bike plane
bike plane
bike plane
bike plane
bike plane
bike plane
bike plane
bike plane

Running playbook:

ansible-playbook sed_with_ansible.yml -i "localhost," -k
SSH password: 

PLAY [all] *********************************************************************

TASK [setup] *******************************************************************
ok: [localhost]

TASK [Run sed via ansible] *****************************************************
changed: [localhost]
 [WARNING]: Consider using template or lineinfile module rather than running
sed


PLAY RECAP *********************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0  

File after playbook:

cat sed_example 
bike plane
bike plane
bike plane
car plane
bike plane
bike plane
bike plane
bike plane
bike plane
bike plane

You might be able to achieve this with the lineinfile module, but I do not know of any such switches, and could not find any in the documentation.

  • The sed command seems to work great. – user2236794 Sep 2 '18 at 18:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.