diff --git a/upup/pkg/fi/cloudup/awstasks/vpc.go b/upup/pkg/fi/cloudup/awstasks/vpc.go index 786d4b5e13..fbe49c3418 100644 --- a/upup/pkg/fi/cloudup/awstasks/vpc.go +++ b/upup/pkg/fi/cloudup/awstasks/vpc.go @@ -296,7 +296,10 @@ func (_ *VPC) RenderTerraform(t *terraform.TerraformTarget, a, e, changes *VPC) return err } - if err := t.AddOutputVariable("vpc_ipv6_cidr_length", terraformWriter.LiteralFunctionExpression("local.vpc_ipv6_cidr_block == null ? null : tonumber", "regex(\".*/(\\\\d+)\", local.vpc_ipv6_cidr_block)[0]")); err != nil { + if err := t.AddOutputVariable("vpc_ipv6_cidr_length", terraformWriter.LiteralNullConditionalExpression( + terraformWriter.LiteralTokens("local", "vpc_ipv6_cidr_block"), + terraformWriter.LiteralFunctionExpression("tonumber", "regex(\".*/(\\\\d+)\", local.vpc_ipv6_cidr_block)[0]"), + )); err != nil { return err } diff --git a/upup/pkg/fi/cloudup/terraformWriter/literal.go b/upup/pkg/fi/cloudup/terraformWriter/literal.go index 990d66e03d..c665d27758 100644 --- a/upup/pkg/fi/cloudup/terraformWriter/literal.go +++ b/upup/pkg/fi/cloudup/terraformWriter/literal.go @@ -77,6 +77,16 @@ func LiteralWithIndex(s string) *Literal { } } +// LiteralNullConditionalExpression constructs a Literal which returns `null` +// if the supplied "nullable" expression is null, otherwise returns "value". +// It is the caller's responsibility to ensure the supplied parameters do not use operators +// with lower precedence than the conditional operator. +func LiteralNullConditionalExpression(nullable, value *Literal) *Literal { + return &Literal{ + String: fmt.Sprintf("%s == null ? null : %s", nullable.String, value.String), + } +} + // SortLiterals sorts a list of Literal, by key. It does so in-place func SortLiterals(v []*Literal) { sort.Slice(v, func(i, j int) bool {