diff --git a/agent/cloudinit/file_writer.go b/agent/cloudinit/file_writer.go index bd7e497a4..9ac071f52 100644 --- a/agent/cloudinit/file_writer.go +++ b/agent/cloudinit/file_writer.go @@ -56,6 +56,8 @@ func (w FileWriter) WriteToFile(file *Files) error { flag := os.O_WRONLY | os.O_CREATE if file.Append { flag |= os.O_APPEND + } else { + flag |= os.O_TRUNC } f, err := os.OpenFile(file.Path, flag, initPermission) diff --git a/agent/cloudinit/file_writer_test.go b/agent/cloudinit/file_writer_test.go index 3142f0725..d896254d5 100644 --- a/agent/cloudinit/file_writer_test.go +++ b/agent/cloudinit/file_writer_test.go @@ -97,6 +97,31 @@ var _ = Describe("FileWriter", func() { }) + It("Should overwrite content of file when append mode is disabled", func() { + fileOriginContent := "very long long message" + file := cloudinit.Files{ + Path: path.Join(workDir, "file3.txt"), + Encoding: "", + Owner: "", + Permissions: "", + Content: "short message", + Append: false, + } + + err := cloudinit.FileWriter{}.MkdirIfNotExists(workDir) + Expect(err).NotTo(HaveOccurred()) + + err = os.WriteFile(file.Path, []byte(fileOriginContent), 0644) + Expect(err).NotTo(HaveOccurred()) + + err = cloudinit.FileWriter{}.WriteToFile(&file) + Expect(err).NotTo(HaveOccurred()) + + buffer, err := os.ReadFile(file.Path) + Expect(err).NotTo(HaveOccurred()) + Expect(string(buffer)).To(Equal(file.Content)) + }) + It("should return error with invalid owner format", func() { file := cloudinit.Files{ Path: path.Join(workDir, "file1.txt"),