简体   繁体   中英

Ansible replace or lineinfile?

All,

I have been trying to figure something out all day, i got ot working with the shell module and sed but cant do it with a more native way such as replace or lineinfile. This is what i am trying to do:

I have a file that has a few lines and some lines start with a different string but others with the same which are the ones i want to edit, then all the lines at some point have a particular string and i want to edit this string only on the lines that start with that particular string.

Here is a more visual example:

The file by the way is /etc/fstab and looks something like this

Aaaaa:/mount1  /mountpoint1 nfs mount-options 0 0
Aaaaa:/mount2  /mountpoint4 nfs mount-options 0 0
Bbbbbn:/mount1  /mountpoin9  nfs mount-options 0 0

As you can see in this example the mount options which is what I want to change are identical however I want to edit only the ones in lines that start with aaaa for example.

Any clues how to do this with a module like replace or lineinfile and not sed using the shell?

Thanks

UPDATE: Let me clarify that the stuff after aaaaa: until nfs mount-options 0 0 could be anything, as the mount folders and mount points on the server could be anything. Also this is how I got it to work using the shell module, still looking for a more native module instead of shell:

  - name: Inserting new mounting options
    shell: sed -i '/^aaaaa/ s/mount-options/new-mount-options/g' /etc/fstab

In the above example I successfully target lines starting with aaaaa and replace the mount-options to different ones while keeping the 0 0 at this end.

Replace fits better the use-case. See the example below. For example, let's

  • set dump fsck to 1 1 where lines begin with Aaaaa
  • set fstype to ext4 where lines begin with Bbbbbn

The task below

- replace:
    path: /scratch/fstab
    regexp: "{{ item.regexp }}"
    replace: "{{ item.replace }}"
  loop:
    - regexp: '^Aaaaa(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(.*)$'
      replace: 'Aaaaa\1 \2 \3 \4 1 1'
    - regexp: '^Bbbbbn(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)\s+(\S+)(.*)$'
      replace: 'Bbbbbn\1 \2 ext4 \4 \5 \6'

gives

$ cat fstab
Aaaaa:/mount1 /mountpoint1 nfs mount-options 1 1
Aaaaa:/mount2 /mountpoint4 nfs mount-options 1 1
Bbbbbn:/mount1 /mountpoin9 ext4 mount-options 0 0


The regex are cumbersome. I can't get working Capturing repeating subpatterns in Python regex .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM