2

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'
Mark Caudill
  • 111
  • 1
  • 6
  • what happens when you run that? does it give an error, what does it do to the file, etc.? – tedder42 May 21 '16 at 03:44
  • No matter the contents of `crypttab`, it adds `discard discard` (two `discard`s) to the end of each line. My goal is to have it add a single `discard` to the end of each line that doesn't already have it. – Mark Caudill May 22 '16 at 15:38
  • Try putting .* in parenthesis and then using \2 instead of \1. If that doesn't work I'll build a test case and try to reproduce. – tedder42 May 22 '16 at 18:36
  • Using `regexp='^((.*)(?! discard))$' replace='\2 discard'` it still appnded `discard discard`. Though, I noticed that it's actually appending `discard\n discard`. That's the same behavior as before, but I hadn't noticed the `\n` until now. – Mark Caudill May 23 '16 at 12:13

1 Answers1

3

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)$.

Marty
  • 496
  • 2
  • 5