Search code examples
regexsedsalt-project

Using SaltStack to append to lines in a file if a regex is found


In essence, I'm trying to convert this sed command to a Salt file.replace method:

sed -i '/^\s*kernel/ s/$/ elevator=noop/' /etc/grub.conf

What it does, is if it finds a line in grub.conf that begins with any number of whitespaces and then "kernel", it replaces that with the entire original line + elevator=noop at the end.

so this:

kernel vmlinuz-2.6.32-431.29.2.el6.x86_64 [...] KEYTABLE=us rd_NO_DM rhgb quiet

becomes:

kernel vmlinuz-2.6.32-431.29.2.el6.x86_64 [...] KEYTABLE=us rd_NO_DM rhgb quiet elevator=noop

But when I directly copy in the sed cmd into pattern and repl in Salt's file.replace, I get this line:

s/$/ elevator=noop vmlinuz-2.6.32-431.29.2.el6.x86_64 [...] KEYTABLE=us rd_NO_DM rhgb quiet


Solution

  • I'm not proficient in sed and couldn't fully understand your sed command, but one thing I noticed that you may have missed is that sed uses $ for referencing groups while Python regex uses \ for that.

    That aside, your description was clear. So:

    If on the minion I did:

    echo "kernel vmlinuz-2.6.32-431.29.2.el6.x86_64 [...] KEYTABLE=us rd_NO_DM rhgb quiet" > /tmp/foo
    

    Then on the master:

    salt '*' file.replace /tmp/foo '(\s*kernel.*)' '\1 elevator=noop'
    

    Result:

    --- 
    +++ 
    @@ -1 +1 @@
    -kernel vmlinuz-2.6.32-431.29.2.el6.x86_64 [...] KEYTABLE=us rd_NO_DM rhgb quiet
    +kernel vmlinuz-2.6.32-431.29.2.el6.x86_64 [...] KEYTABLE=us rd_NO_DM rhgb quiet elevator=noop