fix(cloudformation): provision AWS::Scheduler::ScheduleGroup (#2796)

This commit is contained in:
Olamide Kosile authored and GitHub committed 2026-09-01 21:26:02 -05:00
1 parent afa5960709
commit 961d82dda9
6 files changed
+480

No files matched your search

+1
View File
@@ -81,6 +81,7 @@ cross-resource references.
| Batch | `ComputeEnvironment`, `JobQueue`, `JobDefinition` |
| Cognito | `UserPool`, `UserPoolClient` |
| EventBridge | `Rule`, `EventBus`, `EventBusPolicy` |
| EventBridge Scheduler | `ScheduleGroup` |
| Pipes | `Pipe` |
| Kinesis | `Stream` |
| Kinesis Data Firehose | `DeliveryStream` |
@@ -0,0 +1,122 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
import io.github.hectorvent.floci.services.scheduler.model.ScheduleGroup;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
/**
* CloudFormation provisioning for {@code AWS::Scheduler::ScheduleGroup}. Previously unhandled, so
* the resource type fell through to the generic stub: the stack reported CREATE_COMPLETE with a
* random physical id and no group was ever created in SchedulerService (issue #2396).
*/
@ApplicationScoped
public class SchedulerScheduleGroupCfnProvisioner implements CfnResourceProvisioner {
private static final Logger LOG = Logger.getLogger(SchedulerScheduleGroupCfnProvisioner.class);
private final SchedulerService schedulerService;
@Inject
public SchedulerScheduleGroupCfnProvisioner(SchedulerService schedulerService) {
this.schedulerService = schedulerService;
}
@Override
public Set<String> resourceTypes() {
return Set.of("AWS::Scheduler::ScheduleGroup");
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
String name = ctx.resolveOptional(props, "Name");
if (name == null || name.isBlank()) {
// No explicit name and this resource already has a physical id: keep it across updates
// instead of generating a fresh random one each retry, same as LogGroup/Queue do.
name = r.getPhysicalId() != null
? r.getPhysicalId()
: ctx.generatePhysicalName(r.getLogicalId(), 64, false);
}
// Tags wrapped in an intrinsic (e.g. Fn::If choosing between two tag lists) is not resolved
// here: the engine's Fn::If support is scalar-only, so a conditional list would collapse to
// a string rather than 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 retry path below must not treat
// "couldn't resolve the intended tags" as "the intended tags are empty" and delete everything
// live.
boolean hasTagsProperty = props != null && props.has("Tags");
boolean tagsAreResolvable = !hasTagsProperty || props.get("Tags").isArray();
Map<String, String> tags = new HashMap<>();
if (hasTagsProperty && tagsAreResolvable) {
for (JsonNode tag : props.get("Tags")) {
String key = ctx.engine().resolve(tag.path("Key"));
if (!key.isEmpty()) {
tags.put(key, ctx.engine().resolve(tag.path("Value")));
}
}
}
ScheduleGroup group;
try {
group = schedulerService.createScheduleGroup(name, tags, ctx.region());
} catch (AwsException e) {
if (!"ConflictException".equals(e.getErrorCode()) || !name.equals(r.getPhysicalId())) {
throw e;
}
// Same-stack create-retry: CloudFormation only retries a resource under the physical id
// it previously assigned, so a conflict on that exact name means this logical resource's
// own group already exists from an earlier attempt. Adopt it instead of failing the whole
// stack on a retry of a step that already succeeded.
group = schedulerService.getScheduleGroup(name, ctx.region());
// Reconcile tags both ways: a key dropped from the template (or the whole Tags list
// emptied, or Tags removed entirely) must not linger on the live resource, matching how
// the same-stack retry path applies every other property change rather than only ever
// adding. Skipped only when Tags is present but unresolvable (Fn::If) - untagging every
// live key there would erase tags for a reason unrelated to what the template asked for.
if (tagsAreResolvable) {
Set<String> staleKeys = new HashSet<>(group.getTags().keySet());
staleKeys.removeAll(tags.keySet());
if (!staleKeys.isEmpty()) {
schedulerService.untagScheduleGroup(name, ctx.region(), new ArrayList<>(staleKeys));
}
}
if (!tags.isEmpty()) {
schedulerService.tagScheduleGroup(name, ctx.region(), tags);
}
}
r.setPhysicalId(group.getName());
r.getAttributes().put("Arn", group.getArn());
if (group.getCreationDate() != null) {
r.getAttributes().put("CreationDate", group.getCreationDate().toString());
}
if (group.getLastModificationDate() != null) {
r.getAttributes().put("LastModificationDate", group.getLastModificationDate().toString());
}
if (group.getState() != null) {
r.getAttributes().put("State", group.getState());
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
try {
schedulerService.deleteScheduleGroup(physicalId, region);
} catch (AwsException e) {
if (!"ResourceNotFoundException".equals(e.getErrorCode())) {
throw e;
}
LOG.debugv("Schedule group already gone, treating as deleted: {0}", physicalId);
}
}
}
@@ -2460,6 +2460,65 @@ class CloudFormationIntegrationTest {
.body(containsString("CaseSensitive-Stack-MyMixedCaseQueue-"));
}
@Test
void createStack_schedulerScheduleGroup_isActuallyProvisioned() {
// github.com/floci-io/floci/issues/2396: AWS::Scheduler::ScheduleGroup fell through to the
// generic stub, so the stack reported CREATE_COMPLETE with a fake physical id and the group
// never actually existed. GetScheduleGroup used to return ResourceNotFoundException here.
// ArnParam pins Fn::GetAtt MyGroup.Arn against the group's actual ARN, so an omission or
// rename of the provisioner's Arn attribute fails this test rather than only the direct
// GetScheduleGroup check below (Greptile review on PR #2796).
String template = """
{
"Resources": {
"MyGroup": {
"Type": "AWS::Scheduler::ScheduleGroup",
"Properties": {
"Name": "group-repro"
}
},
"ArnParam": {
"Type": "AWS::SSM::Parameter",
"Properties": {
"Name": "/app/schedule-group-arn",
"Type": "String",
"Value": {"Fn::GetAtt": ["MyGroup", "Arn"]}
}
}
}
}
""";
given()
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "CreateStack")
.formParam("StackName", "SchedulerGroupStack")
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.when()
.get("/schedule-groups/group-repro")
.then()
.statusCode(200)
.body(containsString("group-repro"));
given()
.header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType(SSM_CONTENT_TYPE)
.body("""
{"Name": "/app/schedule-group-arn", "WithDecryption": true}
""")
.when()
.post("/")
.then()
.statusCode(200)
.body("Parameter.Value", equalTo("arn:aws:scheduler:us-east-1:000000000000:schedule-group/group-repro"));
}
@Test
void createStack_multipleUnnamedResources_uniqueNames() {
// Multiple resources of same type without names get unique auto-generated names
@@ -0,0 +1,295 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
import io.github.hectorvent.floci.services.scheduler.model.ScheduleGroup;
import org.junit.jupiter.api.Test;
import java.time.Instant;
import java.util.HashMap;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* github.com/floci-io/floci/issues/2396 - AWS::Scheduler::ScheduleGroup fell through to the
* generic stub (fake physical id, no backing call), so a stack reporting CREATE_COMPLETE never
* actually created the group. These tests exercise the provisioner in isolation.
*/
class SchedulerScheduleGroupCfnProvisionerTest {
private final SchedulerService schedulerService = mock(SchedulerService.class);
private final SchedulerScheduleGroupCfnProvisioner provisioner =
new SchedulerScheduleGroupCfnProvisioner(schedulerService);
private final ObjectMapper mapper = new ObjectMapper();
private ProvisionContext ctx() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
}
private StackResource resource(String logicalId) {
StackResource r = new StackResource();
r.setLogicalId(logicalId);
r.setResourceType("AWS::Scheduler::ScheduleGroup");
r.setAttributes(new HashMap<>());
return r;
}
private static ScheduleGroup group(String name, Map<String, String> tags) {
ScheduleGroup g = new ScheduleGroup(name,
"arn:aws:scheduler:us-east-1:000000000000:schedule-group/" + name,
"ACTIVE", Instant.now(), Instant.now());
g.getTags().putAll(tags);
return g;
}
@Test
void createsGroupAndSetsPhysicalIdAndArn() {
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
.thenReturn(group("my-group", Map.of()));
StackResource r = resource("MyGroup");
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
provisioner.provision(r, props, ctx());
assertEquals("my-group", r.getPhysicalId());
assertEquals("arn:aws:scheduler:us-east-1:000000000000:schedule-group/my-group",
r.getAttributes().get("Arn"));
}
@Test
void withoutNameGeneratesPhysicalName() {
when(schedulerService.createScheduleGroup(anyString(), any(), eq("us-east-1")))
.thenAnswer(inv -> group(inv.getArgument(0), Map.of()));
StackResource r = resource("MyGroup");
provisioner.provision(r, mapper.createObjectNode(), ctx());
assertTrue(r.getPhysicalId().startsWith("my-stack-MyGroup-"),
"generated name should follow <stack>-<logicalId>-<suffix> but was: " + r.getPhysicalId());
assertTrue(r.getPhysicalId().length() <= 64, "schedule group names are capped at 64 characters");
}
@Test
void passesResolvedTagsToCreateScheduleGroup() {
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
.thenReturn(group("my-group", Map.of("Env", "prod")));
StackResource r = resource("MyGroup");
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
ObjectNode tag = mapper.createObjectNode().put("Key", "Env").put("Value", "prod");
props.set("Tags", mapper.createArrayNode().add(tag));
provisioner.provision(r, props, ctx());
verify(schedulerService).createScheduleGroup("my-group", Map.of("Env", "prod"), "us-east-1");
}
@Test
void sameStackRetryAdoptsExistingGroup() {
// The physical id already recorded on this resource (from an earlier attempt) matches the
// name this attempt resolves to, so a ConflictException on create means this attempt's own
// group already exists - adopt it instead of failing the stack.
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
.thenThrow(new AwsException("ConflictException", "already exists", 409));
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
.thenReturn(group("my-group", Map.of()));
StackResource r = resource("MyGroup");
r.setPhysicalId("my-group");
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
provisioner.provision(r, props, ctx());
assertEquals("my-group", r.getPhysicalId());
assertEquals("arn:aws:scheduler:us-east-1:000000000000:schedule-group/my-group",
r.getAttributes().get("Arn"));
}
@Test
void createSetsCreationDateLastModificationDateAndState() {
// pgermosen review on PR #2796: real AWS's Fn::GetAtt for AWS::Scheduler::ScheduleGroup
// supports Arn, CreationDate, LastModificationDate and State; only Arn was populated,
// so Fn::GetAtt MyGroup.State resolved to nothing.
Instant created = Instant.parse("2026-01-01T00:00:00Z");
Instant modified = Instant.parse("2026-01-02T00:00:00Z");
ScheduleGroup g = new ScheduleGroup("my-group",
"arn:aws:scheduler:us-east-1:000000000000:schedule-group/my-group",
"ACTIVE", created, modified);
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1"))).thenReturn(g);
StackResource r = resource("MyGroup");
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
provisioner.provision(r, props, ctx());
assertEquals(created.toString(), r.getAttributes().get("CreationDate"));
assertEquals(modified.toString(), r.getAttributes().get("LastModificationDate"));
assertEquals("ACTIVE", r.getAttributes().get("State"));
}
@Test
void tagsWithIntrinsicKeyOrValueAreResolvedThroughTheEngine() {
// pgermosen review on PR #2796 raised this as a gap; the loop already calls
// ctx.engine().resolve(...) for both Key and Value, so this pins that a Ref/Fn::Sub node
// resolves to the engine's answer rather than a raw JsonNode-to-text conversion of the
// intrinsic object itself.
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
.thenReturn(group("my-group", Map.of()));
StackResource r = resource("MyGroup");
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
ObjectNode keyRef = mapper.createObjectNode();
keyRef.put("Ref", "TagKeyParam");
ObjectNode valueSub = mapper.createObjectNode();
valueSub.put("Fn::Sub", "env-${AWS::Region}");
ObjectNode tag = mapper.createObjectNode();
tag.set("Key", keyRef);
tag.set("Value", valueSub);
props.set("Tags", mapper.createArrayNode().add(tag));
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = inv.getArgument(0);
return node == null ? null : node.asText();
});
when(engine.resolve(keyRef)).thenReturn("resolved-key");
when(engine.resolve(valueSub)).thenReturn("env-us-east-1");
ProvisionContext ctx = new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
provisioner.provision(r, props, ctx);
verify(schedulerService).createScheduleGroup(
"my-group", Map.of("resolved-key", "env-us-east-1"), "us-east-1");
}
@Test
void sameStackRetryRemovesTagsDroppedFromTheTemplate() {
// pgermosen review on PR #2796: the retry path only ever added tags on conflict, so a tag
// removed from the template stayed on the live resource across every subsequent update.
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
.thenThrow(new AwsException("ConflictException", "already exists", 409));
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
.thenReturn(group("my-group", Map.of("Old", "value", "Keep", "same")));
StackResource r = resource("MyGroup");
r.setPhysicalId("my-group");
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
ObjectNode tag = mapper.createObjectNode().put("Key", "Keep").put("Value", "same");
props.set("Tags", mapper.createArrayNode().add(tag));
provisioner.provision(r, props, ctx());
verify(schedulerService).untagScheduleGroup(eq("my-group"), eq("us-east-1"),
argThat(keys -> keys.size() == 1 && keys.contains("Old")));
verify(schedulerService).tagScheduleGroup("my-group", "us-east-1", Map.of("Keep", "same"));
}
@Test
void sameStackRetryWithEmptyTemplateTagsRemovesAllExistingTags() {
// The Tags property emptied entirely on the template is the same case as a dropped key,
// just for every key at once - the whole existing tag set must come off.
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
.thenThrow(new AwsException("ConflictException", "already exists", 409));
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
.thenReturn(group("my-group", Map.of("Old", "value")));
StackResource r = resource("MyGroup");
r.setPhysicalId("my-group");
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
provisioner.provision(r, props, ctx());
verify(schedulerService).untagScheduleGroup(eq("my-group"), eq("us-east-1"),
argThat(keys -> keys.size() == 1 && keys.contains("Old")));
verify(schedulerService, never()).tagScheduleGroup(anyString(), anyString(), any());
}
@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.
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
.thenThrow(new AwsException("ConflictException", "already exists", 409));
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
.thenReturn(group("my-group", Map.of("Old", "value")));
StackResource r = resource("MyGroup");
r.setPhysicalId("my-group");
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);
provisioner.provision(r, props, ctx());
verify(schedulerService, never()).untagScheduleGroup(anyString(), anyString(), any());
verify(schedulerService, never()).tagScheduleGroup(anyString(), anyString(), any());
}
@Test
void sameStackRetryWithNoTagChangesDoesNotCallUntagOrTag() {
when(schedulerService.createScheduleGroup(eq("my-group"), any(), eq("us-east-1")))
.thenThrow(new AwsException("ConflictException", "already exists", 409));
when(schedulerService.getScheduleGroup("my-group", "us-east-1"))
.thenReturn(group("my-group", Map.of()));
StackResource r = resource("MyGroup");
r.setPhysicalId("my-group");
ObjectNode props = mapper.createObjectNode().put("Name", "my-group");
provisioner.provision(r, props, ctx());
verify(schedulerService, never()).untagScheduleGroup(anyString(), anyString(), any());
verify(schedulerService, never()).tagScheduleGroup(anyString(), anyString(), any());
}
@Test
void conflictForADifferentPhysicalIdIsNotAdopted() {
// No prior physical id recorded (fresh create) colliding with someone else's group of the
// same name: not this attempt's retry, must fail rather than silently adopting a stranger's
// group.
when(schedulerService.createScheduleGroup(eq("taken-name"), any(), eq("us-east-1")))
.thenThrow(new AwsException("ConflictException", "already exists", 409));
StackResource r = resource("MyGroup");
ObjectNode props = mapper.createObjectNode().put("Name", "taken-name");
AwsException thrown = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
assertEquals("ConflictException", thrown.getErrorCode());
verify(schedulerService, never()).getScheduleGroup(anyString(), anyString());
}
@Test
void deleteDelegatesToService() {
provisioner.delete("AWS::Scheduler::ScheduleGroup", "my-group", "us-east-1");
verify(schedulerService).deleteScheduleGroup("my-group", "us-east-1");
}
@Test
void deleteAlreadyGoneIsTreatedAsSuccess() {
doThrowNotFoundOnDelete("my-group");
provisioner.delete("AWS::Scheduler::ScheduleGroup", "my-group", "us-east-1");
}
private void doThrowNotFoundOnDelete(String name) {
org.mockito.Mockito.doThrow(new AwsException("ResourceNotFoundException", "not found", 404))
.when(schedulerService).deleteScheduleGroup(name, "us-east-1");
}
}
@@ -105,6 +105,7 @@ AWS::SNS::Topic SnsCfnProvisioner
AWS::SQS::Queue SqsCfnProvisioner
AWS::SQS::QueuePolicy SqsCfnProvisioner
AWS::SSM::Parameter SsmCfnProvisioner
AWS::Scheduler::ScheduleGroup SchedulerScheduleGroupCfnProvisioner
AWS::SecretsManager::Secret LEGACY_SWITCH
AWS::SecretsManager::SecretTargetAttachment LEGACY_SWITCH
AWS::StepFunctions::StateMachine LEGACY_SWITCH
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
105 AWS::SQS::Queue SqsCfnProvisioner
106 AWS::SQS::QueuePolicy SqsCfnProvisioner
107 AWS::SSM::Parameter SsmCfnProvisioner
108 AWS::Scheduler::ScheduleGroup SchedulerScheduleGroupCfnProvisioner
109 AWS::SecretsManager::Secret LEGACY_SWITCH
110 AWS::SecretsManager::SecretTargetAttachment LEGACY_SWITCH
111 AWS::StepFunctions::StateMachine LEGACY_SWITCH
+2
View File
@@ -36,6 +36,7 @@ order:
- AWS::Batch
- AWS::Cognito
- AWS::Events
- AWS::Scheduler
- AWS::Pipes
- AWS::Kinesis
- AWS::KinesisFirehose
@@ -125,6 +126,7 @@ service_labels:
AWS::SNS: SNS
AWS::SQS: SQS
AWS::SSM: SSM
AWS::Scheduler: EventBridge Scheduler
AWS::SecretsManager: Secrets Manager
AWS::StepFunctions: Step Functions
AWS::WAFv2: WAFv2