github.com/hashicorp/packer@v1.14.3/hcl2template/function/filebase64.go (about)

     1  package function
     2  
     3  import (
     4  	"encoding/base64"
     5  	"fmt"
     6  	"os"
     7  	"strings"
     8  
     9  	"github.com/zclconf/go-cty/cty"
    10  	"github.com/zclconf/go-cty/cty/function"
    11  )
    12  
    13  var Filebase64 = function.New(&function.Spec{
    14  	Params: []function.Parameter{
    15  		function.Parameter{
    16  			Name:        "path",
    17  			Description: "Read a file and encode it as a base64 string",
    18  			Type:        cty.String,
    19  		},
    20  	},
    21  	Type:         function.StaticReturnType(cty.String),
    22  	RefineResult: refineNotNull,
    23  	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
    24  		path := args[0].AsString()
    25  		content, err := os.ReadFile(path)
    26  		if err != nil {
    27  			return cty.NullVal(cty.String), fmt.Errorf("failed to read file %q: %s", path, err)
    28  		}
    29  
    30  		out := &strings.Builder{}
    31  		enc := base64.NewEncoder(base64.StdEncoding, out)
    32  		_, err = enc.Write(content)
    33  		if err != nil {
    34  			return cty.NullVal(cty.String), fmt.Errorf("failed to write file %q as base64: %s", path, err)
    35  		}
    36  		_ = enc.Close()
    37  
    38  		return cty.StringVal(out.String()), nil
    39  	},
    40  })