Search code examples
puppet

Add text to the first line of a file with puppet


Is there a way to add a single line (or better yet a few lines) of new text to the very first line of a file with Puppet? (and have it do it just once obviously)

The background is, I am managing certain lines in the file, but I would like to put a one-time comment at the top of the file so its clear parts of this file are "managed".


Solution

  • I don't think you can do that with standard puppet resources such as file_line or augeas. What you could do is use an exec fx [edited]:

    $file = /somefile,
    $text = 'some text'
    ) {
      exec { "add ${text} to ${file}":
        command => "sed -i '1s/^/${text}\\n/' '${file}'",
        unless  => "grep '${text}' '${file}'",
        path     => ['/bin'],
      }    
    }
    

    See How do I add text to the beginning of a file in Bash? for other examples using bash.

    [original posted syntax] The example is updated with suggesting from [anonymous] to support spaces in filename and double escaped new line. Kept original syntax below for reference, since I haven't tested the double escaping of newline.

    $file = /somefile,
    $text = 'some text'
    ) {
      exec { "add ${text} to ${file}":
        command => "sed -i '1s/^/${text}\n/' ${file}",
        unless  => "grep '${text}' ${file}",
        path     => ['bin'],
      }    
    }