大网数据广告活动
服务器运维问答

How can I use Ansible to conditionally append a line in a file?

· 52CE 我爱测

I'm trying to create an Ansible task that sets up trim/discards. I have a playbook that takes care of everything else (LVM, fstrim), but I can't figure out how to get crypttab configured properly. I'm trying to use the replace mo…

问题原文

原帖链接 · Mark Caudill · CC BY-SA 3.0

I'm trying to create an Ansible task that sets up trim/discards. I have a playbook that takes care of everything else (LVM, fstrim), but I can't figure out how to get crypttab configured properly.

I'm trying to use the replace module to append discard to the end of every line that doesn't have discard present, but I can't seem to get the regex right (I think that's my problem anyway).

I have a /etc/crypttab file that looks something like this:

luks-nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn UUID=nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn none discard
luks-nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn UUID=nnnnnnnn-nnnn-nnnn-nnnn-nnnnnnnnnnnn none

And here's the task:

- name: ensure crypttab is configured to issue discards
  replace: dest=/etc/crypttab backup=yes
    regexp='^(.*(?! discard))$'
    replace='\1 discard'

已采纳解答

原帖链接 · Marty · CC BY-SA 3.0

I'm pretty sure your issue is with the regexp. You'll need to move the lookahead assertion in front of the wildcard in order to only match lines that do not end in discard. For example, ^(?!.* discard$)(.*)$.

Once you make that change you'll have an additional problem in that empty lines will match too -- probably undesirable. Use something like ^(?!.* discard$)(.+)$ to fix this issue by matching one or more characters with .+ (instead of zero or more, .*).

Alternatively, you can use a lookbehind assertion, as in ^(.+)(?<! discard)$.

摘自公开归档,保留原文语言,版式经整理,外部媒体与邮箱地址已移除。

资料来源与适用范围

资料来源
Server Fault
适用范围
以原帖系统、软件版本与发布日期为准(2016-05-20)
内容语言
中文;命令、路径和错误标识保留技术原文
本地收录日期
2026-11-15
授权说明
CC BY-SA 3.0

正文与所需资源由本站本地存储。查看来源及更新记录 ↗

请按适用版本和实际日志确认原因;本站没有对每一种系统或设备逐项执行文中的操作。