From 094079090ca6b9ec8a98b1eada9fe3ca0e9c163c Mon Sep 17 00:00:00 2001 From: Mike Heffner Date: Mon, 22 Nov 2021 10:04:43 -0500 Subject: [PATCH] feat(intrinsics): Add SubVars to Sub with replacement variables (#411) --- cloudformation/intrinsics.go | 10 ++++++++++ goformation_test.go | 12 ++++++++++++ 2 files changed, 22 insertions(+) diff --git a/cloudformation/intrinsics.go b/cloudformation/intrinsics.go index 3d76956ce0..aeaa1407e5 100644 --- a/cloudformation/intrinsics.go +++ b/cloudformation/intrinsics.go @@ -146,6 +146,16 @@ func Sub(value interface{}) string { return encode(fmt.Sprintf(`{ "Fn::Sub" : %q }`, value)) } +// SubVars works like Sub(), except it accepts a map of variable values to replace +func SubVars(value interface{}, variables map[string]interface{}) string { + pairs := make([]string, 0, len(variables)) + for key, val := range variables { + pairs = append(pairs, fmt.Sprintf(`%q : %q`, key, val)) + } + + return encode(fmt.Sprintf(`{ "Fn::Sub" : [ %q, { %s } ] }`, value, strings.Join(pairs, ","))) +} + // (str, str) -> str // GetAtt returns the value of an attribute from a resource in the template. diff --git a/goformation_test.go b/goformation_test.go index 350213ad3c..372355cfe4 100644 --- a/goformation_test.go +++ b/goformation_test.go @@ -1066,6 +1066,18 @@ var _ = Describe("Goformation", func() { "Fn::Sub": "test-sub", }, }, + { + Name: "Fn::SubVars", + Input: cloudformation.SubVars("test-sub", map[string]interface{}{"foo": "bar"}), + Expected: map[string]interface{}{ + "Fn::Sub": []interface{}{ + "test-sub", + map[string]interface{}{ + "foo": "bar", + }, + }, + }, + }, { Name: "Fn::And", Input: cloudformation.And([]string{"test-and-first", "test-and-second", "test-and-third"}),