fix(cloudformation): preserve list intrinsics and conditional tags (#2986)

This commit is contained in:
BingEdward authored and GitHub committed 2026-09-07 19:23:33 -05:00
1 parent b9039fef1d
commit 9f442543e3
14 files changed
+207 -54

No files matched your search

@@ -1080,8 +1080,9 @@ public class CloudFormationResourceProvisioner {
private Map<String, String> resolveAsgTags(JsonNode props, CloudFormationTemplateEngine engine) {
Map<String, String> tags = new LinkedHashMap<>();
if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
for (JsonNode tag : props.get("Tags")) {
JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = engine.resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.put(key, engine.resolve(tag.path("Value")));
@@ -1093,8 +1094,9 @@ public class CloudFormationResourceProvisioner {
private Map<String, Boolean> resolveAsgTagPropagation(JsonNode props, CloudFormationTemplateEngine engine) {
Map<String, Boolean> propagation = new LinkedHashMap<>();
if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
for (JsonNode tag : props.get("Tags")) {
JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = engine.resolve(tag.path("Key"));
if (!key.isEmpty()) {
propagation.put(key, Boolean.parseBoolean(engine.resolve(tag.path("PropagateAtLaunch"))));
@@ -1161,8 +1163,9 @@ public class CloudFormationResourceProvisioner {
}
List<Tag> tags = new ArrayList<>();
if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
for (JsonNode tag : props.get("Tags")) {
JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = engine.resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.add(new Tag(key, engine.resolve(tag.path("Value"))));
@@ -1856,6 +1859,16 @@ public class CloudFormationResourceProvisioner {
table = dynamoDbService.describeTable(tableName, region);
}
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, engine);
List<String> staleTags = ProvisionContext.staleTagKeys(
dynamoDbService.listTagsOfResource(table.getTableArn(), region), tags);
if (!staleTags.isEmpty()) {
dynamoDbService.untagResource(table.getTableArn(), staleTags, region);
}
if (!tags.isEmpty()) {
dynamoDbService.tagResource(table.getTableArn(), tags, region);
}
// A template that declares StreamSpecification wants a stream. Unlike the DynamoDB API,
// the CloudFormation property carries no StreamEnabled flag — declaring the block IS the
// request — so its presence alone turns the stream on. Without this the table is created
@@ -4740,6 +4753,7 @@ public class CloudFormationResourceProvisioner {
}
private Map<String, String> parseCfnTags(JsonNode tagsNode, CloudFormationTemplateEngine engine) {
tagsNode = engine.resolveNode(tagsNode);
Map<String, String> out = new HashMap<>();
if (tagsNode == null || tagsNode.isNull() || !tagsNode.isArray()) {
return out;
@@ -129,10 +129,12 @@ public class CloudFormationTemplateEngine {
JsonNode branch = selectIfBranch(node.get("Fn::If"));
return branch == null ? TextNode.valueOf("") : resolveNode(branch);
}
if (node.has("Fn::Split") || node.has("Fn::GetAZs") || node.has("Fn::Cidr")) {
return objectMapper.valueToTree(resolveList(node));
}
if (node.has("Ref") || node.has("Fn::Sub") || node.has("Fn::Join") ||
node.has("Fn::Select") || node.has("Fn::Base64") ||
node.has("Fn::GetAtt") || node.has("Fn::ImportValue") || node.has("Fn::Split") ||
node.has("Fn::GetAZs") || node.has("Fn::Cidr") || node.has("Fn::FindInMap")) {
node.has("Fn::GetAtt") || node.has("Fn::ImportValue") || node.has("Fn::FindInMap")) {
return TextNode.valueOf(resolve(node));
}
// Plain object — resolve each field
@@ -245,15 +247,7 @@ public class CloudFormationTemplateEngine {
return "";
}
String delimiter = join.get(0).asText("");
JsonNode parts = join.get(1);
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.size(); i++) {
if (i > 0) {
sb.append(delimiter);
}
sb.append(resolve(parts.get(i)));
}
return sb.toString();
return String.join(delimiter, resolveList(join.get(1)));
}
private String resolveSelect(JsonNode select) {
@@ -364,12 +358,8 @@ public class CloudFormationTemplateEngine {
return true;
}
if (node.has("Fn::If")) {
JsonNode ifNode = node.get("Fn::If");
if (ifNode.isArray() && ifNode.size() >= 3) {
String conditionName = ifNode.get(0).asText();
boolean condValue = conditions.getOrDefault(conditionName, false);
return isListValuedIntrinsic(condValue ? ifNode.get(1) : ifNode.get(2));
}
JsonNode branch = selectIfBranch(node.get("Fn::If"));
return branch != null && isListValuedIntrinsic(branch);
}
}
return false;
@@ -130,6 +130,7 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner {
/** See {@code KmsCfnProvisioner#parseCfnTags} for why this is copied rather than shared. */
private Map<String, String> parseCfnTags(JsonNode tagsNode, ProvisionContext ctx) {
tagsNode = ctx.engine().resolveNode(tagsNode);
Map<String, String> out = new HashMap<>();
if (tagsNode == null || tagsNode.isNull() || !tagsNode.isArray()) {
return out;
@@ -191,7 +191,7 @@ public class EcsCapacityCfnProvisioner implements CfnResourceProvisioner {
private Map<String, String> tags(JsonNode props, ProvisionContext ctx) {
Map<String, String> out = new HashMap<>();
JsonNode tagsNode = props != null ? props.get("Tags") : null;
JsonNode tagsNode = props != null ? ctx.engine().resolveNode(props.get("Tags")) : null;
if (tagsNode == null || !tagsNode.isArray()) {
return out;
}
@@ -59,8 +59,9 @@ public class FirehoseCfnProvisioner implements CfnResourceProvisioner {
}
List<DeliveryStreamDescription.Tag> tags = new ArrayList<>();
if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
for (JsonNode tag : props.get("Tags")) {
JsonNode tagsNode = props != null ? ctx.engine().resolveNode(props.get("Tags")) : null;
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = ctx.engine().resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.add(new DeliveryStreamDescription.Tag(key, ctx.engine().resolve(tag.path("Value"))));
@@ -76,8 +76,9 @@ public class KinesisCfnProvisioner implements CfnResourceProvisioner {
}
}
Map<String, String> tags = new LinkedHashMap<>();
if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
for (JsonNode tag : props.get("Tags")) {
JsonNode tagsNode = props != null ? ctx.engine().resolveNode(props.get("Tags")) : null;
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = ctx.engine().resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.put(key, ctx.engine().resolve(tag.path("Value")));
@@ -69,11 +69,11 @@ public class KmsCfnProvisioner implements CfnResourceProvisioner {
/**
* Copied from {@code CloudFormationResourceProvisioner} rather than delegating to
* {@link ProvisionContext#resolveTags}, which is not equivalent: it skips a blank key this
* keeps, orders entries by insertion rather than hash, and resolves the whole property so an
* {@code Fn::If} around the list works. Adopting it here is a behaviour change and belongs in
* its own PR; this copy dies when the monolith's last caller migrates.
* keeps and orders entries by insertion rather than hash. This copy dies when the monolith's
* last caller migrates.
*/
private Map<String, String> parseCfnTags(JsonNode tagsNode, ProvisionContext ctx) {
tagsNode = ctx.engine().resolveNode(tagsNode);
Map<String, String> out = new HashMap<>();
if (tagsNode == null || tagsNode.isNull() || !tagsNode.isArray()) {
return out;
@@ -77,8 +77,9 @@ public class LogsCfnProvisioner implements CfnResourceProvisioner {
}
}
Map<String, String> tags = new HashMap<>();
if (props != null && props.has("Tags") && props.get("Tags").isArray()) {
for (JsonNode tag : props.get("Tags")) {
JsonNode tagsNode = props != null ? ctx.engine().resolveNode(props.get("Tags")) : null;
if (tagsNode != null && tagsNode.isArray()) {
for (JsonNode tag : tagsNode) {
String key = ctx.engine().resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.put(key, ctx.engine().resolve(tag.path("Value")));
@@ -285,11 +285,12 @@ public class OrganizationsCfnProvisioner implements CfnResourceProvisioner {
/** CloudFormation tags are a list of {@code {Key, Value}} objects. */
private Map<String, String> resolveTags(JsonNode props, ProvisionContext ctx) {
if (props == null || !props.has("Tags") || !props.get("Tags").isArray()) {
JsonNode tagsNode = props != null ? ctx.engine().resolveNode(props.get("Tags")) : null;
if (tagsNode == null || !tagsNode.isArray()) {
return null;
}
Map<String, String> tags = new LinkedHashMap<>();
for (JsonNode tag : ctx.engine().resolveNode(props.get("Tags"))) {
for (JsonNode tag : tagsNode) {
String key = tag.path("Key").asText(null);
if (key != null && !key.isBlank()) {
tags.put(key, tag.path("Value").asText(""));
@@ -498,6 +498,7 @@ public class PipesCfnProvisioner implements CfnResourceProvisioner {
/** See {@code KmsCfnProvisioner#parseCfnTags} for why this is copied rather than shared. */
private Map<String, String> parseCfnTags(JsonNode tagsNode, ProvisionContext ctx) {
tagsNode = ctx.engine().resolveNode(tagsNode);
Map<String, String> out = new HashMap<>();
if (tagsNode == null || tagsNode.isNull() || !tagsNode.isArray()) {
return out;
@@ -42,19 +42,13 @@ public class SchedulerScheduleGroupCfnProvisioner implements CfnResourceProvisio
// it already had across updates instead of getting a fresh random one each time provision
// runs. Read from the context, not the resource: provision assigns the new id as it works.
String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "Name"), r.getLogicalId(), 64, false);
// Tags wrapped in an intrinsic (e.g. Fn::If choosing between two tag lists) is not resolved
// here: the engine collapses a list-valued intrinsic to a string (#2983), so a conditional
// list would not arrive as the chosen array. tagsAreResolvable is true both when Tags is
// absent (the template genuinely wants no tags) and when it is a plain array (the template's
// actual desired tags), and false only when Tags is present but not a plain array, the one
// case where the desired state genuinely cannot be read, so the reconcile path below must
// not treat "couldn't resolve the intended tags" as "the intended tags are empty" and delete
// everything live.
// Preserve live tags when a present property still cannot resolve to a tag list.
boolean hasTagsProperty = props != null && props.has("Tags");
boolean tagsAreResolvable = !hasTagsProperty || props.get("Tags").isArray();
JsonNode tagsNode = hasTagsProperty ? ctx.engine().resolveNode(props.get("Tags")) : null;
boolean tagsAreResolvable = !hasTagsProperty || (tagsNode != null && tagsNode.isArray());
Map<String, String> tags = new HashMap<>();
if (hasTagsProperty && tagsAreResolvable) {
for (JsonNode tag : props.get("Tags")) {
for (JsonNode tag : tagsNode) {
String key = ctx.engine().resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.put(key, ctx.engine().resolve(tag.path("Value")));
@@ -0,0 +1,108 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Map;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
@QuarkusTest
class CloudFormationListIntrinsicsIntegrationTest {
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void conditionalTagsAndJoinedListsSurviveStackCreationAndUpdates() {
String name = "cfn-lists-" + Long.toString(System.nanoTime(), 36);
String template = """
{
"Parameters": {"UseTags": {"Type": "String"}},
"Conditions": {"Tagged": {"Fn::Equals": [{"Ref": "UseTags"}, "true"]}},
"Resources": {
"Stream": {
"Type": "AWS::Kinesis::Stream",
"Properties": {"Name": "%1$s", "ShardCount": 1,
"Tags": {"Fn::If": ["Tagged", [{"Key": "region", "Value": {"Ref": "AWS::Region"}}], []]}}
},
"Table": {
"Type": "AWS::DynamoDB::Table",
"Properties": {"TableName": "%1$s", "BillingMode": "PAY_PER_REQUEST",
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
"Tags": {"Fn::If": ["Tagged", [{"Key": "region", "Value": {"Ref": "AWS::Region"}}], []]}}
},
"Group": {
"Type": "AWS::Scheduler::ScheduleGroup",
"Properties": {"Name": "%1$s",
"Tags": {"Fn::If": ["Tagged", [{"Key": "region", "Value": {"Ref": "AWS::Region"}}], []]}}
}
},
"Outputs": {
"JoinedIf": {"Value": {"Fn::Join": [",", {"Fn::If": ["Tagged", ["a", "b"], ["c"]]}]}},
"JoinedSplit": {"Value": {"Fn::Join": ["|", {"Fn::Split": [",", "x,,y,"]}]}}
}
}
""".formatted(name);
try {
for (boolean tagged : List.of(true, false)) {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", tagged ? "CreateStack" : "UpdateStack")
.formParam("StackName", name)
.formParam("TemplateBody", template)
.formParam("Parameters.member.1.ParameterKey", "UseTags")
.formParam("Parameters.member.1.ParameterValue", Boolean.toString(tagged))
.when().post("/")
.then().statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DescribeStacks")
.formParam("StackName", name)
.when().post("/")
.then().statusCode(200)
.body(containsString(tagged ? "CREATE_COMPLETE" : "UPDATE_COMPLETE"))
.body(containsString(tagged ? "<OutputValue>a,b</OutputValue>" : "<OutputValue>c</OutputValue>"))
.body(containsString("<OutputValue>x||y|</OutputValue>"));
List<Map<String, String>> expected = tagged
? List.of(Map.of("Key", "region", "Value", "us-east-1")) : List.of();
given()
.contentType("application/x-amz-json-1.1")
.header("X-Amz-Target", "Kinesis_20131202.ListTagsForStream")
.body(Map.of("StreamName", name))
.when().post("/")
.then().statusCode(200).body("Tags", equalTo(expected));
given()
.contentType("application/x-amz-json-1.0")
.header("X-Amz-Target", "DynamoDB_20120810.ListTagsOfResource")
.body(Map.of("ResourceArn", "arn:aws:dynamodb:us-east-1:000000000000:table/" + name))
.when().post("/")
.then().statusCode(200).body("Tags", equalTo(expected));
given()
.queryParam("resourceArn", "arn:aws:scheduler:us-east-1:000000000000:schedule-group/" + name)
.when().get("/tags")
.then().statusCode(200).body("Tags", equalTo(expected));
}
} finally {
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "DeleteStack")
.formParam("StackName", name)
.when().post("/")
.then().statusCode(200);
}
}
}
@@ -3,6 +3,9 @@ package io.github.hectorvent.floci.services.cloudformation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
@@ -30,6 +33,49 @@ class CloudFormationTemplateEngineTest {
}
}
@Test
void joinAcceptsSplitAsItsListOfValues() {
assertEquals("x|y|z", engine().resolve(json("""
{"Fn::Join": ["|", {"Fn::Split": [",", "x,y,z"]}]}
""")));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void resolveNodePreservesConditionalTagLists(boolean useTags) {
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000",
"us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(),
Map.of("UseTags", useTags), Map.of(), mapper, name -> null);
JsonNode tags = json("""
{"Fn::If": ["UseTags", [{"Key": "region", "Value": {"Ref": "AWS::Region"}}], []]}
""");
assertEquals(json(useTags ? "[{\"Key\":\"region\",\"Value\":\"us-east-1\"}]" : "[]"),
e.resolveNode(tags));
}
@ParameterizedTest
@CsvSource(textBlock = """
'{"Fn::Split": [".", "a..b."]}', '["a", "", "b", ""]'
'{"Fn::GetAZs": ""}', '["us-east-1a", "us-east-1b", "us-east-1c"]'
'{"Fn::Cidr": ["10.0.0.0/16", 2, 8]}', '["10.0.0.0/24", "10.0.1.0/24"]'
""")
void resolveNodePreservesListValuedIntrinsics(String expression, String expected) {
assertEquals(json(expected), engine().resolveNode(json(expression)));
}
@ParameterizedTest
@ValueSource(booleans = {true, false})
void joinAcceptsConditionalLists(boolean useFirst) {
CloudFormationTemplateEngine e = new CloudFormationTemplateEngine("000000000000",
"us-east-1", "my-stack", "stack/id", Map.of(), Map.of(), Map.of(),
Map.of("UseFirst", useFirst), Map.of(), mapper, name -> null);
assertEquals(useFirst ? "a,b" : "x,,y,", e.resolve(json("""
{"Fn::Join": [",", {"Fn::If": ["UseFirst", ["a", "b"],
{"Fn::Split": ["|", "x||y|"]}]}]}
""")));
}
@Test
void getAzsReturnsStackRegionZones() {
assertEquals("us-east-1a,us-east-1b,us-east-1c",
@@ -46,6 +46,7 @@ class SchedulerScheduleGroupCfnProvisionerTest {
/** An update-path context carries the physical id the previous provision assigned. */
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
@@ -205,6 +206,7 @@ class SchedulerScheduleGroupCfnProvisionerTest {
props.set("Tags", mapper.createArrayNode().add(tag));
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
@@ -255,19 +257,12 @@ class SchedulerScheduleGroupCfnProvisionerTest {
@Test
void sameStackRetryWithUnresolvableTagsDoesNotUntagExistingTags() {
// Greptile review on PR #2796: the engine's Fn::If support is scalar-only, so a Tags
// property wrapped in Fn::If (choosing between two tag lists) does not resolve to an array
// here - props.get("Tags").isArray() is false, same as no Tags at all. Before this test, that
// made the retry path's tag-diff see an empty desired set and untag every live key, actively
// destroying tags a resolvable Tags property never asked to remove.
// A malformed Tags value must not be mistaken for an empty desired tag set.
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
.thenReturn(group("my-group", Map.of("Old", "value")));
StackResource r = resource("MyGroup");
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
ObjectNode condition = mapper.createObjectNode();
condition.set("Fn::If", mapper.createArrayNode().add("UseProdTags")
.add(mapper.createArrayNode()).add(mapper.createArrayNode()));
props.set("Tags", condition);
props.put("Tags", "not-a-list");
provisioner.provision(r, props, ctx("my-group"));