Can cloud-config’s write_files control whether a newline is appended to the file

amazon-web-servicescloud-configcloud-init

I'd like to use cloud-config in user-data on AWS to write a file, say /etc/myfile. My experimentation so far seems to suggest that if the write_files block is the last bit of the user-data, then no trailing newline is written to the resulting file, whereas if there are other bits of config following then a newline is appended to the file. For example:

#cloud-config
write_files:
  - path: "/etc/myfile"
    permissions: "0444"
    owner: "root"
    content: |
      hello
  - path: "/etc/myfile2"
    permissions: "0444"
    owner: "root"
    content: |
      hello

…will generate two files. But they will have different content:

[me@ip-172-31-40-207:~]$ cat /etc/myfile
hello
[me@ip-172-31-40-207:~]$ cat /etc/myfile2
hello[me@ip-172-31-40-207:~]$

Other than manually ensuring write_files is never at the bottom, is there any way to control whether newline is added, and is this documented anywhere?

Best Answer

Turns out that it was the pipe (|) that caused it, combined with the fact that I had omitted the trailing newline on the input. So the solution is to omit the pipe, resulting in both files being written without a trailing newline.

The pipe means "maintain formatting of the following block of text", which cloud-init does correctly, including the newlines. Because I had omitted the trailing whitespace (i.e. the very last newline in the above example) , myfile2 was written without a trailing newline.

Related Topic