hclfuncs

package module
v0.6.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 27, 2024 License: MPL-2.0 Imports: 23 Imported by: 2

README

HCL Funcs

This library is a facade that combines all built-in functions provided by HashiCorp Packer and some functions from HashiCorp Terraform.

All copied functions are copied from Terraform and Packer's latest MPL 2.0 license version, all referenced functions are based on MPL 2.0 or MIT license.

Goroutine-local env function

env function is different than the Packer version, we provided a goroutine-local cache so the caller can set different environment variables for different goroutines, this is very handy when you allow users to set different environment variables for a specified HCL block, like this example. Please check out this unit test for details.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var ComplimentFunction = function.New(&function.Spec{
	Description: "Return the compliment of list1 and all otherLists.",
	Params: []function.Parameter{
		{
			Name:             "list1",
			Description:      "the first list, will return all elements that in this list but not in any of other lists.",
			Type:             cty.Set(cty.DynamicPseudoType),
			AllowDynamicType: true,
		},
	},
	VarParam: &function.Parameter{
		Name:             "otherList",
		Description:      "other_list",
		Type:             cty.Set(cty.DynamicPseudoType),
		AllowDynamicType: true,
	},
	Type:         setOperationReturnType,
	RefineResult: refineNonNull,
	Impl: setOperationImpl(func(s1, s2 cty.ValueSet) cty.ValueSet {
		return s1.Subtract(s2)
	}, false),
})
View Source
var ConsulFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "key",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		key := args[0].AsString()
		val, err := commontpl.Consul(key)

		return cty.StringVal(val), err
	},
})

ConsulFunc constructs a function that retrieves KV secrets from HC vault

View Source
var EnvFunction = function.New(&function.Spec{
	Description: "Read environment variable, return empty string if the variable is not set.",
	Params: []function.Parameter{
		{
			Name:         "key",
			Description:  "Environment variable name",
			Type:         cty.String,
			AllowUnknown: true,
			AllowMarked:  true,
		},
	},
	Type: function.StaticReturnType(cty.String),
	RefineResult: func(builder *cty.RefinementBuilder) *cty.RefinementBuilder {
		return builder.NotNull()
	},
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		key := args[0]
		if !key.IsKnown() {
			return cty.UnknownVal(cty.String), nil
		}
		envKey := key.AsString()
		localEnv := GoroutineLocalEnv.Get()
		if localEnv != nil {
			if env, ok := localEnv[envKey]; ok {
				return cty.StringVal(env), nil
			}
		}
		env := os.Getenv(envKey)
		return cty.StringVal(env), nil
	},
})
View Source
var GoroutineLocalEnv = routine.NewThreadLocal[map[string]string]()
View Source
var IndexFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "list",
			Type: cty.DynamicPseudoType,
		},
		{
			Name: "value",
			Type: cty.DynamicPseudoType,
		},
	},
	Type: function.StaticReturnType(cty.Number),
	Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
		if !(args[0].Type().IsListType() || args[0].Type().IsTupleType()) {
			return cty.NilVal, errors.New("argument must be a list or tuple")
		}

		if !args[0].IsKnown() {
			return cty.UnknownVal(cty.Number), nil
		}

		if args[0].LengthInt() == 0 {
			return cty.NilVal, errors.New("cannot search an empty list")
		}

		for it := args[0].ElementIterator(); it.Next(); {
			i, v := it.Element()
			eq, err := stdlib.Equal(v, args[1])
			if err != nil {
				return cty.NilVal, err
			}
			if !eq.IsKnown() {
				return cty.UnknownVal(cty.Number), nil
			}
			if eq.True() {
				return i, nil
			}
		}
		return cty.NilVal, errors.New("item not found")

	},
})

IndexFunc constructs a function that finds the element index for a given value in a list.

View Source
var InitTime time.Time

InitTime is the UTC time when this package was initialized. It is used as the timestamp for all configuration templates so that they match for a single build.

View Source
var LegacyIsotimeFunc = function.New(&function.Spec{
	Params: []function.Parameter{},
	VarParam: &function.Parameter{
		Name: "format",
		Type: cty.String,
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		if len(args) > 1 {
			return cty.StringVal(""), fmt.Errorf("too many values, 1 needed: %v", args)
		} else if len(args) == 0 {
			return cty.StringVal(InitTime.Format(time.RFC3339)), nil
		}
		format := args[0].AsString()
		return cty.StringVal(InitTime.Format(format)), nil
	},
})

LegacyIsotimeFunc constructs a function that returns a string representation of the current date and time using golang's datetime formatting.

View Source
var LegacyStrftimeFunc = function.New(&function.Spec{
	Params: []function.Parameter{},
	VarParam: &function.Parameter{
		Name: "format",
		Type: cty.String,
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		if len(args) > 1 {
			return cty.StringVal(""), fmt.Errorf("too many values, 1 needed: %v", args)
		} else if len(args) == 0 {
			return cty.StringVal(InitTime.Format(time.RFC3339)), nil
		}
		format := args[0].AsString()
		return cty.StringVal(strftime.Format(format, InitTime)), nil
	},
})

LegacyStrftimeFunc constructs a function that returns a string representation of the current date and time using golang's strftime datetime formatting.

View Source
var LengthFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name:             "value",
			Type:             cty.DynamicPseudoType,
			AllowDynamicType: true,
			AllowUnknown:     true,
		},
	},
	Type: func(args []cty.Value) (cty.Type, error) {
		collTy := args[0].Type()
		switch {
		case collTy == cty.String || collTy.IsTupleType() || collTy.IsObjectType() || collTy.IsListType() || collTy.IsMapType() || collTy.IsSetType() || collTy == cty.DynamicPseudoType:
			return cty.Number, nil
		default:
			return cty.Number, errors.New("argument must be a string, a collection type, or a structural type")
		}
	},
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		coll := args[0]
		collTy := args[0].Type()
		switch {
		case collTy == cty.DynamicPseudoType:
			return cty.UnknownVal(cty.Number), nil
		case collTy.IsTupleType():
			l := len(collTy.TupleElementTypes())
			return cty.NumberIntVal(int64(l)), nil
		case collTy.IsObjectType():
			l := len(collTy.AttributeTypes())
			return cty.NumberIntVal(int64(l)), nil
		case collTy == cty.String:

			return stdlib.Strlen(coll)
		case collTy.IsListType() || collTy.IsSetType() || collTy.IsMapType():
			return coll.Length(), nil
		default:

			return cty.UnknownVal(cty.Number), errors.New("impossible value type for length(...)")
		}
	},
})
View Source
var TimestampFunc = function.New(&function.Spec{
	Params: []function.Parameter{},
	Type:   function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		return cty.StringVal(time.Now().UTC().Format(time.RFC3339)), nil
	},
})

TimestampFunc constructs a function that returns a string representation of the current date and time.

View Source
var TypeFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name:             "value",
			Type:             cty.DynamicPseudoType,
			AllowDynamicType: true,
			AllowUnknown:     true,
			AllowNull:        true,
		},
	},
	Type: function.StaticReturnType(TypeType),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		givenType := args[0].Type()
		return cty.CapsuleVal(TypeType, &givenType).Mark(TypeType), nil
	},
})

TypeFunc returns an encapsulated value containing its argument's type. This value is marked to allow us to limit the use of this function at the moment to only a few supported use cases.

View Source
var TypeType = cty.Capsule("type", reflect.TypeOf(cty.Type{}))
View Source
var VaultFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "path",
			Type: cty.String,
		},
		{
			Name: "key",
			Type: cty.String,
		},
	},
	Type: function.StaticReturnType(cty.String),
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		path := args[0].AsString()
		key := args[1].AsString()

		val, err := commontpl.Vault(path, key)

		return cty.StringVal(val), err
	},
})

VaultFunc constructs a function that retrieves KV secrets from HC vault

View Source
var YAML2JsonFunc = function.New(&function.Spec{
	Params: []function.Parameter{
		{
			Name: "src",
			Type: cty.String,
		},
	},
	Type: func(args []cty.Value) (cty.Type, error) {
		if !args[0].IsKnown() {
			return cty.DynamicPseudoType, nil
		}
		if args[0].IsNull() {
			return cty.NilType, function.NewArgErrorf(0, "YAML source code cannot be null")
		}
		return cty.String, nil
	},
	Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
		json, err := yaml2json.Convert([]byte(args[0].AsString()))
		if err != nil {
			return cty.NilVal, err
		}
		return cty.StringVal(string(json)), nil
	},
})

Functions

func Functions added in v0.2.0

func Functions(baseDir string) map[string]function.Function

func MakeToFunc

func MakeToFunc(wantTy cty.Type) function.Function

func Type

func Type(input []cty.Value) (cty.Value, error)

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL