Documentation ¶
Index ¶
- Variables
- func Base64Decode(str cty.Value) (cty.Value, error)
- func Base64Encode(str cty.Value) (cty.Value, error)
- func Base64Gzip(str cty.Value) (cty.Value, error)
- func Base64Sha256(str cty.Value) (cty.Value, error)
- func Base64Sha512(str cty.Value) (cty.Value, error)
- func Basename(path cty.Value) (cty.Value, error)
- func Bcrypt(str cty.Value, cost ...cty.Value) (cty.Value, error)
- func Ceil(num cty.Value) (cty.Value, error)
- func Chomp(str cty.Value) (cty.Value, error)
- func Chunklist(list, size cty.Value) (cty.Value, error)
- func CidrHost(prefix, hostnum cty.Value) (cty.Value, error)
- func CidrNetmask(prefix cty.Value) (cty.Value, error)
- func CidrSubnet(prefix, newbits, netnum cty.Value) (cty.Value, error)
- func CidrSubnets(prefix cty.Value, newbits ...cty.Value) (cty.Value, error)
- func Coalesce(args ...cty.Value) (cty.Value, error)
- func CoalesceList(args ...cty.Value) (cty.Value, error)
- func Compact(list cty.Value) (cty.Value, error)
- func Contains(list, value cty.Value) (cty.Value, error)
- func Dirname(path cty.Value) (cty.Value, error)
- func Distinct(list cty.Value) (cty.Value, error)
- func Element(list, index cty.Value) (cty.Value, error)
- func File(baseDir string, path cty.Value) (cty.Value, error)
- func FileBase64(baseDir string, path cty.Value) (cty.Value, error)
- func FileExists(baseDir string, path cty.Value) (cty.Value, error)
- func Flatten(list cty.Value) (cty.Value, error)
- func Floor(num cty.Value) (cty.Value, error)
- func Indent(spaces, str cty.Value) (cty.Value, error)
- func Index(list, value cty.Value) (cty.Value, error)
- func Join(sep cty.Value, lists ...cty.Value) (cty.Value, error)
- func Keys(inputMap cty.Value) (cty.Value, error)
- func Length(collection cty.Value) (cty.Value, error)
- func List(args ...cty.Value) (cty.Value, error)
- func Log(num, base cty.Value) (cty.Value, error)
- func Lookup(args ...cty.Value) (cty.Value, error)
- func MakeFileBase64Sha256Func(baseDir string) function.Function
- func MakeFileBase64Sha512Func(baseDir string) function.Function
- func MakeFileExistsFunc(baseDir string) function.Function
- func MakeFileFunc(baseDir string, encBase64 bool) function.Function
- func MakeFileMd5Func(baseDir string) function.Function
- func MakeFileSha1Func(baseDir string) function.Function
- func MakeFileSha256Func(baseDir string) function.Function
- func MakeFileSha512Func(baseDir string) function.Function
- func MakeTemplateFileFunc(baseDir string, funcsCb func() map[string]function.Function) function.Function
- func MakeToFunc(wantTy cty.Type) function.Function
- func Map(args ...cty.Value) (cty.Value, error)
- func Matchkeys(values, keys, searchset cty.Value) (cty.Value, error)
- func Md5(str cty.Value) (cty.Value, error)
- func Merge(maps ...cty.Value) (cty.Value, error)
- func ParseInt(num cty.Value, base cty.Value) (cty.Value, error)
- func Pathexpand(path cty.Value) (cty.Value, error)
- func Pow(num, power cty.Value) (cty.Value, error)
- func Replace(str, substr, replace cty.Value) (cty.Value, error)
- func Reverse(list cty.Value) (cty.Value, error)
- func RsaDecrypt(ciphertext, privatekey cty.Value) (cty.Value, error)
- func SetProduct(sets ...cty.Value) (cty.Value, error)
- func Sha1(str cty.Value) (cty.Value, error)
- func Sha256(str cty.Value) (cty.Value, error)
- func Sha512(str cty.Value) (cty.Value, error)
- func Signum(num cty.Value) (cty.Value, error)
- func Slice(list, start, end cty.Value) (cty.Value, error)
- func Sort(list cty.Value) (cty.Value, error)
- func Split(sep, str cty.Value) (cty.Value, error)
- func TimeAdd(timestamp cty.Value, duration cty.Value) (cty.Value, error)
- func Timestamp() (cty.Value, error)
- func Title(str cty.Value) (cty.Value, error)
- func Transpose(values cty.Value) (cty.Value, error)
- func TrimSpace(str cty.Value) (cty.Value, error)
- func URLEncode(str cty.Value) (cty.Value, error)
- func UUID() (cty.Value, error)
- func UUIDV5(namespace cty.Value, name cty.Value) (cty.Value, error)
- func Values(values cty.Value) (cty.Value, error)
- func Zipmap(keys, values cty.Value) (cty.Value, error)
Constants ¶
This section is empty.
Variables ¶
var AbsPathFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { absPath, err := filepath.Abs(args[0].AsString()) return cty.StringVal(filepath.ToSlash(absPath)), err }, })
AbsPathFunc constructs a function that converts a filesystem path to an absolute path
var Base64DecodeFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { s := args[0].AsString() sDec, err := base64.StdEncoding.DecodeString(s) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("failed to decode base64 data '%s'", s) } if !utf8.Valid([]byte(sDec)) { log.Printf("[DEBUG] the result of decoding the the provided string is not valid UTF-8: %s", sDec) return cty.UnknownVal(cty.String), fmt.Errorf("the result of decoding the the provided string is not valid UTF-8") } return cty.StringVal(string(sDec)), nil }, })
Base64DecodeFunc constructs a function that decodes a string containing a base64 sequence.
var Base64EncodeFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { return cty.StringVal(base64.StdEncoding.EncodeToString([]byte(args[0].AsString()))), nil }, })
Base64EncodeFunc constructs a function that encodes a string to a base64 sequence.
var Base64GzipFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { s := args[0].AsString() var b bytes.Buffer gz := gzip.NewWriter(&b) if _, err := gz.Write([]byte(s)); err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("failed to write gzip raw data: '%s'", s) } if err := gz.Flush(); err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("failed to flush gzip writer: '%s'", s) } if err := gz.Close(); err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("failed to close gzip writer: '%s'", s) } return cty.StringVal(base64.StdEncoding.EncodeToString(b.Bytes())), nil }, })
Base64GzipFunc constructs a function that compresses a string with gzip and then encodes the result in Base64 encoding.
var Base64Sha256Func = makeStringHashFunction(sha256.New, base64.StdEncoding.EncodeToString)
Base64Sha256Func constructs a function that computes the SHA256 hash of a given string and encodes it with Base64.
var Base64Sha512Func = makeStringHashFunction(sha512.New, base64.StdEncoding.EncodeToString)
Base64Sha512Func constructs a function that computes the SHA256 hash of a given string and encodes it with Base64.
var BasenameFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { return cty.StringVal(filepath.Base(args[0].AsString())), nil }, })
BasenameFunc constructs a function that takes a string containing a filesystem path and removes all except the last portion from it.
var BcryptFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, VarParam: &function.Parameter{ Name: "cost", Type: cty.Number, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { defaultCost := 10 if len(args) > 1 { var val int if err := gocty.FromCtyValue(args[1], &val); err != nil { return cty.UnknownVal(cty.String), err } defaultCost = val } if len(args) > 2 { return cty.UnknownVal(cty.String), fmt.Errorf("bcrypt() takes no more than two arguments") } input := args[0].AsString() out, err := bcrypt.GenerateFromPassword([]byte(input), defaultCost) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("error occured generating password %s", err.Error()) } return cty.StringVal(string(out)), nil }, })
BcryptFunc constructs a function that computes a hash of the given string using the Blowfish cipher.
var CeilFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "num", Type: cty.Number, }, }, Type: function.StaticReturnType(cty.Number), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var val float64 if err := gocty.FromCtyValue(args[0], &val); err != nil { return cty.UnknownVal(cty.String), err } return cty.NumberIntVal(int64(math.Ceil(val))), nil }, })
CeilFunc contructs a function that returns the closest whole number greater than or equal to the given value.
var ChompFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { newlines := regexp.MustCompile(`(?:\r\n?|\n)*\z`) return cty.StringVal(newlines.ReplaceAllString(args[0].AsString(), "")), nil }, })
ChompFunc constructions a function that removes newline characters at the end of a string.
var ChunklistFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "list", Type: cty.List(cty.DynamicPseudoType), }, { Name: "size", Type: cty.Number, }, }, Type: func(args []cty.Value) (cty.Type, error) { return cty.List(args[0].Type()), nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { listVal := args[0] if !listVal.IsKnown() { return cty.UnknownVal(retType), nil } if listVal.LengthInt() == 0 { return cty.ListValEmpty(listVal.Type()), nil } var size int err = gocty.FromCtyValue(args[1], &size) if err != nil { return cty.NilVal, fmt.Errorf("invalid index: %s", err) } if size < 0 { return cty.NilVal, errors.New("the size argument must be positive") } output := make([]cty.Value, 0) if size == 0 { output = append(output, listVal) return cty.ListVal(output), nil } chunk := make([]cty.Value, 0) l := args[0].LengthInt() i := 0 for it := listVal.ElementIterator(); it.Next(); { _, v := it.Element() chunk = append(chunk, v) if (i+1)%size == 0 || (i+1) == l { output = append(output, cty.ListVal(chunk)) chunk = make([]cty.Value, 0) } i++ } return cty.ListVal(output), nil }, })
ChunklistFunc constructs a function that splits a single list into fixed-size chunks, returning a list of lists.
var CidrHostFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "prefix", Type: cty.String, }, { Name: "hostnum", Type: cty.Number, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var hostNum int if err := gocty.FromCtyValue(args[1], &hostNum); err != nil { return cty.UnknownVal(cty.String), err } _, network, err := net.ParseCIDR(args[0].AsString()) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) } ip, err := cidr.Host(network, hostNum) if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(ip.String()), nil }, })
CidrHostFunc contructs a function that calculates a full host IP address within a given IP network address prefix.
var CidrNetmaskFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "prefix", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { _, network, err := net.ParseCIDR(args[0].AsString()) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) } return cty.StringVal(net.IP(network.Mask).String()), nil }, })
CidrNetmaskFunc contructs a function that converts an IPv4 address prefix given in CIDR notation into a subnet mask address.
var CidrSubnetFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "prefix", Type: cty.String, }, { Name: "newbits", Type: cty.Number, }, { Name: "netnum", Type: cty.Number, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var newbits int if err := gocty.FromCtyValue(args[1], &newbits); err != nil { return cty.UnknownVal(cty.String), err } var netnum int if err := gocty.FromCtyValue(args[2], &netnum); err != nil { return cty.UnknownVal(cty.String), err } _, network, err := net.ParseCIDR(args[0].AsString()) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("invalid CIDR expression: %s", err) } if newbits > 32 { return cty.UnknownVal(cty.String), fmt.Errorf("may not extend prefix by more than 32 bits") } newNetwork, err := cidr.Subnet(network, newbits, netnum) if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(newNetwork.String()), nil }, })
CidrSubnetFunc contructs a function that calculates a subnet address within a given IP network address prefix.
var CidrSubnetsFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "prefix", Type: cty.String, }, }, VarParam: &function.Parameter{ Name: "newbits", Type: cty.Number, }, Type: function.StaticReturnType(cty.List(cty.String)), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { _, network, err := net.ParseCIDR(args[0].AsString()) if err != nil { return cty.UnknownVal(cty.String), function.NewArgErrorf(0, "invalid CIDR expression: %s", err) } startPrefixLen, _ := network.Mask.Size() prefixLengthArgs := args[1:] if len(prefixLengthArgs) == 0 { return cty.ListValEmpty(cty.String), nil } var firstLength int if err := gocty.FromCtyValue(prefixLengthArgs[0], &firstLength); err != nil { return cty.UnknownVal(cty.String), function.NewArgError(1, err) } firstLength += startPrefixLen retVals := make([]cty.Value, len(prefixLengthArgs)) current, _ := cidr.PreviousSubnet(network, firstLength) for i, lengthArg := range prefixLengthArgs { var length int if err := gocty.FromCtyValue(lengthArg, &length); err != nil { return cty.UnknownVal(cty.String), function.NewArgError(i+1, err) } if length < 1 { return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "must extend prefix by at least one bit") } if length > 32 { return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "may not extend prefix by more than 32 bits") } length += startPrefixLen if length > (len(network.IP) * 8) { protocol := "IP" switch len(network.IP) * 8 { case 32: protocol = "IPv4" case 128: protocol = "IPv6" } return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "would extend prefix to %d bits, which is too long for an %s address", length, protocol) } next, rollover := cidr.NextSubnet(current, length) if rollover || !network.Contains(next.IP) { return cty.UnknownVal(cty.String), function.NewArgErrorf(i+1, "not enough remaining address space for a subnet with a prefix of %d bits after %s", length, current.String()) } current = next retVals[i] = cty.StringVal(current.String()) } return cty.ListVal(retVals), nil }, })
CidrSubnetsFunc is similar to CidrSubnetFunc but calculates many consecutive subnet addresses at once, rather than just a single subnet extension.
var CoalesceFunc = function.New(&function.Spec{ Params: []function.Parameter{}, VarParam: &function.Parameter{ Name: "vals", Type: cty.DynamicPseudoType, AllowUnknown: true, AllowDynamicType: true, AllowNull: true, }, Type: func(args []cty.Value) (ret cty.Type, err error) { argTypes := make([]cty.Type, len(args)) for i, val := range args { argTypes[i] = val.Type() } retType, _ := convert.UnifyUnsafe(argTypes) if retType == cty.NilType { return cty.NilType, errors.New("all arguments must have the same type") } return retType, nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { for _, argVal := range args { argVal, _ = convert.Convert(argVal, retType) if !argVal.IsKnown() { return cty.UnknownVal(retType), nil } if argVal.IsNull() { continue } if retType == cty.String && argVal.RawEquals(cty.StringVal("")) { continue } return argVal, nil } return cty.NilVal, errors.New("no non-null, non-empty-string arguments") }, })
CoalesceFunc constructs a function that takes any number of arguments and returns the first one that isn't empty. This function was copied from go-cty stdlib and modified so that it returns the first *non-empty* non-null element from a sequence, instead of merely the first non-null.
var CoalesceListFunc = function.New(&function.Spec{ Params: []function.Parameter{}, VarParam: &function.Parameter{ Name: "vals", Type: cty.DynamicPseudoType, AllowUnknown: true, AllowDynamicType: true, AllowNull: true, }, Type: func(args []cty.Value) (ret cty.Type, err error) { if len(args) == 0 { return cty.NilType, errors.New("at least one argument is required") } argTypes := make([]cty.Type, len(args)) for i, arg := range args { if !arg.IsKnown() { return cty.DynamicPseudoType, nil } ty := arg.Type() if !ty.IsListType() && !ty.IsTupleType() { return cty.NilType, errors.New("coalescelist arguments must be lists or tuples") } argTypes[i] = arg.Type() } last := argTypes[0] for _, next := range argTypes[1:] { if !next.Equals(last) { return cty.DynamicPseudoType, nil } } return last, nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { for _, arg := range args { if !arg.IsKnown() { return cty.UnknownVal(retType), nil } if arg.LengthInt() > 0 { return arg, nil } } return cty.NilVal, errors.New("no non-null arguments") }, })
CoalesceListFunc constructs a function that takes any number of list arguments and returns the first one that isn't empty.
var CompactFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "list", Type: cty.List(cty.String), }, }, Type: function.StaticReturnType(cty.List(cty.String)), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { listVal := args[0] if !listVal.IsWhollyKnown() { return cty.UnknownVal(retType), nil } var outputList []cty.Value for it := listVal.ElementIterator(); it.Next(); { _, v := it.Element() if v.IsNull() || v.AsString() == "" { continue } outputList = append(outputList, v) } if len(outputList) == 0 { return cty.ListValEmpty(cty.String), nil } return cty.ListVal(outputList), nil }, })
CompactFunc constructs a function that takes a list of strings and returns a new list with any empty string elements removed.
var ContainsFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "list", Type: cty.DynamicPseudoType, }, { Name: "value", Type: cty.DynamicPseudoType, }, }, Type: function.StaticReturnType(cty.Bool), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { arg := args[0] ty := arg.Type() if !ty.IsListType() && !ty.IsTupleType() && !ty.IsSetType() { return cty.NilVal, errors.New("argument must be list, tuple, or set") } _, err = Index(cty.TupleVal(arg.AsValueSlice()), args[1]) if err != nil { return cty.False, nil } return cty.True, nil }, })
ContainsFunc constructs a function that determines whether a given list or set contains a given single value as one of its elements.
var DirnameFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { return cty.StringVal(filepath.Dir(args[0].AsString())), nil }, })
DirnameFunc constructs a function that takes a string containing a filesystem path and removes the last portion from it.
var DistinctFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "list", Type: cty.List(cty.DynamicPseudoType), }, }, Type: func(args []cty.Value) (cty.Type, error) { return args[0].Type(), nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { listVal := args[0] if !listVal.IsWhollyKnown() { return cty.UnknownVal(retType), nil } var list []cty.Value for it := listVal.ElementIterator(); it.Next(); { _, v := it.Element() list, err = appendIfMissing(list, v) if err != nil { return cty.NilVal, err } } if len(list) == 0 { return cty.ListValEmpty(retType.ElementType()), nil } return cty.ListVal(list), nil }, })
DistinctFunc constructs a function that takes a list and returns a new list with any duplicate elements removed.
var ElementFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "list", Type: cty.DynamicPseudoType, }, { Name: "index", Type: cty.Number, }, }, Type: func(args []cty.Value) (cty.Type, error) { list := args[0] listTy := list.Type() switch { case listTy.IsListType(): return listTy.ElementType(), nil case listTy.IsTupleType(): if !args[1].IsKnown() { return cty.DynamicPseudoType, nil } etys := listTy.TupleElementTypes() var index int err := gocty.FromCtyValue(args[1], &index) if err != nil { return cty.DynamicPseudoType, fmt.Errorf("invalid index: %s", err) } if len(etys) == 0 { return cty.DynamicPseudoType, errors.New("cannot use element function with an empty list") } index = index % len(etys) return etys[index], nil default: return cty.DynamicPseudoType, fmt.Errorf("cannot read elements from %s", listTy.FriendlyName()) } }, Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { var index int err := gocty.FromCtyValue(args[1], &index) if err != nil { return cty.DynamicVal, fmt.Errorf("invalid index: %s", err) } if !args[0].IsKnown() { return cty.UnknownVal(retType), nil } l := args[0].LengthInt() if l == 0 { return cty.DynamicVal, errors.New("cannot use element function with an empty list") } index = index % l return args[0].Index(cty.NumberIntVal(int64(index))), nil }, })
var FlattenFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "list", Type: cty.DynamicPseudoType, }, }, Type: func(args []cty.Value) (cty.Type, error) { if !args[0].IsWhollyKnown() { return cty.DynamicPseudoType, nil } argTy := args[0].Type() if !argTy.IsListType() && !argTy.IsSetType() && !argTy.IsTupleType() { return cty.NilType, errors.New("can only flatten lists, sets and tuples") } retVal, known := flattener(args[0]) if !known { return cty.DynamicPseudoType, nil } tys := make([]cty.Type, len(retVal)) for i, ty := range retVal { tys[i] = ty.Type() } return cty.Tuple(tys), nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { inputList := args[0] if inputList.LengthInt() == 0 { return cty.EmptyTupleVal, nil } out, known := flattener(inputList) if !known { return cty.UnknownVal(retType), nil } return cty.TupleVal(out), nil }, })
FlattenFunc constructs a function that takes a list and replaces any elements that are lists with a flattened sequence of the list contents.
var FloorFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "num", Type: cty.Number, }, }, Type: function.StaticReturnType(cty.Number), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var val float64 if err := gocty.FromCtyValue(args[0], &val); err != nil { return cty.UnknownVal(cty.String), err } return cty.NumberIntVal(int64(math.Floor(val))), nil }, })
FloorFunc contructs a function that returns the closest whole number lesser than or equal to the given value.
var IndentFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "spaces", Type: cty.Number, }, { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var spaces int if err := gocty.FromCtyValue(args[0], &spaces); err != nil { return cty.UnknownVal(cty.String), err } data := args[1].AsString() pad := strings.Repeat(" ", spaces) return cty.StringVal(strings.Replace(data, "\n", "\n"+pad, -1)), nil }, })
IndentFunc constructions a function that adds a given number of spaces to the beginnings of all but the first line in a given multi-line string.
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.
var JoinFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "separator", Type: cty.String, }, }, VarParam: &function.Parameter{ Name: "lists", Type: cty.List(cty.String), }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { sep := args[0].AsString() listVals := args[1:] if len(listVals) < 1 { return cty.UnknownVal(cty.String), fmt.Errorf("at least one list is required") } l := 0 for _, list := range listVals { if !list.IsWhollyKnown() { return cty.UnknownVal(cty.String), nil } l += list.LengthInt() } items := make([]string, 0, l) for ai, list := range listVals { ei := 0 for it := list.ElementIterator(); it.Next(); { _, val := it.Element() if val.IsNull() { if len(listVals) > 1 { return cty.UnknownVal(cty.String), function.NewArgErrorf(ai+1, "element %d of list %d is null; cannot concatenate null values", ei, ai+1) } return cty.UnknownVal(cty.String), function.NewArgErrorf(ai+1, "element %d is null; cannot concatenate null values", ei) } items = append(items, val.AsString()) ei++ } } return cty.StringVal(strings.Join(items, sep)), nil }, })
var KeysFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "inputMap", Type: cty.DynamicPseudoType, AllowUnknown: true, }, }, Type: func(args []cty.Value) (cty.Type, error) { ty := args[0].Type() switch { case ty.IsMapType(): return cty.List(cty.String), nil case ty.IsObjectType(): atys := ty.AttributeTypes() if len(atys) == 0 { return cty.EmptyTuple, nil } etys := make([]cty.Type, len(atys)) for i := range etys { etys[i] = cty.String } return cty.Tuple(etys), nil default: return cty.DynamicPseudoType, function.NewArgErrorf(0, "must have map or object type") } }, Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { m := args[0] var keys []cty.Value switch { case m.Type().IsObjectType(): // In this case we allow unknown values so we must work only with // the attribute _types_, not with the value itself. var names []string for name := range m.Type().AttributeTypes() { names = append(names, name) } sort.Strings(names) if len(names) == 0 { return cty.EmptyTupleVal, nil } keys = make([]cty.Value, len(names)) for i, name := range names { keys[i] = cty.StringVal(name) } return cty.TupleVal(keys), nil default: if !m.IsKnown() { return cty.UnknownVal(retType), nil } for it := args[0].ElementIterator(); it.Next(); { k, _ := it.Element() keys = append(keys, k) } if len(keys) == 0 { return cty.ListValEmpty(cty.String), nil } return cty.ListVal(keys), nil } }, })
KeysFunc constructs a function that takes a map and returns a sorted list of the map keys.
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(...)") } }, })
var ListFunc = function.New(&function.Spec{ Params: []function.Parameter{}, VarParam: &function.Parameter{ Name: "vals", Type: cty.DynamicPseudoType, AllowUnknown: true, AllowDynamicType: true, AllowNull: true, }, Type: func(args []cty.Value) (ret cty.Type, err error) { if len(args) == 0 { return cty.NilType, errors.New("at least one argument is required") } argTypes := make([]cty.Type, len(args)) for i, arg := range args { argTypes[i] = arg.Type() } retType, _ := convert.UnifyUnsafe(argTypes) if retType == cty.NilType { return cty.NilType, errors.New("all arguments must have the same type") } return cty.List(retType), nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { newList := make([]cty.Value, 0, len(args)) for _, arg := range args { arg, _ = convert.Convert(arg, retType.ElementType()) newList = append(newList, arg) } return cty.ListVal(newList), nil }, })
ListFunc constructs a function that takes an arbitrary number of arguments and returns a list containing those values in the same order.
This function is deprecated in Terraform v0.12
var LogFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "num", Type: cty.Number, }, { Name: "base", Type: cty.Number, }, }, Type: function.StaticReturnType(cty.Number), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var num float64 if err := gocty.FromCtyValue(args[0], &num); err != nil { return cty.UnknownVal(cty.String), err } var base float64 if err := gocty.FromCtyValue(args[1], &base); err != nil { return cty.UnknownVal(cty.String), err } return cty.NumberFloatVal(math.Log(num) / math.Log(base)), nil }, })
LogFunc contructs a function that returns the logarithm of a given number in a given base.
var LookupFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "inputMap", Type: cty.DynamicPseudoType, }, { Name: "key", Type: cty.String, }, }, VarParam: &function.Parameter{ Name: "default", Type: cty.DynamicPseudoType, AllowUnknown: true, AllowDynamicType: true, AllowNull: true, }, Type: func(args []cty.Value) (ret cty.Type, err error) { if len(args) < 1 || len(args) > 3 { return cty.NilType, fmt.Errorf("lookup() takes two or three arguments, got %d", len(args)) } ty := args[0].Type() switch { case ty.IsObjectType(): if !args[1].IsKnown() { return cty.DynamicPseudoType, nil } key := args[1].AsString() if ty.HasAttribute(key) { return args[0].GetAttr(key).Type(), nil } else if len(args) == 3 { return args[2].Type(), nil } return cty.DynamicPseudoType, function.NewArgErrorf(0, "the given object has no attribute %q", key) case ty.IsMapType(): if len(args) == 3 { _, err = convert.Convert(args[2], ty.ElementType()) if err != nil { return cty.NilType, function.NewArgErrorf(2, "the default value must have the same type as the map elements") } } return ty.ElementType(), nil default: return cty.NilType, function.NewArgErrorf(0, "lookup() requires a map as the first argument") } }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var defaultVal cty.Value defaultValueSet := false if len(args) == 3 { defaultVal = args[2] defaultValueSet = true } mapVar := args[0] lookupKey := args[1].AsString() if !mapVar.IsWhollyKnown() { return cty.UnknownVal(retType), nil } if mapVar.Type().IsObjectType() { if mapVar.Type().HasAttribute(lookupKey) { return mapVar.GetAttr(lookupKey), nil } } else if mapVar.HasIndex(cty.StringVal(lookupKey)) == cty.True { return mapVar.Index(cty.StringVal(lookupKey)), nil } if defaultValueSet { defaultVal, err = convert.Convert(defaultVal, retType) if err != nil { return cty.NilVal, err } return defaultVal, nil } return cty.UnknownVal(cty.DynamicPseudoType), fmt.Errorf( "lookup failed to find '%s'", lookupKey) }, })
LookupFunc constructs a function that performs dynamic lookups of map types.
var MapFunc = function.New(&function.Spec{ Params: []function.Parameter{}, VarParam: &function.Parameter{ Name: "vals", Type: cty.DynamicPseudoType, AllowUnknown: true, AllowDynamicType: true, AllowNull: true, }, Type: func(args []cty.Value) (ret cty.Type, err error) { if len(args) < 2 || len(args)%2 != 0 { return cty.NilType, fmt.Errorf("map requires an even number of two or more arguments, got %d", len(args)) } argTypes := make([]cty.Type, len(args)/2) index := 0 for i := 0; i < len(args); i += 2 { argTypes[index] = args[i+1].Type() index++ } valType, _ := convert.UnifyUnsafe(argTypes) if valType == cty.NilType { return cty.NilType, errors.New("all arguments must have the same type") } return cty.Map(valType), nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { for _, arg := range args { if !arg.IsWhollyKnown() { return cty.UnknownVal(retType), nil } } outputMap := make(map[string]cty.Value) for i := 0; i < len(args); i += 2 { key := args[i].AsString() err := gocty.FromCtyValue(args[i], &key) if err != nil { return cty.NilVal, err } val := args[i+1] var variable cty.Value err = gocty.FromCtyValue(val, &variable) if err != nil { return cty.NilVal, err } variable, _ = convert.Convert(variable, retType.ElementType()) if _, ok := outputMap[key]; ok { return cty.NilVal, fmt.Errorf("argument %d is a duplicate key: %q", i+1, key) } outputMap[key] = variable } return cty.MapVal(outputMap), nil }, })
MapFunc constructs a function that takes an even number of arguments and returns a map whose elements are constructed from consecutive pairs of arguments.
This function is deprecated in Terraform v0.12
var MatchkeysFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "values", Type: cty.List(cty.DynamicPseudoType), }, { Name: "keys", Type: cty.List(cty.DynamicPseudoType), }, { Name: "searchset", Type: cty.List(cty.DynamicPseudoType), }, }, Type: func(args []cty.Value) (cty.Type, error) { ty, _ := convert.UnifyUnsafe([]cty.Type{args[1].Type(), args[2].Type()}) if ty == cty.NilType { return cty.NilType, errors.New("keys and searchset must be of the same type") } return args[0].Type(), nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { if !args[0].IsKnown() { return cty.UnknownVal(cty.List(retType.ElementType())), nil } if args[0].LengthInt() != args[1].LengthInt() { return cty.ListValEmpty(retType.ElementType()), errors.New("length of keys and values should be equal") } output := make([]cty.Value, 0) values := args[0] ty, _ := convert.UnifyUnsafe([]cty.Type{args[1].Type(), args[2].Type()}) keys, _ := convert.Convert(args[1], ty) searchset, _ := convert.Convert(args[2], ty) if searchset.LengthInt() == 0 { return cty.ListValEmpty(retType.ElementType()), nil } if !values.IsWhollyKnown() || !keys.IsWhollyKnown() { return cty.UnknownVal(retType), nil } i := 0 for it := keys.ElementIterator(); it.Next(); { _, key := it.Element() for iter := searchset.ElementIterator(); iter.Next(); { _, search := iter.Element() eq, err := stdlib.Equal(key, search) if err != nil { return cty.NilVal, err } if !eq.IsKnown() { return cty.ListValEmpty(retType.ElementType()), nil } if eq.True() { v := values.Index(cty.NumberIntVal(int64(i))) output = append(output, v) break } } i++ } if len(output) == 0 { return cty.ListValEmpty(retType.ElementType()), nil } return cty.ListVal(output), nil }, })
MatchkeysFunc constructs a function that constructs a new list by taking a subset of elements from one list whose indexes match the corresponding indexes of values in another list.
var Md5Func = makeStringHashFunction(md5.New, hex.EncodeToString)
Md5Func constructs a function that computes the MD5 hash of a given string and encodes it with hexadecimal digits.
var MergeFunc = function.New(&function.Spec{ Params: []function.Parameter{}, VarParam: &function.Parameter{ Name: "maps", Type: cty.DynamicPseudoType, AllowDynamicType: true, }, Type: function.StaticReturnType(cty.DynamicPseudoType), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { outputMap := make(map[string]cty.Value) for _, arg := range args { if !arg.IsWhollyKnown() { return cty.UnknownVal(retType), nil } if !arg.Type().IsObjectType() && !arg.Type().IsMapType() { return cty.NilVal, fmt.Errorf("arguments must be maps or objects, got %#v", arg.Type().FriendlyName()) } for it := arg.ElementIterator(); it.Next(); { k, v := it.Element() outputMap[k.AsString()] = v } } return cty.ObjectVal(outputMap), nil }, })
MergeFunc constructs a function that takes an arbitrary number of maps and returns a single map that contains a merged set of elements from all of the maps.
If more than one given map defines the same key then the one that is later in the argument sequence takes precedence.
var ParseIntFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "number", Type: cty.DynamicPseudoType, }, { Name: "base", Type: cty.Number, }, }, Type: func(args []cty.Value) (cty.Type, error) { if !args[0].Type().Equals(cty.String) { return cty.Number, function.NewArgErrorf(0, "first argument must be a string, not %s", args[0].Type().FriendlyName()) } return cty.Number, nil }, Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { var numstr string var base int var err error if err = gocty.FromCtyValue(args[0], &numstr); err != nil { return cty.UnknownVal(cty.String), function.NewArgError(0, err) } if err = gocty.FromCtyValue(args[1], &base); err != nil { return cty.UnknownVal(cty.Number), function.NewArgError(1, err) } if base < 2 || base > 62 { return cty.UnknownVal(cty.Number), function.NewArgErrorf( 1, "base must be a whole number between 2 and 62 inclusive", ) } num, ok := (&big.Int{}).SetString(numstr, base) if !ok { return cty.UnknownVal(cty.Number), function.NewArgErrorf( 0, "cannot parse %q as a base %d integer", numstr, base, ) } parsedNum := cty.NumberVal((&big.Float{}).SetInt(num)) return parsedNum, nil }, })
ParseIntFunc contructs a function that parses a string argument and returns an integer of the specified base.
var PathExpandFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "path", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { homePath, err := homedir.Expand(args[0].AsString()) return cty.StringVal(homePath), err }, })
PathExpandFunc constructs a function that expands a leading ~ character to the current user's home directory.
var PowFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "num", Type: cty.Number, }, { Name: "power", Type: cty.Number, }, }, Type: function.StaticReturnType(cty.Number), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var num float64 if err := gocty.FromCtyValue(args[0], &num); err != nil { return cty.UnknownVal(cty.String), err } var power float64 if err := gocty.FromCtyValue(args[1], &power); err != nil { return cty.UnknownVal(cty.String), err } return cty.NumberFloatVal(math.Pow(num, power)), nil }, })
PowFunc contructs a function that returns the logarithm of a given number in a given base.
var ReplaceFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, { Name: "substr", Type: cty.String, }, { Name: "replace", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { str := args[0].AsString() substr := args[1].AsString() replace := args[2].AsString() if len(substr) > 1 && substr[0] == '/' && substr[len(substr)-1] == '/' { re, err := regexp.Compile(substr[1 : len(substr)-1]) if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(re.ReplaceAllString(str, replace)), nil } return cty.StringVal(strings.Replace(str, substr, replace, -1)), nil }, })
ReplaceFunc constructions a function that searches a given string for another given substring, and replaces each occurence with a given replacement string.
var ReverseFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "list", Type: cty.DynamicPseudoType, }, }, Type: func(args []cty.Value) (cty.Type, error) { argTy := args[0].Type() switch { case argTy.IsTupleType(): argTys := argTy.TupleElementTypes() retTys := make([]cty.Type, len(argTys)) for i, ty := range argTys { retTys[len(retTys)-i-1] = ty } return cty.Tuple(retTys), nil case argTy.IsListType(), argTy.IsSetType(): return cty.List(argTy.ElementType()), nil default: return cty.NilType, function.NewArgErrorf(0, "can only reverse list or tuple values, not %s", argTy.FriendlyName()) } }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { in := args[0].AsValueSlice() outVals := make([]cty.Value, len(in)) for i, v := range in { outVals[len(outVals)-i-1] = v } switch { case retType.IsTupleType(): return cty.TupleVal(outVals), nil default: if len(outVals) == 0 { return cty.ListValEmpty(retType.ElementType()), nil } return cty.ListVal(outVals), nil } }, })
ReverseFunc takes a sequence and produces a new sequence of the same length with all of the same elements as the given sequence but in reverse order.
var RsaDecryptFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "ciphertext", Type: cty.String, }, { Name: "privatekey", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { s := args[0].AsString() key := args[1].AsString() b, err := base64.StdEncoding.DecodeString(s) if err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("failed to decode input %q: cipher text must be base64-encoded", s) } block, _ := pem.Decode([]byte(key)) if block == nil { return cty.UnknownVal(cty.String), fmt.Errorf("failed to parse key: no key found") } if block.Headers["Proc-Type"] == "4,ENCRYPTED" { return cty.UnknownVal(cty.String), fmt.Errorf( "failed to parse key: password protected keys are not supported. Please decrypt the key prior to use", ) } x509Key, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return cty.UnknownVal(cty.String), err } out, err := rsa.DecryptPKCS1v15(nil, x509Key, b) if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(string(out)), nil }, })
RsaDecryptFunc constructs a function that decrypts an RSA-encrypted ciphertext.
var SetProductFunc = function.New(&function.Spec{ Params: []function.Parameter{}, VarParam: &function.Parameter{ Name: "sets", Type: cty.DynamicPseudoType, }, Type: func(args []cty.Value) (retType cty.Type, err error) { if len(args) < 2 { return cty.NilType, errors.New("at least two arguments are required") } listCount := 0 elemTys := make([]cty.Type, len(args)) for i, arg := range args { aty := arg.Type() switch { case aty.IsSetType(): elemTys[i] = aty.ElementType() case aty.IsListType(): elemTys[i] = aty.ElementType() listCount++ case aty.IsTupleType(): allEtys := aty.TupleElementTypes() if len(allEtys) == 0 { elemTys[i] = cty.DynamicPseudoType listCount++ break } ety, _ := convert.UnifyUnsafe(allEtys) if ety == cty.NilType { return cty.NilType, function.NewArgErrorf(i, "all elements must be of the same type") } elemTys[i] = ety listCount++ default: return cty.NilType, function.NewArgErrorf(i, "a set or a list is required") } } if listCount == len(args) { return cty.List(cty.Tuple(elemTys)), nil } return cty.Set(cty.Tuple(elemTys)), nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { ety := retType.ElementType() total := 1 for _, arg := range args { total *= arg.LengthInt() } if total == 0 { if retType.IsListType() { return cty.ListValEmpty(ety), nil } return cty.SetValEmpty(ety), nil } subEtys := ety.TupleElementTypes() product := make([][]cty.Value, total) b := make([]cty.Value, total*len(args)) n := make([]int, len(args)) s := 0 argVals := make([][]cty.Value, len(args)) for i, arg := range args { argVals[i] = arg.AsValueSlice() } for i := range product { e := s + len(args) pi := b[s:e] product[i] = pi s = e for j, n := range n { val := argVals[j][n] ty := subEtys[j] if !val.Type().Equals(ty) { var err error val, err = convert.Convert(val, ty) if err != nil { return cty.NilVal, fmt.Errorf("failed to convert argVals[%d][%d] to %s; this is a bug in Terraform", j, n, ty.FriendlyName()) } } pi[j] = val } for j := len(n) - 1; j >= 0; j-- { n[j]++ if n[j] < len(argVals[j]) { break } n[j] = 0 } } productVals := make([]cty.Value, total) for i, vals := range product { productVals[i] = cty.TupleVal(vals) } if retType.IsListType() { return cty.ListVal(productVals), nil } return cty.SetVal(productVals), nil }, })
SetProductFunc calculates the cartesian product of two or more sets or sequences. If the arguments are all lists then the result is a list of tuples, preserving the ordering of all of the input lists. Otherwise the result is a set of tuples.
var Sha1Func = makeStringHashFunction(sha1.New, hex.EncodeToString)
Sha1Func contructs a function that computes the SHA1 hash of a given string and encodes it with hexadecimal digits.
var Sha256Func = makeStringHashFunction(sha256.New, hex.EncodeToString)
Sha256Func contructs a function that computes the SHA256 hash of a given string and encodes it with hexadecimal digits.
var Sha512Func = makeStringHashFunction(sha512.New, hex.EncodeToString)
Sha512Func contructs a function that computes the SHA512 hash of a given string and encodes it with hexadecimal digits.
var SignumFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "num", Type: cty.Number, }, }, Type: function.StaticReturnType(cty.Number), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var num int if err := gocty.FromCtyValue(args[0], &num); err != nil { return cty.UnknownVal(cty.String), err } switch { case num < 0: return cty.NumberIntVal(-1), nil case num > 0: return cty.NumberIntVal(+1), nil default: return cty.NumberIntVal(0), nil } }, })
SignumFunc contructs a function that returns the closest whole number greater than or equal to the given value.
var SliceFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "list", Type: cty.DynamicPseudoType, }, { Name: "start_index", Type: cty.Number, }, { Name: "end_index", Type: cty.Number, }, }, Type: func(args []cty.Value) (cty.Type, error) { arg := args[0] argTy := arg.Type() if argTy.IsSetType() { return cty.NilType, function.NewArgErrorf(0, "cannot slice a set, because its elements do not have indices; use the tolist function to force conversion to list if the ordering of the result is not important") } if !argTy.IsListType() && !argTy.IsTupleType() { return cty.NilType, function.NewArgErrorf(0, "must be a list or tuple value") } startIndex, endIndex, idxsKnown, err := sliceIndexes(args) if err != nil { return cty.NilType, err } if argTy.IsListType() { return argTy, nil } if !idxsKnown { return cty.DynamicPseudoType, nil } return cty.Tuple(argTy.TupleElementTypes()[startIndex:endIndex]), nil }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { inputList := args[0] if retType == cty.DynamicPseudoType { return cty.DynamicVal, nil } startIndex, endIndex, _, err := sliceIndexes(args) if err != nil { return cty.NilVal, err } if endIndex-startIndex == 0 { if retType.IsTupleType() { return cty.EmptyTupleVal, nil } return cty.ListValEmpty(retType.ElementType()), nil } outputList := inputList.AsValueSlice()[startIndex:endIndex] if retType.IsTupleType() { return cty.TupleVal(outputList), nil } return cty.ListVal(outputList), nil }, })
SliceFunc constructs a function that extracts some consecutive elements from within a list.
var SortFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "list", Type: cty.List(cty.String), }, }, Type: function.StaticReturnType(cty.List(cty.String)), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { listVal := args[0] if !listVal.IsWhollyKnown() { return cty.UnknownVal(retType), nil } if listVal.LengthInt() == 0 { return listVal, nil } list := make([]string, 0, listVal.LengthInt()) for it := listVal.ElementIterator(); it.Next(); { iv, v := it.Element() if v.IsNull() { return cty.UnknownVal(retType), fmt.Errorf("given list element %s is null; a null string cannot be sorted", iv.AsBigFloat().String()) } list = append(list, v.AsString()) } sort.Strings(list) retVals := make([]cty.Value, len(list)) for i, s := range list { retVals[i] = cty.StringVal(s) } return cty.ListVal(retVals), nil }, })
var SplitFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "separator", Type: cty.String, }, { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.List(cty.String)), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { sep := args[0].AsString() str := args[1].AsString() elems := strings.Split(str, sep) elemVals := make([]cty.Value, len(elems)) for i, s := range elems { elemVals[i] = cty.StringVal(s) } if len(elemVals) == 0 { return cty.ListValEmpty(cty.String), nil } return cty.ListVal(elemVals), nil }, })
var TimeAddFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "timestamp", Type: cty.String, }, { Name: "duration", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { ts, err := time.Parse(time.RFC3339, args[0].AsString()) if err != nil { return cty.UnknownVal(cty.String), err } duration, err := time.ParseDuration(args[1].AsString()) if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(ts.Add(duration).Format(time.RFC3339)), nil }, })
TimeAddFunc constructs a function that adds a duration to a timestamp, returning a new timestamp.
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.
var TitleFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { return cty.StringVal(strings.Title(args[0].AsString())), nil }, })
TitleFunc constructions a function that converts the first letter of each word in the given string to uppercase.
var TransposeFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "values", Type: cty.Map(cty.List(cty.String)), }, }, Type: function.StaticReturnType(cty.Map(cty.List(cty.String))), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { inputMap := args[0] if !inputMap.IsWhollyKnown() { return cty.UnknownVal(retType), nil } outputMap := make(map[string]cty.Value) tmpMap := make(map[string][]string) for it := inputMap.ElementIterator(); it.Next(); { inKey, inVal := it.Element() for iter := inVal.ElementIterator(); iter.Next(); { _, val := iter.Element() if !val.Type().Equals(cty.String) { return cty.MapValEmpty(cty.List(cty.String)), errors.New("input must be a map of lists of strings") } outKey := val.AsString() if _, ok := tmpMap[outKey]; !ok { tmpMap[outKey] = make([]string, 0) } outVal := tmpMap[outKey] outVal = append(outVal, inKey.AsString()) sort.Strings(outVal) tmpMap[outKey] = outVal } } for outKey, outVal := range tmpMap { values := make([]cty.Value, 0) for _, v := range outVal { values = append(values, cty.StringVal(v)) } outputMap[outKey] = cty.ListVal(values) } return cty.MapVal(outputMap), nil }, })
TransposeFunc contructs a function that takes a map of lists of strings and TransposeFunc constructs a function that takes a map of lists of strings and swaps the keys and values to produce a new map of lists of strings.
var TrimSpaceFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { return cty.StringVal(strings.TrimSpace(args[0].AsString())), nil }, })
TrimSpaceFunc constructions a function that removes any space characters from the start and end of the given string.
var URLEncodeFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "str", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) { return cty.StringVal(url.QueryEscape(args[0].AsString())), nil }, })
URLEncodeFunc constructs a function that applies URL encoding to a given string.
var UUIDFunc = function.New(&function.Spec{ Params: []function.Parameter{}, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { result, err := uuid.GenerateUUID() if err != nil { return cty.UnknownVal(cty.String), err } return cty.StringVal(result), nil }, })
var UUIDV5Func = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "namespace", Type: cty.String, }, { Name: "name", Type: cty.String, }, }, Type: function.StaticReturnType(cty.String), Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { var namespace uuidv5.UUID switch { case args[0].AsString() == "dns": namespace = uuidv5.NameSpaceDNS case args[0].AsString() == "url": namespace = uuidv5.NameSpaceURL case args[0].AsString() == "oid": namespace = uuidv5.NameSpaceOID case args[0].AsString() == "x500": namespace = uuidv5.NameSpaceX500 default: if namespace, err = uuidv5.Parse(args[0].AsString()); err != nil { return cty.UnknownVal(cty.String), fmt.Errorf("uuidv5() doesn't support namespace %s (%v)", args[0].AsString(), err) } } val := args[1].AsString() return cty.StringVal(uuidv5.NewSHA1(namespace, []byte(val)).String()), nil }, })
var ValuesFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "values", Type: cty.DynamicPseudoType, }, }, Type: func(args []cty.Value) (ret cty.Type, err error) { ty := args[0].Type() if ty.IsMapType() { return cty.List(ty.ElementType()), nil } else if ty.IsObjectType() { atys := ty.AttributeTypes() if len(atys) == 0 { return cty.EmptyTuple, nil } attrNames := make([]string, 0, len(atys)) for name := range atys { attrNames = append(attrNames, name) } sort.Strings(attrNames) tys := make([]cty.Type, len(attrNames)) for i, name := range attrNames { tys[i] = atys[name] } return cty.Tuple(tys), nil } return cty.NilType, errors.New("values() requires a map as the first argument") }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { mapVar := args[0] // We can just iterate the map/object value here because cty guarantees // that these types always iterate in key lexicographical order. var values []cty.Value for it := mapVar.ElementIterator(); it.Next(); { _, val := it.Element() values = append(values, val) } if retType.IsTupleType() { return cty.TupleVal(values), nil } if len(values) == 0 { return cty.ListValEmpty(retType.ElementType()), nil } return cty.ListVal(values), nil }, })
ValuesFunc constructs a function that returns a list of the map values, in the order of the sorted keys.
var ZipmapFunc = function.New(&function.Spec{ Params: []function.Parameter{ { Name: "keys", Type: cty.List(cty.String), }, { Name: "values", Type: cty.DynamicPseudoType, }, }, Type: func(args []cty.Value) (ret cty.Type, err error) { keys := args[0] values := args[1] valuesTy := values.Type() switch { case valuesTy.IsListType(): return cty.Map(values.Type().ElementType()), nil case valuesTy.IsTupleType(): if !keys.IsWhollyKnown() { return cty.DynamicPseudoType, nil } keysRaw := keys.AsValueSlice() valueTypesRaw := valuesTy.TupleElementTypes() if len(keysRaw) != len(valueTypesRaw) { return cty.NilType, fmt.Errorf("number of keys (%d) does not match number of values (%d)", len(keysRaw), len(valueTypesRaw)) } atys := make(map[string]cty.Type, len(valueTypesRaw)) for i, keyVal := range keysRaw { if keyVal.IsNull() { return cty.NilType, fmt.Errorf("keys list has null value at index %d", i) } key := keyVal.AsString() atys[key] = valueTypesRaw[i] } return cty.Object(atys), nil default: return cty.NilType, errors.New("values argument must be a list or tuple value") } }, Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) { keys := args[0] values := args[1] if !keys.IsWhollyKnown() { return cty.UnknownVal(retType), nil } if keys.LengthInt() != values.LengthInt() { return cty.NilVal, fmt.Errorf("number of keys (%d) does not match number of values (%d)", keys.LengthInt(), values.LengthInt()) } output := make(map[string]cty.Value) i := 0 for it := keys.ElementIterator(); it.Next(); { _, v := it.Element() val := values.Index(cty.NumberIntVal(int64(i))) output[v.AsString()] = val i++ } switch { case retType.IsMapType(): if len(output) == 0 { return cty.MapValEmpty(retType.ElementType()), nil } return cty.MapVal(output), nil case retType.IsObjectType(): return cty.ObjectVal(output), nil default: return cty.NilVal, fmt.Errorf("internally selected incorrect result type %s (this is a bug)", retType.FriendlyName()) } }, })
ZipmapFunc constructs a function that constructs a map from a list of keys and a corresponding list of values.
Functions ¶
func Base64Decode ¶
Base64Decode decodes a string containing a base64 sequence.
Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4.
Strings in the Terraform language are sequences of unicode characters rather than bytes, so this function will also interpret the resulting bytes as UTF-8. If the bytes after Base64 decoding are _not_ valid UTF-8, this function produces an error.
func Base64Encode ¶
Base64Encode applies Base64 encoding to a string.
Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4.
Strings in the Terraform language are sequences of unicode characters rather than bytes, so this function will first encode the characters from the string as UTF-8, and then apply Base64 encoding to the result.
func Base64Gzip ¶
Base64Gzip compresses a string with gzip and then encodes the result in Base64 encoding.
Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4.
Strings in the Terraform language are sequences of unicode characters rather than bytes, so this function will first encode the characters from the string as UTF-8, then apply gzip compression, and then finally apply Base64 encoding.
func Base64Sha256 ¶
Base64Sha256 computes the SHA256 hash of a given string and encodes it with Base64.
The given string is first encoded as UTF-8 and then the SHA256 algorithm is applied as defined in RFC 4634. The raw hash is then encoded with Base64 before returning. Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4.
func Base64Sha512 ¶
Base64Sha512 computes the SHA512 hash of a given string and encodes it with Base64.
The given string is first encoded as UTF-8 and then the SHA256 algorithm is applied as defined in RFC 4634. The raw hash is then encoded with Base64 before returning. Terraform uses the "standard" Base64 alphabet as defined in RFC 4648 section 4
func Basename ¶
Basename takes a string containing a filesystem path and removes all except the last portion from it.
The underlying function implementation works only with the path string and does not access the filesystem itself. It is therefore unable to take into account filesystem features such as symlinks.
If the path is empty then the result is ".", representing the current working directory.
func Bcrypt ¶
Bcrypt computes a hash of the given string using the Blowfish cipher, returning a string in the Modular Crypt Format usually expected in the shadow password file on many Unix systems.
func CidrHost ¶
CidrHost calculates a full host IP address within a given IP network address prefix.
func CidrNetmask ¶
CidrNetmask converts an IPv4 address prefix given in CIDR notation into a subnet mask address.
func CidrSubnet ¶
CidrSubnet calculates a subnet address within a given IP network address prefix.
func CidrSubnets ¶ added in v1.1.0
CidrSubnets calculates a sequence of consecutive subnet prefixes that may be of different prefix lengths under a common base prefix.
func CoalesceList ¶
CoalesceList takes any number of list arguments and returns the first one that isn't empty.
func Compact ¶
Compact takes a list of strings and returns a new list with any empty string elements removed.
func Contains ¶
Contains determines whether a given list contains a given single value as one of its elements.
func Dirname ¶
Dirname takes a string containing a filesystem path and removes the last portion from it.
The underlying function implementation works only with the path string and does not access the filesystem itself. It is therefore unable to take into account filesystem features such as symlinks.
If the path is empty then the result is ".", representing the current working directory.
func Element ¶
Element returns a single element from a given list at the given index. If index is greater than the length of the list then it is wrapped modulo the list length.
func File ¶
File reads the contents of the file at the given path.
The file must contain valid UTF-8 bytes, or this function will return an error.
The underlying function implementation works relative to a particular base directory, so this wrapper takes a base directory string and uses it to construct the underlying function before calling it.
func FileBase64 ¶
FileBase64 reads the contents of the file at the given path.
The bytes from the file are encoded as base64 before returning.
The underlying function implementation works relative to a particular base directory, so this wrapper takes a base directory string and uses it to construct the underlying function before calling it.
func FileExists ¶
FileExists determines whether a file exists at the given path.
The underlying function implementation works relative to a particular base directory, so this wrapper takes a base directory string and uses it to construct the underlying function before calling it.
func Flatten ¶
Flatten takes a list and replaces any elements that are lists with a flattened sequence of the list contents.
func Indent ¶
Indent adds a given number of spaces to the beginnings of all but the first line in a given multi-line string.
func Join ¶
Join concatenates together the string elements of one or more lists with a given separator.
func Length ¶
Length returns the number of elements in the given collection or number of Unicode characters in the given string.
func List ¶
List takes any number of list arguments and returns a list containing those
values in the same order.
func Lookup ¶
Lookup performs a dynamic lookup into a map. There are two required arguments, map and key, plus an optional default, which is a value to return if no key is found in map.
func MakeFileBase64Sha256Func ¶
MakeFileBase64Sha256Func constructs a function that is like Base64Sha256Func but reads the contents of a file rather than hashing a given literal string.
func MakeFileBase64Sha512Func ¶
MakeFileBase64Sha512Func constructs a function that is like Base64Sha512Func but reads the contents of a file rather than hashing a given literal string.
func MakeFileExistsFunc ¶
MakeFileExistsFunc constructs a function that takes a path and determines whether a file exists at that path
func MakeFileFunc ¶
MakeFileFunc constructs a function that takes a file path and returns the contents of that file, either directly as a string (where valid UTF-8 is required) or as a string containing base64 bytes.
func MakeFileMd5Func ¶
MakeFileMd5Func constructs a function that is like Md5Func but reads the contents of a file rather than hashing a given literal string.
func MakeFileSha1Func ¶
MakeFileSha1Func constructs a function that is like Sha1Func but reads the contents of a file rather than hashing a given literal string.
func MakeFileSha256Func ¶
MakeFileSha256Func constructs a function that is like Sha256Func but reads the contents of a file rather than hashing a given literal string.
func MakeFileSha512Func ¶
MakeFileSha512Func constructs a function that is like Sha512Func but reads the contents of a file rather than hashing a given literal string.
func MakeTemplateFileFunc ¶
func MakeTemplateFileFunc(baseDir string, funcsCb func() map[string]function.Function) function.Function
MakeTemplateFileFunc constructs a function that takes a file path and an arbitrary object of named values and attempts to render the referenced file as a template using HCL template syntax.
The template itself may recursively call other functions so a callback must be provided to get access to those functions. The template cannot, however, access any variables defined in the scope: it is restricted only to those variables provided in the second function argument, to ensure that all dependencies on other graph nodes can be seen before executing this function.
As a special exception, a referenced template file may not recursively call the templatefile function, since that would risk the same file being included into itself indefinitely.
func MakeToFunc ¶
MakeToFunc constructs a "to..." function, like "tostring", which converts its argument to a specific type or type kind.
The given type wantTy can be any type constraint that cty's "convert" package would accept. In particular, this means that you can pass cty.List(cty.DynamicPseudoType) to mean "list of any single type", which will then cause cty to attempt to unify all of the element types when given a tuple.
func Map ¶
Map takes an even number of arguments and returns a map whose elements are constructed from consecutive pairs of arguments.
func Matchkeys ¶
Matchkeys constructs a new list by taking a subset of elements from one list whose indexes match the corresponding indexes of values in another list.
func Merge ¶
Merge takes an arbitrary number of maps and returns a single map that contains a merged set of elements from all of the maps.
If more than one given map defines the same key then the one that is later in the argument sequence takes precedence.
func ParseInt ¶ added in v1.1.0
ParseInt parses a string argument and returns an integer of the specified base.
func Pathexpand ¶
Pathexpand takes a string that might begin with a `~` segment, and if so it replaces that segment with the current user's home directory path.
The underlying function implementation works only with the path string and does not access the filesystem itself. It is therefore unable to take into account filesystem features such as symlinks.
If the leading segment in the path is not `~` then the given path is returned unmodified.
func Replace ¶
Replace searches a given string for another given substring, and replaces all occurences with a given replacement string.
func Reverse ¶
Reverse takes a sequence and produces a new sequence of the same length with all of the same elements as the given sequence but in reverse order.
func RsaDecrypt ¶
RsaDecrypt decrypts an RSA-encrypted ciphertext, returning the corresponding cleartext.
func SetProduct ¶
SetProduct computes the cartesian product of sets or sequences.
func Sha256 ¶
Sha256 computes the SHA256 hash of a given string and encodes it with hexadecimal digits.
func Sha512 ¶
Sha512 computes the SHA512 hash of a given string and encodes it with hexadecimal digits.
func Signum ¶
Signum determines the sign of a number, returning a number between -1 and 1 to represent the sign.
func Sort ¶
Sort re-orders the elements of a given list of strings so that they are in ascending lexicographical order.
func Split ¶
Split divides a given string by a given separator, returning a list of strings containing the characters between the separator sequences.
func TimeAdd ¶
TimeAdd adds a duration to a timestamp, returning a new timestamp.
In the Terraform language, timestamps are conventionally represented as strings using RFC 3339 "Date and Time format" syntax. Timeadd requires the timestamp argument to be a string conforming to this syntax.
`duration` is a string representation of a time difference, consisting of sequences of number and unit pairs, like `"1.5h"` or `1h30m`. The accepted units are `ns`, `us` (or `µs`), `"ms"`, `"s"`, `"m"`, and `"h"`. The first number may be negative to indicate a negative duration, like `"-2h5m"`.
The result is a string, also in RFC 3339 format, representing the result of adding the given direction to the given timestamp.
func Timestamp ¶
Timestamp returns a string representation of the current date and time.
In the Terraform language, timestamps are conventionally represented as strings using RFC 3339 "Date and Time format" syntax, and so timestamp returns a string in this format.
func Transpose ¶
Transpose takes a map of lists of strings and swaps the keys and values to produce a new map of lists of strings.
func URLEncode ¶
URLEncode applies URL encoding to a given string.
This function identifies characters in the given string that would have a special meaning when included as a query string argument in a URL and escapes them using RFC 3986 "percent encoding".
If the given string contains non-ASCII characters, these are first encoded as UTF-8 and then percent encoding is applied separately to each UTF-8 byte.
func UUID ¶
UUID generates and returns a Type-4 UUID in the standard hexadecimal string format.
This is not a pure function: it will generate a different result for each call. It must therefore be registered as an impure function in the function table in the "lang" package.
Types ¶
This section is empty.