From 8e75537601072bc54f5860e75e5f97bae38795a4 Mon Sep 17 00:00:00 2001 From: Anurag Sharma Date: Thu, 13 Mar 2025 22:05:49 +0530 Subject: [PATCH] check for shebang after whole script is interpolated --- provisioner/shell/provisioner.go | 34 +++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/provisioner/shell/provisioner.go b/provisioner/shell/provisioner.go index e73a6f4a1..b9673acc1 100644 --- a/provisioner/shell/provisioner.go +++ b/provisioner/shell/provisioner.go @@ -9,6 +9,7 @@ package shell import ( "bufio" + "bytes" "context" "errors" "fmt" @@ -207,29 +208,38 @@ func (p *Provisioner) Provision(ctx context.Context, ui packersdk.Ui, comm packe scripts = append(scripts, tf.Name()) // Write our contents to it - writer := bufio.NewWriter(tf) - var shebangWritten bool + fileWriter := bufio.NewWriter(tf) + commandBuffer := &bytes.Buffer{} for _, command := range p.config.Inline { p.config.ctx.Data = generatedData command, err := interpolate.Render(command, &p.config.ctx) if err != nil { return fmt.Errorf("Error interpolating Inline: %s", err) } - if !shebangWritten { - // If the user has defined an inline shebang, use that. - // Or If command does not start with a shebang, use the default shebang. - // else command already has a shebang, so do not write it. - if p.config.inlineShebangDefined || !strings.HasPrefix(command, "#!") { - _, _ = writer.WriteString(fmt.Sprintf("#!%s\n", p.config.InlineShebang)) - } - shebangWritten = true + if _, err := commandBuffer.WriteString(command + "\n"); err != nil { + return fmt.Errorf("Error preparing shell script: %s", err) } - if _, err := writer.WriteString(command + "\n"); err != nil { + } + + firstLine, err := commandBuffer.ReadString('\n') + if err != nil && err != io.EOF { + return fmt.Errorf("Error preparing shell script: %s", err) + } + // If the user has defined an inline shebang, use that. + // Or If command does not start with a shebang, use the default shebang. + // else command already has a shebang, so do not write it. + if p.config.inlineShebangDefined || !strings.HasPrefix(firstLine, "#!") { + if _, err := fileWriter.WriteString(fmt.Sprintf("#!%s\n", p.config.InlineShebang)); err != nil { return fmt.Errorf("Error preparing shell script: %s", err) } } - if err := writer.Flush(); err != nil { + // Write the collected commands to the file buffer + if _, err := fileWriter.Write(commandBuffer.Bytes()); err != nil { + return fmt.Errorf("Error preparing shell script: %s", err) + } + + if err := fileWriter.Flush(); err != nil { return fmt.Errorf("Error preparing shell script: %s", err) }