繁体   English   中英

Ansible Replace或lineinfile?

[英]Ansible replace or lineinfile?

所有,

我一直在努力寻找解决办法,我可以使用shell模块进行sed操作,但无法使用更本地的方式(例如replace或lineinfile)来完成。 这就是我想要做的:

我有一个文件,其中有几行,有些行以不同的字符串开头,而其他几行以我要编辑的相同,那么所有的行在某个点上都有特定的字符串,我只想编辑此字符串以该特定字符串开头的行。

这是一个更直观的示例:

顺便说一下,文件是/ etc / fstab,看起来像这样

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

正如您在本示例中看到的那样,我要更改的安装选项是相同的,但是我只想编辑以aaaa开头的行中的选项。

有什么线索如何使用诸如replace或lineinfile之类的模块而不是使用Shell来执行此操作?

谢谢

更新:让我澄清一下,aaaaa之后的内容:直到nfs mount-options 0 0可以是任何东西,因为服务器上的安装文件夹和安装点可以是任何东西。 这也是我使用shell模块使它工作的方式,仍然在寻找一个更本地的模块而不是shell:

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

在上面的示例中,我成功地定位了以aaaaa开头的行,并将mount-options替换为不同的选项,同时保持0 0到此结束。

替换更适合用例。 请参见下面的示例。 例如,让我们

  • dump fsck设置为1 1 ,其中行以Aaaaa开头
  • fstype设置为ext4 ,其中行以Bbbbbn

下面的任务

- 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'

$ 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


正则表达式很麻烦。 我无法使用Python regex捕获重复子模式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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