github.com/terramate-io/tf@v0.0.0-20230830114523-fce866b4dfcd/lang/funcs/sensitive.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: MPL-2.0
     3  
     4  package funcs
     5  
     6  import (
     7  	"github.com/terramate-io/tf/lang/marks"
     8  	"github.com/zclconf/go-cty/cty"
     9  	"github.com/zclconf/go-cty/cty/function"
    10  )
    11  
    12  // SensitiveFunc returns a value identical to its argument except that
    13  // Terraform will consider it to be sensitive.
    14  var SensitiveFunc = function.New(&function.Spec{
    15  	Params: []function.Parameter{
    16  		{
    17  			Name:             "value",
    18  			Type:             cty.DynamicPseudoType,
    19  			AllowUnknown:     true,
    20  			AllowNull:        true,
    21  			AllowMarked:      true,
    22  			AllowDynamicType: true,
    23  		},
    24  	},
    25  	Type: func(args []cty.Value) (cty.Type, error) {
    26  		// This function only affects the value's marks, so the result
    27  		// type is always the same as the argument type.
    28  		return args[0].Type(), nil
    29  	},
    30  	Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
    31  		val, _ := args[0].Unmark()
    32  		return val.Mark(marks.Sensitive), nil
    33  	},
    34  })
    35  
    36  // NonsensitiveFunc takes a sensitive value and returns the same value without
    37  // the sensitive marking, effectively exposing the value.
    38  var NonsensitiveFunc = function.New(&function.Spec{
    39  	Params: []function.Parameter{
    40  		{
    41  			Name:             "value",
    42  			Type:             cty.DynamicPseudoType,
    43  			AllowUnknown:     true,
    44  			AllowNull:        true,
    45  			AllowMarked:      true,
    46  			AllowDynamicType: true,
    47  		},
    48  	},
    49  	Type: func(args []cty.Value) (cty.Type, error) {
    50  		// This function only affects the value's marks, so the result
    51  		// type is always the same as the argument type.
    52  		return args[0].Type(), nil
    53  	},
    54  	Impl: func(args []cty.Value, retType cty.Type) (ret cty.Value, err error) {
    55  		if args[0].IsKnown() && !args[0].HasMark(marks.Sensitive) {
    56  			return cty.DynamicVal, function.NewArgErrorf(0, "the given value is not sensitive, so this call is redundant")
    57  		}
    58  		v, m := args[0].Unmark()
    59  		delete(m, marks.Sensitive) // remove the sensitive marking
    60  		return v.WithMarks(m), nil
    61  	},
    62  })
    63  
    64  func Sensitive(v cty.Value) (cty.Value, error) {
    65  	return SensitiveFunc.Call([]cty.Value{v})
    66  }
    67  
    68  func Nonsensitive(v cty.Value) (cty.Value, error) {
    69  	return NonsensitiveFunc.Call([]cty.Value{v})
    70  }