feat(cloudformation): provision AWS::CloudFormation::StackSet (#7244)

Create, update and delete StackSet resources and their instances through the existing StackSet service. Preserve current main's asynchronous automatic deployment and stable tag reads while reconciling the resource's declared account and organizational-unit targets and Regions.

Return StackSetId for Ref and Fn::GetAtt and cover the provisioner lifecycle with integration tests. OperationPreferences, CallAs and ParameterOverrides remain unsupported.
This commit is contained in:
galsuchetzky-act authored and GitHub committed 2026-11-10 08:54:32 -04:00
1 parent 128e4e6227
commit 09ac552cf7
13 files changed
+1320 -139

No files matched your search

+3 -1
View File
@@ -68,6 +68,8 @@ StackSets support both `SELF_MANAGED` and the Cloud Launchpad `SERVICE_MANAGED`
With `AutoDeployment` enabled, a service-managed stack set follows its organization. An account created in, invited into or moved under a targeted root or OU gets an instance in every Region of the targets that now cover it, and an account moved out of every target or removed from the organization loses its instances; their stacks stay when `RetainStacksOnAccountRemoval` is set. Account placement changes are reconciled asynchronously, so Organizations calls do not wait for deployments and deployment failures do not undo completed account changes. A second `CreateStackInstances` for a target already recorded adds its Regions to the earlier ones. Automatic creates and deletes are recorded in `ListStackSetOperations` and `DescribeStackSetOperation`, with their timestamps and success or failure status. An account move that needs no instance changes records no operation. A returning account uses a distinct backing-stack name when its previous name remains occupied; the retained stack is not reassociated.
A template can declare `AWS::CloudFormation::StackSet` with required `StackSetName` and `PermissionModel` properties. Missing or blank values fail resource creation. Floci creates the stack set and an instance in every account, or account under every root and OU, and Region of its `StackInstancesGroup`. An update applies the template, parameters and settings to every instance, deploys to the targets and Regions the template adds, and removes the instances of a target it drops or of a Region it drops from a target it keeps; deleting the resource deletes every instance and then the stack set. `Ref` and `Fn::GetAtt StackSetId` return the stack set id. Resource updates require that original id; deleting a resource whose original id is gone succeeds. Changing `StackSetName` or `PermissionModel` replaces the resource. `UpdateReplacePolicy: Retain` preserves the displaced set; replacement rollback restores the previous identity and removes the replacement. In-place rollback restores the saved configuration, deployment targets and instances. A failed restore keeps its snapshot for `ContinueUpdateRollback`. `AdministrationRoleARN`, `ExecutionRoleName`, `OperationPreferences`, `CallAs` and `ParameterOverrides` are not applied.
`CreateStackInstances` and `UpdateStackSet` execute the backing CloudFormation stacks in each target account. A failed resource can therefore drive the backing stack through rollback and leave the stack instance `INOPERABLE` with detailed status `FAILED`; the StackSet operation is reported as `FAILED` instead of being forced to success.
Operation IDs are recorded and validated. Duplicate IDs return `OperationIdAlreadyExistsException`, missing stack sets return `StackSetNotFoundException`, and missing operation IDs return `OperationNotFoundException`. Invalid targets and request shapes use the CloudFormation query-protocol validation errors. Operations complete locally, so `OperationInProgressException` is only reachable when local operation state actually overlaps; Floci does not inject concurrency failures solely to exercise an error code.
@@ -240,7 +242,7 @@ cross-resource references.
| WAFv2 | `IPSet`, `LoggingConfiguration`, `WebACL`, `WebACLAssociation` |
| Config | `ConfigRule` |
| Bedrock AgentCore | `Runtime` (Ref returns the AgentRuntimeId; CapacityProviderConfiguration, FilesystemConfigurations, LifecycleConfiguration, PlatformVersion and RequestHeaderConfiguration are accepted and not stored), `RuntimeEndpoint` (Ref returns the endpoint ARN; Tags are accepted and not stored), `Memory` (Ref returns the memory ARN; MemoryStrategies, IndexedKeys, NamespaceKeys and StreamDeliveryResources are accepted and not stored) |
| CloudFormation | `CustomResource`, `Custom::DynamoDBReplica` (applied natively against DynamoDB, not via a provider Lambda), `Stack` (nested stacks), `Custom::*` (Lambda-backed) |
| CloudFormation | `CustomResource`, `Custom::DynamoDBReplica` (applied natively against DynamoDB, not via a provider Lambda), `StackSet`, `Stack` (nested stacks), `Custom::*` (Lambda-backed) |
| CloudTrail | `Trail` |
| CDK | `CDK::Metadata` (accepted; no-op) |
<!-- floci:cfn-types:end -->
@@ -41,6 +41,7 @@ import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.regex.Pattern;
@@ -231,36 +232,63 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
Boolean autoDeploymentEnabled,
Boolean retainStacksOnAccountRemoval,
Boolean managedExecutionActive) {
return updateStackSet(name, templateBody, parameters, capabilities, tags, description, requestedOperationId,
autoDeploymentEnabled, retainStacksOnAccountRemoval, managedExecutionActive, false);
}
public synchronized StackSetOperation updateStackSetResource(String name, String templateBody,
Map<String, String> parameters,
List<String> capabilities, Map<String, String> tags,
String description, Boolean autoDeploymentEnabled,
Boolean retainStacksOnAccountRemoval,
Boolean managedExecutionActive) {
return updateStackSet(name, templateBody, parameters, capabilities, tags, description, null,
autoDeploymentEnabled, retainStacksOnAccountRemoval, managedExecutionActive, true);
}
private StackSetOperation updateStackSet(String name, String templateBody, Map<String, String> parameters,
List<String> capabilities, Map<String, String> tags, String description,
String requestedOperationId, Boolean autoDeploymentEnabled,
Boolean retainStacksOnAccountRemoval, Boolean managedExecutionActive,
boolean replaceSettings) {
StackSet ss = getStackSetOrThrow(name);
if (replaceSettings) {
if ("SERVICE_MANAGED".equals(ss.getPermissionModel())) {
autoDeploymentEnabled = Boolean.TRUE.equals(autoDeploymentEnabled);
}
retainStacksOnAccountRemoval = Boolean.TRUE.equals(retainStacksOnAccountRemoval);
managedExecutionActive = Boolean.TRUE.equals(managedExecutionActive);
}
if (autoDeploymentEnabled != null && !"SERVICE_MANAGED".equals(ss.getPermissionModel())) {
throw new AwsException("InvalidOperationException",
"AutoDeployment is valid only for SERVICE_MANAGED StackSets.", 400);
}
// Checked against the template and parameters the update leaves the stack set with, before
// either is changed or an operation is recorded.
String keptTemplate = templateBody != null && !templateBody.isBlank() ? templateBody : ss.getTemplateBody();
requireValidTemplate(keptTemplate);
cfnService.requireParameterValues(keptTemplate,
parameters != null && !parameters.isEmpty() ? parameters : ss.getParameters());
Map<String, String> updatedParameters = replaceSettings
? (parameters == null ? Map.of() : parameters)
: (parameters != null && !parameters.isEmpty() ? parameters : ss.getParameters());
cfnService.requireParameterValues(keptTemplate, updatedParameters);
String operationId = reserveOperation(name, "UPDATE", requestedOperationId).getOperationId();
if (templateBody != null && !templateBody.isBlank()) {
ss.setTemplateBody(templateBody);
}
if (parameters != null && !parameters.isEmpty()) {
ss.setParameters(new LinkedHashMap<>(parameters));
}
if (capabilities != null && !capabilities.isEmpty()) {
ss.setParameters(new LinkedHashMap<>(updatedParameters));
if (replaceSettings || (capabilities != null && !capabilities.isEmpty())) {
ss.getCapabilities().clear();
ss.getCapabilities().addAll(capabilities);
if (capabilities != null) {
ss.getCapabilities().addAll(capabilities);
}
}
if (tags != null && !tags.isEmpty()) {
ss.setTags(new LinkedHashMap<>(tags));
if (replaceSettings || (tags != null && !tags.isEmpty())) {
ss.setTags(tags == null ? new LinkedHashMap<>() : new LinkedHashMap<>(tags));
}
if (description != null) {
if (replaceSettings || description != null) {
ss.setDescription(description);
}
if (autoDeploymentEnabled != null) {
if (!"SERVICE_MANAGED".equals(ss.getPermissionModel())) {
completeOperation(name, operationId, "FAILED");
throw new AwsException("InvalidOperationException",
"AutoDeployment is valid only for SERVICE_MANAGED StackSets.", 400);
}
ss.setAutoDeploymentEnabled(autoDeploymentEnabled);
}
if (retainStacksOnAccountRemoval != null) ss.setRetainStacksOnAccountRemoval(retainStacksOnAccountRemoval);
@@ -301,7 +329,7 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
}
}
public void deleteStackSet(String name) {
public synchronized void deleteStackSet(String name) {
getStackSetOrThrow(name);
if (!listStackInstances(name, null, null).isEmpty()) {
throw new AwsException("StackSetNotEmptyException",
@@ -311,6 +339,43 @@ public class StackSetService implements PassedRoleLookup, AccountPlacementListen
LOG.infov("Deleted StackSet: {0}", name);
}
public synchronized boolean mutateStackSetResource(String stackSetId, Consumer<StackSet> mutation) {
if (stackSetId == null || stackSetId.indexOf(':') < 1) {
return false;
}
String name = stackSetId.substring(0, stackSetId.indexOf(':'));
StackSet stackSet = stackSets.get(name).orElse(null);
if (stackSet == null || !stackSetId.equals(stackSet.getStackSetId())) {
return false;
}
mutation.accept(stackSet);
return true;
}
/**
* Deletes every stack instance with its stack, then the stack set, as deleting an
* {@code AWS::CloudFormation::StackSet} resource does. A stack set already gone is left alone.
*/
public synchronized void deleteStackSetWithInstances(String name) {
StackSet stackSet = stackSets.get(name).orElse(null);
if (stackSet == null) {
return;
}
for (StackInstance instance : listStackInstances(name, null, null)) {
removeInstance(stackSet, instance, false);
}
if (listStackInstances(name, null, null).isEmpty()) {
deleteAutoDeploymentTargets(name);
}
deleteStackSet(name);
}
private void deleteAutoDeploymentTargets(String name) {
for (StackSetAutoDeploymentTarget target : listStackSetAutoDeploymentTargets(name)) {
autoDeploymentTargets.delete(name + "::" + target.getOrganizationalUnitId());
}
}
// ── Instances ──────────────────────────────────────────────────────────────
public StackSetOperation createStackInstances(String name, List<String> accounts, List<String> regions) {
@@ -134,6 +134,8 @@ public final class CfnRollback {
*/
public static final String DASHBOARD_UPDATE_SNAPSHOT_ATTR = "__FlociDashboardUpdateSnapshot";
public static final String STACK_SET_UPDATE_SNAPSHOT_ATTR = "__FlociStackSetUpdateSnapshot";
/**
* Holds the configuration and tags a Route 53 health check carried before an in-place update
* changed them, so a failed stack update can put them back. Written by
@@ -0,0 +1,354 @@
package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RequestScopes;
import io.floci.aws.services.cloudformation.CloudFormationService;
import io.floci.aws.services.cloudformation.StackSetService;
import io.floci.aws.services.cloudformation.model.StackInstance;
import io.floci.aws.services.cloudformation.model.StackResource;
import io.floci.aws.services.cloudformation.model.StackSet;
import io.floci.aws.services.cloudformation.model.StackSetAutoDeploymentTarget;
import io.floci.aws.services.cloudformation.model.StackSetOperation;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* Provisions {@code AWS::CloudFormation::StackSet}: the stack set, then a stack instance in every account and
* Region its {@code StackInstancesGroup} names, through {@link StackSetService} as the StackSets API does.
* {@code Ref} and {@code Fn::GetAtt StackSetId} return the stack set's id. An update applies the template,
* parameters and settings to every instance, deploys to targets the template adds and removes the instances
* of the targets and Regions it drops; deleting the resource deletes every instance and then the stack set.
*
* @see <a href="https://docs.aws.amazon.com/AWSCloudFormation/latest/TemplateReference/aws-resource-cloudformation-stackset.html">AWS::CloudFormation::StackSet</a>
*/
@ApplicationScoped
public class StackSetCfnProvisioner implements CfnResourceProvisioner {
private static final String STACK_SET = "AWS::CloudFormation::StackSet";
private static final String SERVICE_MANAGED = "SERVICE_MANAGED";
private static final ObjectMapper MAPPER = new ObjectMapper();
private static final CreateOnlyInputs CREATE_ONLY_INPUTS =
new CreateOnlyInputs("__FlociStackSetInputs", "__FlociStackSetPriorInputs");
private final Instance<StackSetService> stackSetService;
private final Instance<CloudFormationService> cfnService;
@Inject
public StackSetCfnProvisioner(Instance<StackSetService> stackSetService, Instance<CloudFormationService> cfnService) {
this.stackSetService = stackSetService;
this.cfnService = cfnService;
}
@Override
public Set<String> resourceTypes() {
return Set.of(STACK_SET);
}
@Override
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
String permissionModel = ctx.resolveOptional(props, "PermissionModel");
if (permissionModel == null || permissionModel.isBlank()) {
throw new AwsException("ValidationError", "PermissionModel is required for AWS::CloudFormation::StackSet", 400);
}
String explicitName = ctx.resolveOptional(props, "StackSetName");
if (explicitName == null || explicitName.isBlank()) {
throw new AwsException("ValidationError", "StackSetName is required for AWS::CloudFormation::StackSet", 400);
}
StackSetService stackSets = stackSetService.get();
String templateBody = cfnService.get().resolveTemplateBody(
ctx.resolveOptional(props, "TemplateBody"), ctx.resolveOptional(props, "TemplateURL"));
Map<String, String> parameters = resolveParameters(props, ctx);
List<String> capabilities = ctx.resolveStringList(props, "Capabilities");
Map<String, String> tags = ctx.resolveTags(props, "Tags");
String description = ctx.resolveOptional(props, "Description");
JsonNode autoDeployment = props.path("AutoDeployment");
List<InstanceGroup> groups = resolveGroups(props, ctx);
if (ctx.isUpdate()) {
if (requiresUpdateRecovery(r)) {
rollbackUpdate(r);
}
ReplacementCleanup.endRollbackRetry(r);
}
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
String inputs = createOnlyInputs(explicitName, permissionModel);
Runnable create = () -> {
String name = explicitName;
StackSet stackSet = stackSets.createStackSet(name, templateBody, parameters, capabilities, tags, description,
permissionModel,
Boolean.TRUE.equals(optionalBoolean(autoDeployment, "Enabled", ctx)),
Boolean.TRUE.equals(optionalBoolean(autoDeployment, "RetainStacksOnAccountRemoval", ctx)),
Boolean.TRUE.equals(optionalBoolean(props.path("ManagedExecution"), "Active", ctx)));
setIdentity(r, stackSet);
CREATE_ONLY_INPUTS.record(r, ctx, attributesBefore, inputs);
ReplacementCleanup.record(r, ctx, attributesBefore);
CfnRollback.guarded(r, ctx, true, () -> delete(STACK_SET, stackSet.getStackSetId(), ctx.region()), () -> { },
() -> createInstances(stackSets, name, groups));
};
boolean updating = ctx.isUpdate() && !CfnResourceDispatcher.isStub(ctx.priorPhysicalId(), attributesBefore);
if (updating) {
boolean updated = stackSets.mutateStackSetResource(ctx.priorPhysicalId(), stackSet -> {
String name = stackSet.getStackSetName();
String priorInputs = CREATE_ONLY_INPUTS.read(attributesBefore);
if (priorInputs == null) {
priorInputs = createOnlyInputs(ctx.previouslyDeclared("StackSetName") ? name : null,
stackSet.getPermissionModel());
}
if (!inputs.equals(priorInputs)) {
try {
if (name.equals(explicitName)) {
throw CfnExceptions.customNamedReplacement(name);
}
create.run();
} catch (RuntimeException e) {
if (ctx.priorPhysicalId().equals(r.getPhysicalId())) {
r.getAttributes().put(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR, "true");
}
throw e;
}
return;
}
boolean serviceManaged = SERVICE_MANAGED.equals(stackSet.getPermissionModel());
Map<String, Set<String>> deployed = deployedTargets(stackSets, name, serviceManaged);
ObjectNode snapshot = MAPPER.createObjectNode().put("account", ctx.accountId()).put("region", ctx.region());
snapshot.set("stackSet", MAPPER.valueToTree(stackSet));
snapshot.set("targets", MAPPER.valueToTree(deployed));
r.getAttributes().put(CfnRollback.STACK_SET_UPDATE_SNAPSHOT_ATTR, snapshot.toString());
requireSuccess(stackSets.updateStackSetResource(name, templateBody, parameters, capabilities, tags, description,
optionalBoolean(autoDeployment, "Enabled", ctx),
optionalBoolean(autoDeployment, "RetainStacksOnAccountRemoval", ctx),
optionalBoolean(props.path("ManagedExecution"), "Active", ctx)));
createInstances(stackSets, name, groups);
removeDroppedTargets(stackSets, name, serviceManaged, deployed, groups);
setIdentity(r, stackSet);
CREATE_ONLY_INPUTS.record(r, ctx, attributesBefore, inputs);
ReplacementCleanup.record(r, ctx, attributesBefore);
});
if (!updated) {
throw new AwsException("StackSetNotFoundException", "The original StackSet no longer exists", 404);
}
return;
}
create.run();
}
private static String createOnlyInputs(String name, String permissionModel) {
return MAPPER.createObjectNode().put("name", name).put("permissionModel", permissionModel).toString();
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return ReplacementCleanup.cleanupPhysicalId(resource);
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.STACK_SET_UPDATE_SNAPSHOT_ATTR);
CREATE_ONLY_INPUTS.clearPrior(resource);
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.STACK_SET_UPDATE_SNAPSHOT_ATTR);
CREATE_ONLY_INPUTS.clearPrior(resource);
ReplacementCleanup.clear(resource);
}
@Override
public void mergeFailedUpdateResourceTracking(StackResource previous, StackResource attempted) {
ReplacementCleanup.mergeDisplaced(previous, attempted);
}
@Override
public boolean retainsFailedUpdateState(StackResource resource) {
return requiresUpdateRecovery(resource);
}
@Override
public boolean requiresUpdateRecovery(StackResource resource) {
return resource.getAttributes().containsKey(CfnRollback.STACK_SET_UPDATE_SNAPSHOT_ATTR);
}
@Override
public boolean rollbackUpdate(StackResource resource) {
String attemptedId = resource.getPhysicalId();
boolean hasPriorInputs = CREATE_ONLY_INPUTS.hasPrior(resource);
try {
JsonNode snapshot = CfnRollback.updateSnapshot(resource, CfnRollback.STACK_SET_UPDATE_SNAPSHOT_ATTR);
if (snapshot != null) {
restoreUpdateSnapshot(snapshot);
resource.getAttributes().remove(CfnRollback.STACK_SET_UPDATE_SNAPSHOT_ATTR);
ReplacementCleanup.rollback(resource, this::delete);
return true;
}
return ReplacementCleanup.rollback(resource, this::delete);
} finally {
if (hasPriorInputs && !Objects.equals(attemptedId, resource.getPhysicalId())) {
CREATE_ONLY_INPUTS.restorePrior(resource);
}
}
}
private void restoreUpdateSnapshot(JsonNode snapshot) {
StackSet prior = MAPPER.convertValue(snapshot.path("stackSet"), StackSet.class);
boolean serviceManaged = SERVICE_MANAGED.equals(prior.getPermissionModel());
List<InstanceGroup> groups = new ArrayList<>();
snapshot.path("targets").properties().forEach(target -> {
List<String> regions = new ArrayList<>();
target.getValue().forEach(region -> regions.add(region.asText()));
List<String> accounts = serviceManaged ? List.of() : List.of(target.getKey());
List<String> organizationalUnits = serviceManaged ? List.of(target.getKey()) : List.of();
groups.add(new InstanceGroup(accounts, organizationalUnits, regions));
});
boolean restored = RequestScopes.callAs(snapshot.path("account").asText(), snapshot.path("region").asText(),
() -> {
StackSetService stackSets = stackSetService.get();
return stackSets.mutateStackSetResource(prior.getStackSetId(), current -> {
String name = prior.getStackSetName();
removeDroppedTargets(stackSets, name, serviceManaged,
deployedTargets(stackSets, name, serviceManaged), groups);
requireSuccess(stackSets.updateStackSetResource(name, prior.getTemplateBody(),
prior.getParameters(), prior.getCapabilities(), prior.getTags(), prior.getDescription(),
serviceManaged ? prior.isAutoDeploymentEnabled() : null,
prior.isRetainStacksOnAccountRemoval(), prior.isManagedExecutionActive()));
createInstances(stackSets, name, groups);
});
});
if (!restored) {
throw new AwsException("StackSetNotFoundException", "The original StackSet no longer exists", 404);
}
}
@Override
public void delete(String resourceType, String physicalId, String region) {
StackSetService stackSets = stackSetService.get();
stackSets.mutateStackSetResource(physicalId,
stackSet -> stackSets.deleteStackSetWithInstances(stackSet.getStackSetName()));
}
/** One {@code StackInstancesGroup} entry: the accounts or the root and OUs it targets, and its Regions. */
private record InstanceGroup(List<String> accounts, List<String> organizationalUnits, List<String> regions) {
}
private static void setIdentity(StackResource r, StackSet stackSet) {
r.setPhysicalId(stackSet.getStackSetId());
r.getAttributes().put("StackSetId", stackSet.getStackSetId());
}
private static void createInstances(StackSetService stackSets, String name, List<InstanceGroup> groups) {
for (InstanceGroup group : groups) {
requireSuccess(stackSets.createStackInstances(name, group.accounts(), group.regions(),
group.organizationalUnits(), null));
}
}
/**
* The targets in place and their Regions, read before an update deploys anything: the targets recorded for a
* service-managed stack set, which also covers a target that has no instance, and the instances of a
* self-managed one.
*/
private static Map<String, Set<String>> deployedTargets(StackSetService stackSets, String name,
boolean serviceManaged) {
Map<String, Set<String>> deployed = new LinkedHashMap<>();
if (serviceManaged) {
for (StackSetAutoDeploymentTarget target : stackSets.listStackSetAutoDeploymentTargets(name)) {
deployed.computeIfAbsent(target.getOrganizationalUnitId(), ignored -> new LinkedHashSet<>())
.addAll(target.getRegions());
}
} else {
for (StackInstance instance : stackSets.listStackInstances(name, null, null)) {
deployed.computeIfAbsent(instance.getAccount(), ignored -> new LinkedHashSet<>()).add(instance.getRegion());
}
}
return deployed;
}
/**
* Deletes the instances of every target and Region the template no longer names: a target it dropped, or a
* Region it dropped from a target it kept.
*/
private static void removeDroppedTargets(StackSetService stackSets, String name, boolean serviceManaged,
Map<String, Set<String>> deployed, List<InstanceGroup> groups) {
Map<String, Set<String>> wanted = new LinkedHashMap<>();
for (InstanceGroup group : groups) {
for (String target : serviceManaged ? group.organizationalUnits() : group.accounts()) {
wanted.computeIfAbsent(target, ignored -> new LinkedHashSet<>()).addAll(group.regions());
}
}
deployed.forEach((target, regions) -> {
Set<String> dropped = new LinkedHashSet<>(regions);
dropped.removeAll(wanted.getOrDefault(target, Set.of()));
if (dropped.isEmpty()) {
return;
}
requireSuccess(serviceManaged
? stackSets.deleteStackInstances(name, List.of(), List.copyOf(dropped), List.of(target), false)
: stackSets.deleteStackInstances(name, List.of(target), List.copyOf(dropped), List.of(), false));
});
}
private static void requireSuccess(StackSetOperation operation) {
if ("FAILED".equals(operation.getStatus())) {
throw new AwsException("ValidationError", "Stack set operation " + operation.getOperationId()
+ " was unexpectedly stopped or failed", 400);
}
}
private static List<InstanceGroup> resolveGroups(JsonNode props, ProvisionContext ctx) {
List<InstanceGroup> groups = new ArrayList<>();
JsonNode group = props.path("StackInstancesGroup");
JsonNode entries = group.isMissingNode() || group.isNull() ? null : ctx.engine().resolveNode(group);
if (entries == null || !entries.isArray()) {
return groups;
}
for (JsonNode entry : entries) {
JsonNode targets = entry.path("DeploymentTargets");
groups.add(new InstanceGroup(ctx.resolveStringList(targets, "Accounts"),
ctx.resolveStringList(targets, "OrganizationalUnitIds"),
ctx.resolveStringList(entry, "Regions")));
}
return groups;
}
private static Map<String, String> resolveParameters(JsonNode props, ProvisionContext ctx) {
Map<String, String> parameters = new LinkedHashMap<>();
JsonNode declared = props.path("Parameters");
JsonNode entries = declared.isMissingNode() || declared.isNull() ? null : ctx.engine().resolveNode(declared);
if (entries == null || !entries.isArray()) {
return parameters;
}
for (JsonNode entry : entries) {
String key = ctx.engine().resolve(entry.path("ParameterKey"));
if (key != null && !key.isBlank()) {
String value = ctx.engine().resolve(entry.path("ParameterValue"));
parameters.put(key, value == null ? "" : value);
}
}
return parameters;
}
private static Boolean optionalBoolean(JsonNode node, String name, ProvisionContext ctx) {
String value = ctx.resolveOptional(node.isObject() ? node : null, name);
return value == null || value.isBlank() ? null : Boolean.valueOf(value);
}
}
@@ -168,6 +168,10 @@
"AWS::CloudFormation::CustomResource": [
"ServiceToken"
],
"AWS::CloudFormation::StackSet": [
"PermissionModel",
"StackSetName"
],
"AWS::CloudFront::CachePolicy": [],
"AWS::CloudFront::Distribution": [],
"AWS::CloudFront::Function": [
@@ -38,11 +38,12 @@ class CfnProvisionerFixtureTest {
/**
* Provisioners the fixture cannot build from a single service, so they must be passed to
* {@code provisioners(...)} explicitly. Both take collaborators beyond one service
* ({@code RegionResolver} and an {@code ObjectMapper}), which the Builder does not model.
* {@code provisioners(...)} explicitly. The CodeBuild and CodePipeline ones take collaborators beyond one
* service ({@code RegionResolver} and an {@code ObjectMapper}), which the Builder does not model, and the
* StackSet one takes CloudFormation's own services, which deploy each stack instance as a stack.
*/
private static final Set<String> NOT_INFERABLE =
Set.of("CodeBuildCfnProvisioner", "CodePipelineCfnProvisioner");
Set.of("CodeBuildCfnProvisioner", "CodePipelineCfnProvisioner", "StackSetCfnProvisioner");
/**
* Builder setters that replace the inferred registry outright rather than naming a service.
@@ -1,19 +1,19 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.CfnRequests;
import io.floci.aws.testing.OrganizationsFixture;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.json.JsonPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
@@ -28,9 +28,8 @@ import static org.junit.jupiter.api.Assertions.assertNotEquals;
class CloudFormationServiceManagedStackSetsIntegrationTest {
private static final String MANAGEMENT = "555555555555";
private static final String REGION = "us-east-1";
private static final String ORG_TARGET = "AWSOrganizationsV20161128.";
private final Set<String> organizationOwners = new LinkedHashSet<>();
private final OrganizationsFixture organizationsFixture = new OrganizationsFixture();
@BeforeAll
static void configureRestAssured() {
@@ -55,10 +54,10 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
.extract().jsonPath().getString("OrganizationalUnit.Id");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String directAccount = createAccount("stacksets-direct-" + suffix + "@example.com", "StackSetsDirect");
String nestedAccount = createAccount("stacksets-nested-" + suffix + "@example.com", "StackSetsNested");
moveAccount(directAccount, rootId, parentOu);
moveAccount(nestedAccount, rootId, childOu);
String directAccount = organizationsFixture.createAccount(MANAGEMENT, "stacksets-direct-" + suffix + "@example.com", "StackSetsDirect");
String nestedAccount = organizationsFixture.createAccount(MANAGEMENT, "stacksets-nested-" + suffix + "@example.com", "StackSetsNested");
organizationsFixture.moveAccount(MANAGEMENT, directAccount, rootId, parentOu);
organizationsFixture.moveAccount(MANAGEMENT, nestedAccount, rootId, childOu);
cloudFormation("ActivateOrganizationsAccess")
.post("/").then().statusCode(200);
@@ -487,9 +486,9 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
void autoDeploymentFollowsAnAccountIntoAndOutOfATargetedOrganizationalUnit() {
String management = "626262626262";
String rootId = createOrganizationWithTrustedAccess(management);
String targetOu = createOu(management, rootId, "AutoTarget");
String childOu = createOu(management, targetOu, "AutoTargetChild");
String otherOu = createOu(management, rootId, "AutoOther");
String targetOu = organizationsFixture.createOu(management, rootId, "AutoTarget");
String childOu = organizationsFixture.createOu(management, targetOu, "AutoTargetChild");
String otherOu = organizationsFixture.createOu(management, rootId, "AutoOther");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "auto-ou-" + suffix;
String queue = "auto-ou-q-" + suffix;
@@ -503,11 +502,11 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
.body(containsString("<member>" + REGION + "</member>"))
.body(containsString("<member>us-west-2</member>"));
String account = createAccount(management, "auto-ou-" + suffix + "@example.com", "AutoOu");
String account = organizationsFixture.createAccount(management, "auto-ou-" + suffix + "@example.com", "AutoOu");
assertQueueAbsent(account, queue);
assertNoInstance(management, stackSet, account);
moveAccount(management, account, rootId, childOu);
organizationsFixture.moveAccount(management, account, rootId, childOu);
assertQueueVisible(account, queue);
assertEquals(3, operationIds(management, stackSet).size());
cloudFormation(management, "ListStackInstances")
@@ -519,11 +518,11 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
.body(containsString("<OrganizationalUnitId>" + targetOu + "</OrganizationalUnitId>"))
.body(containsString("<DetailedStatus>SUCCEEDED</DetailedStatus>"));
moveAccount(management, account, childOu, targetOu);
organizationsFixture.moveAccount(management, account, childOu, targetOu);
assertQueueVisible(account, queue);
assertEquals(3, operationIds(management, stackSet).size());
moveAccount(management, account, targetOu, otherOu);
organizationsFixture.moveAccount(management, account, targetOu, otherOu);
assertQueueAbsent(account, queue);
assertNoInstance(management, stackSet, account);
assertEquals(4, operationIds(management, stackSet).size());
@@ -540,7 +539,7 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
List<String> initialOperations = operationIds(management, stackSet);
assertEquals(1, initialOperations.size());
String account = createAccount(management, "auto-operations-" + suffix + "@example.com", "AutoOperations");
String account = organizationsFixture.createAccount(management, "auto-operations-" + suffix + "@example.com", "AutoOperations");
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertEquals(2, operationIds(management, stackSet).size()));
List<String> afterCreate = operationIds(management, stackSet);
@@ -564,13 +563,13 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
void deletingOneTargetRegionPreservesAutomaticDeploymentToTheOtherRegion() {
String management = "676767676767";
String rootId = createOrganizationWithTrustedAccess(management);
String targetOu = createOu(management, rootId, "RemainingRegion");
String targetOu = organizationsFixture.createOu(management, rootId, "RemainingRegion");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "auto-region-" + suffix;
String queue = "auto-region-q-" + suffix;
String existingAccount = createAccount(management,
String existingAccount = organizationsFixture.createAccount(management,
"auto-region-existing-" + suffix + "@example.com", "ExistingRegion");
moveAccount(management, existingAccount, rootId, targetOu);
organizationsFixture.moveAccount(management, existingAccount, rootId, targetOu);
createAutoDeployingStackSet(management, stackSet, queue, "false");
createStackInstances(management, stackSet, targetOu, REGION);
createStackInstances(management, stackSet, targetOu, "us-west-2");
@@ -587,8 +586,8 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
.body(containsString("<member>" + REGION + "</member>"))
.body(not(containsString("<member>us-west-2</member>")));
String account = createAccount(management, "auto-region-" + suffix + "@example.com", "RemainingRegion");
moveAccount(management, account, rootId, targetOu);
String account = organizationsFixture.createAccount(management, "auto-region-" + suffix + "@example.com", "RemainingRegion");
organizationsFixture.moveAccount(management, account, rootId, targetOu);
assertQueueVisible(account, queue);
cloudFormation(management, "ListStackInstances")
.formParam("StackSetName", stackSet)
@@ -608,7 +607,7 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
createAutoDeployingStackSet(management, stackSet, queue, "false");
createStackInstances(management, stackSet, rootId, REGION);
String account = createAccount(management, "auto-root-" + suffix + "@example.com", "AutoRoot");
String account = organizationsFixture.createAccount(management, "auto-root-" + suffix + "@example.com", "AutoRoot");
assertQueueVisible(account, queue);
assertQueueAbsent(management, queue);
@@ -622,18 +621,18 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
void autoDeploymentRetainsTheStackOfAnAccountThatLeavesItsTargets() {
String management = "646464646464";
String rootId = createOrganizationWithTrustedAccess(management);
String targetOu = createOu(management, rootId, "RetainTarget");
String targetOu = organizationsFixture.createOu(management, rootId, "RetainTarget");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "auto-retain-" + suffix;
String queue = "auto-retain-q-" + suffix;
createAutoDeployingStackSet(management, stackSet, queue, "true");
createStackInstances(management, stackSet, targetOu, REGION);
String account = createAccount(management, "auto-retain-" + suffix + "@example.com", "AutoRetain");
moveAccount(management, account, rootId, targetOu);
String account = organizationsFixture.createAccount(management, "auto-retain-" + suffix + "@example.com", "AutoRetain");
organizationsFixture.moveAccount(management, account, rootId, targetOu);
assertQueueVisible(account, queue);
moveAccount(management, account, targetOu, rootId);
organizationsFixture.moveAccount(management, account, targetOu, rootId);
assertNoInstance(management, stackSet, account);
assertQueueVisible(account, queue);
}
@@ -642,7 +641,7 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
void returningAccountGetsANewStackWithoutAdoptingItsRetainedStack() {
String management = "707070707070";
String rootId = createOrganizationWithTrustedAccess(management);
String targetOu = createOu(management, rootId, "RetainedReturn");
String targetOu = organizationsFixture.createOu(management, rootId, "RetainedReturn");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "retained-return-" + suffix;
cloudFormation(management, "CreateStackSet")
@@ -653,17 +652,17 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
.formParam("AutoDeployment.RetainStacksOnAccountRemoval", "true")
.post("/").then().statusCode(200);
createStackInstances(management, stackSet, targetOu, REGION);
String account = createAccount(management, "retained-return-" + suffix + "@example.com", "RetainedReturn");
moveAccount(management, account, rootId, targetOu);
String account = organizationsFixture.createAccount(management, "retained-return-" + suffix + "@example.com", "RetainedReturn");
organizationsFixture.moveAccount(management, account, rootId, targetOu);
String retained = stackIdForInstance(management, stackSet, account);
moveAccount(management, account, targetOu, rootId);
organizationsFixture.moveAccount(management, account, targetOu, rootId);
assertNoInstance(management, stackSet, account);
cloudFormation(account, "DescribeStacks")
.formParam("StackName", retained)
.post("/").then().statusCode(200)
.body(containsString("CREATE_COMPLETE"));
moveAccount(management, account, rootId, targetOu);
organizationsFixture.moveAccount(management, account, rootId, targetOu);
String replacement = stackIdForInstance(management, stackSet, account);
assertNotEquals(retained, replacement);
@@ -677,7 +676,7 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
void stackSetWithoutAutoDeploymentIgnoresAccountsMovedIntoItsTargets() {
String management = "656565656565";
String rootId = createOrganizationWithTrustedAccess(management);
String targetOu = createOu(management, rootId, "ManualTarget");
String targetOu = organizationsFixture.createOu(management, rootId, "ManualTarget");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "manual-" + suffix;
String queue = "manual-q-" + suffix;
@@ -689,20 +688,14 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
.post("/").then().statusCode(200);
createStackInstances(management, stackSet, targetOu, REGION);
String account = createAccount(management, "manual-" + suffix + "@example.com", "Manual");
moveAccount(management, account, rootId, targetOu);
String account = organizationsFixture.createAccount(management, "manual-" + suffix + "@example.com", "Manual");
organizationsFixture.moveAccount(management, account, rootId, targetOu);
assertQueueAbsent(account, queue);
assertNoInstance(management, stackSet, account);
}
private String createOrganizationWithTrustedAccess(String management) {
organizations(management, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
.post("/").then().statusCode(200);
cloudFormation(management, "ActivateOrganizationsAccess")
.post("/").then().statusCode(200);
return organizations(management, "ListRoots", "{}")
.post("/").then().statusCode(200)
.extract().jsonPath().getString("Roots[0].Id");
return organizationsFixture.createWithTrustedAccess(management);
}
private List<String> operationIds(String management, String stackSet) {
@@ -725,12 +718,6 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
.body(containsString("<EndTimestamp>")));
}
private String createOu(String management, String parentId, String name) {
return organizations(management, "CreateOrganizationalUnit",
"{\"ParentId\":\"" + parentId + "\",\"Name\":\"" + name + "\"}")
.post("/").then().statusCode(200)
.extract().jsonPath().getString("OrganizationalUnit.Id");
}
private void createAutoDeployingStackSet(String management, String stackSet, String queue, String retainStacks) {
cloudFormation(management, "CreateStackSet")
@@ -750,20 +737,7 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
.post("/").then().statusCode(200);
}
private String createAccount(String management, String email, String name) {
return organizations(management, "CreateAccount",
"{\"Email\":\"" + email + "\",\"AccountName\":\"" + name + "\"}")
.post("/").then().statusCode(200)
.body("CreateAccountStatus.State", equalTo("SUCCEEDED"))
.extract().jsonPath().getString("CreateAccountStatus.AccountId");
}
private void moveAccount(String management, String accountId, String sourceParent, String destinationParent) {
organizations(management, "MoveAccount",
"{\"AccountId\":\"" + accountId + "\",\"SourceParentId\":\"" + sourceParent
+ "\",\"DestinationParentId\":\"" + destinationParent + "\"}")
.post("/").then().statusCode(200);
}
private void assertNoInstance(String management, String stackSet, String account) {
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> cloudFormation(management, "ListStackInstances")
@@ -789,66 +763,19 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
"DescribeStackInstanceResponse.DescribeStackInstanceResult.StackInstance.StackId");
}
private String createAccount(String email, String name) {
return createAccount(MANAGEMENT, email, name);
}
private void moveAccount(String accountId, String sourceParent, String destinationParent) {
moveAccount(MANAGEMENT, accountId, sourceParent, destinationParent);
}
private RequestSpecification organizations(String action, String body) {
return organizations(MANAGEMENT, action, body);
}
private RequestSpecification organizations(String account, String action, String body) {
if ("CreateOrganization".equals(action)) {
organizationOwners.add(account);
}
return given()
.header("Authorization", auth(account, "organizations"))
.header("X-Amz-Target", ORG_TARGET + action)
.contentType("application/x-amz-json-1.1")
.body(body);
return organizationsFixture.request(account, action, body);
}
/**
* Organizations state is shared by every test in the JVM and keyed by the management account,
* so an organization left behind here makes the next class that creates one under the same
* account fail with AlreadyInOrganizationException. Dismantle each one this test created:
* member accounts out, organizational units bottom-up, then the organization.
*/
@AfterEach
void deleteTheOrganizationsThisTestCreated() {
for (String owner : organizationOwners) {
if (organizations(owner, "DescribeOrganization", "{}").post("/").statusCode() != 200) {
continue;
}
JsonPath accounts = organizations(owner, "ListAccounts", "{}").post("/").jsonPath();
for (String accountId : accounts.getList("Accounts.Id", String.class)) {
if (!owner.equals(accountId)) {
organizations(owner, "RemoveAccountFromOrganization", "{\"AccountId\":\"" + accountId + "\"}")
.post("/").then().statusCode(200);
}
}
JsonPath roots = organizations(owner, "ListRoots", "{}").post("/").jsonPath();
for (String rootId : roots.getList("Roots.Id", String.class)) {
deleteOrganizationalUnitsUnder(owner, rootId);
}
organizations(owner, "DeleteOrganization", "{}").post("/").then().statusCode(200);
}
organizationOwners.clear();
}
private void deleteOrganizationalUnitsUnder(String owner, String parentId) {
JsonPath units = organizations(owner, "ListOrganizationalUnitsForParent", "{\"ParentId\":\"" + parentId + "\"}")
.post("/").jsonPath();
List<String> ouIds = units.getList("OrganizationalUnits.Id", String.class);
for (String ouId : ouIds) {
deleteOrganizationalUnitsUnder(owner, ouId);
organizations(owner, "DeleteOrganizationalUnit", "{\"OrganizationalUnitId\":\"" + ouId + "\"}")
.post("/").then().statusCode(200);
}
organizationsFixture.cleanup();
}
private RequestSpecification cloudFormation(String action) {
@@ -856,10 +783,8 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
}
private RequestSpecification cloudFormation(String account, String action) {
return given()
.header("Authorization", auth(account, "cloudformation"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", action);
return CfnRequests.cfn(action, null)
.header("Authorization", auth(account, "cloudformation"));
}
private void assertQueueVisible(String account, String queueName) {
@@ -887,8 +812,4 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
+ queueName + "\"}}}}";
}
private static String auth(String account, String service) {
return "AWS4-HMAC-SHA256 Credential=" + account + "/20260904/" + REGION + "/" + service
+ "/aws4_request, SignedHeaders=host, Signature=abc";
}
}
@@ -0,0 +1,708 @@
package io.floci.aws.services.cloudformation;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.testing.CfnRequests;
import io.floci.aws.testing.CfnStackWaits;
import io.floci.aws.testing.OrganizationsFixture;
import io.floci.aws.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.quarkus.test.junit.mockito.InjectSpy;
import io.restassured.response.Response;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import java.util.UUID;
import static io.floci.aws.testing.EnforcementFixtures.auth;
import static io.restassured.RestAssured.given;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.not;
import static org.hamcrest.Matchers.startsWith;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/** {@code AWS::CloudFormation::StackSet} deploys its instances through StackSets, end to end. */
@QuarkusTest
class StackSetCfnIntegrationTest {
private static final String MANAGEMENT = "676767676767";
private static final String REGION = "us-east-1";
private final OrganizationsFixture organizationsFixture = new OrganizationsFixture();
@InjectSpy
StackSetService stackSets;
@BeforeAll
static void configureRestAssured() {
RestAssuredJsonUtils.configureAwsContentTypes();
}
@Test
void serviceManagedStackSetResourceDeploysToItsTargetsAndFollowsUpdatesAndDeletion() throws Exception {
String rootId = organizationsFixture.createWithTrustedAccess(MANAGEMENT);
String targetOu = organizationsFixture.createOu(MANAGEMENT, rootId, "CfnStackSetTarget");
String otherOu = organizationsFixture.createOu(MANAGEMENT, rootId, "CfnStackSetOther");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String targetAccount = organizationsFixture.createAccount(MANAGEMENT,
"cfn-stackset-target-" + suffix + "@example.com", "CfnStackSet", targetOu, rootId);
String otherAccount = organizationsFixture.createAccount(MANAGEMENT,
"cfn-stackset-other-" + suffix + "@example.com", "CfnStackSet", otherOu, rootId);
String stack = "stackset-resource-" + suffix;
String stackSet = "cfn-stackset-" + suffix;
String queue = "cfn-stackset-q-" + suffix;
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", template(stackSet, queue),
"Parameters.member.1.ParameterKey", "Targets", "Parameters.member.1.ParameterValue", targetOu)
.then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String ref = output(stack, "StackSetRef");
assertThat(ref, startsWith(stackSet + ":"));
assertThat(output(stack, "StackSetId"), equalTo(ref));
assertQueue(targetAccount, queue, true);
assertQueue(otherAccount, queue, false);
cloudFormation("DescribeStackSet", "StackSetName", stackSet).then().statusCode(200)
.body(containsString("<PermissionModel>SERVICE_MANAGED</PermissionModel>"))
.body(containsString("<Enabled>true</Enabled>"))
.body(containsString("<ParameterValue>" + queue + "</ParameterValue>"))
.body(containsString("<member>" + targetOu + "</member>"));
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", template(stackSet, queue),
"Parameters.member.1.ParameterKey", "Targets", "Parameters.member.1.ParameterValue", otherOu)
.then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
assertQueue(targetAccount, queue, false);
assertQueue(otherAccount, queue, true);
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
cloudFormation("DescribeStackSet", "StackSetName", stackSet).then().statusCode(404);
assertQueue(otherAccount, queue, false);
}
@Test
void anUpdateRemovesTheInstancesOfARegionDroppedFromAKeptTarget() throws Exception {
String rootId = organizationsFixture.createWithTrustedAccess(MANAGEMENT);
String targetOu = organizationsFixture.createOu(MANAGEMENT, rootId, "CfnStackSetRegions");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String account = organizationsFixture.createAccount(MANAGEMENT,
"cfn-stackset-regions-" + suffix + "@example.com", "CfnStackSet", targetOu, rootId);
String stack = "stackset-regions-" + suffix;
String stackSet = "cfn-stackset-regions-" + suffix;
String queue = "cfn-stackset-regions-q-" + suffix;
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", template(stackSet, queue),
"Parameters.member.1.ParameterKey", "Targets", "Parameters.member.1.ParameterValue", targetOu,
"Parameters.member.2.ParameterKey", "Regions", "Parameters.member.2.ParameterValue", REGION + ",us-west-2")
.then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
assertQueue(account, queue, REGION, true);
assertQueue(account, queue, "us-west-2", true);
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", template(stackSet, queue),
"Parameters.member.1.ParameterKey", "Targets", "Parameters.member.1.ParameterValue", targetOu,
"Parameters.member.2.ParameterKey", "Regions", "Parameters.member.2.ParameterValue", REGION)
.then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
assertQueue(account, queue, REGION, true);
assertQueue(account, queue, "us-west-2", false);
cloudFormation("ListStackInstances", "StackSetName", stackSet).then().statusCode(200)
.body(containsString("<Region>" + REGION + "</Region>"))
.body(not(containsString("<Region>us-west-2</Region>")));
}
@Test
void anUpdateDroppingATargetWithNoInstancesStopsDeployingToIt() throws Exception {
String rootId = organizationsFixture.createWithTrustedAccess(MANAGEMENT);
String emptyOu = organizationsFixture.createOu(MANAGEMENT, rootId, "CfnStackSetEmpty");
String otherOu = organizationsFixture.createOu(MANAGEMENT, rootId, "CfnStackSetOtherEmpty");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stack = "stackset-empty-" + suffix;
String stackSet = "cfn-stackset-empty-" + suffix;
String queue = "cfn-stackset-empty-q-" + suffix;
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", template(stackSet, queue),
"Parameters.member.1.ParameterKey", "Targets", "Parameters.member.1.ParameterValue", emptyOu)
.then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", template(stackSet, queue),
"Parameters.member.1.ParameterKey", "Targets", "Parameters.member.1.ParameterValue", otherOu)
.then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String account = organizationsFixture.createAccount(MANAGEMENT,
"cfn-stackset-empty-" + suffix + "@example.com", "CfnStackSet", emptyOu, rootId);
assertQueue(account, queue, false);
cloudFormation("DescribeStackSet", "StackSetName", stackSet).then().statusCode(200)
.body(not(containsString("<member>" + emptyOu + "</member>")))
.body(containsString("<member>" + otherOu + "</member>"));
}
@Test
void missingPermissionModelFailsStackCreation() {
String stack = "missing-permission-model-" + UUID.randomUUID().toString().substring(0, 8);
ObjectMapper mapper = new ObjectMapper();
String body = mapper.createObjectNode().set("Resources", mapper.createObjectNode().set("StackSet",
mapper.createObjectNode().put("Type", "AWS::CloudFormation::StackSet")
.set("Properties", mapper.createObjectNode().put("StackSetName", stack).put("TemplateBody",
"{\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"}}}"))))
.toString();
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body).then().statusCode(200);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack, auth(MANAGEMENT, "cloudformation"));
assertEquals("ROLLBACK_COMPLETE", state.status());
assertTrue(CfnStackWaits.failedResourceReason(stack, auth(MANAGEMENT, "cloudformation"))
.contains("PermissionModel"));
}
@Test
void missingStackSetNameFailsStackCreation() {
String stack = "missing-stackset-name-" + UUID.randomUUID().toString().substring(0, 8);
ObjectNode body = simpleStackSetTemplate("temporary");
((ObjectNode) body.path("Resources").path("Set").path("Properties")).remove("StackSetName");
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack, auth(MANAGEMENT, "cloudformation"));
assertEquals("ROLLBACK_COMPLETE", state.status());
assertTrue(CfnStackWaits.failedResourceReason(stack, auth(MANAGEMENT, "cloudformation"))
.contains("StackSetName"));
}
@Test
void removingDeclaredCollectionsAndDescriptionClearsTheirStackSetValues() {
String stack = "removed-settings-" + UUID.randomUUID().toString().substring(0, 8);
String name = "set-" + stack;
ObjectMapper mapper = new ObjectMapper();
ObjectNode body = simpleStackSetTemplate(name);
ObjectNode properties = (ObjectNode) body.path("Resources").path("Set").path("Properties");
properties.put("TemplateBody", "{\"Parameters\":{\"Value\":{\"Type\":\"String\",\"Default\":\"default\"}},"
+ "\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"}}}");
properties.set("Parameters", mapper.createArrayNode().add(mapper.createObjectNode()
.put("ParameterKey", "Value").put("ParameterValue", "explicit")));
properties.set("Capabilities", mapper.createArrayNode().add("CAPABILITY_NAMED_IAM"));
properties.set("Tags", mapper.createArrayNode().add(mapper.createObjectNode()
.put("Key", "declared").put("Value", "value")));
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Description>original</Description>"))
.body(containsString("<ParameterValue>explicit</ParameterValue>"))
.body(containsString("<member>CAPABILITY_NAMED_IAM</member>"))
.body(containsString("<Key>declared</Key>"));
for (String key : new String[]{"Description", "Parameters", "Capabilities", "Tags"}) {
properties.remove(key);
}
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(not(containsString("<Description>original</Description>")))
.body(not(containsString("<ParameterValue>explicit</ParameterValue>")))
.body(not(containsString("<member>CAPABILITY_NAMED_IAM</member>")))
.body(not(containsString("<Key>declared</Key>")));
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
@Test
void apiUpdateStillKeepsOmittedSettings() {
String name = "api-keep-" + UUID.randomUUID().toString().substring(0, 8);
String templateBody = "{\"Parameters\":{\"Value\":{\"Type\":\"String\"}},"
+ "\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"}}}";
cloudFormation("CreateStackSet", "StackSetName", name, "PermissionModel", "SELF_MANAGED",
"TemplateBody", templateBody, "Description", "keep",
"Parameters.member.1.ParameterKey", "Value", "Parameters.member.1.ParameterValue", "explicit",
"Capabilities.member.1", "CAPABILITY_NAMED_IAM", "Tags.member.1.Key", "declared",
"Tags.member.1.Value", "value").then().statusCode(200);
cloudFormation("UpdateStackSet", "StackSetName", name, "TemplateBody", templateBody)
.then().statusCode(200);
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Description>keep</Description>"))
.body(containsString("<ParameterValue>explicit</ParameterValue>"))
.body(containsString("<member>CAPABILITY_NAMED_IAM</member>"))
.body(containsString("<Key>declared</Key>"));
cloudFormation("DeleteStackSet", "StackSetName", name).then().statusCode(200);
}
@Test
void removingDeploymentSettingsRestoresTheirDefaults() {
organizationsFixture.createWithTrustedAccess(MANAGEMENT);
String stack = "removed-deployment-" + UUID.randomUUID().toString().substring(0, 8);
String name = "set-" + stack;
ObjectMapper mapper = new ObjectMapper();
ObjectNode body = simpleStackSetTemplate(name);
ObjectNode properties = (ObjectNode) body.path("Resources").path("Set").path("Properties");
properties.put("PermissionModel", "SERVICE_MANAGED");
properties.set("AutoDeployment", mapper.createObjectNode().put("Enabled", true)
.put("RetainStacksOnAccountRemoval", true));
properties.set("ManagedExecution", mapper.createObjectNode().put("Active", true));
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Enabled>true</Enabled>"))
.body(containsString("<RetainStacksOnAccountRemoval>true</RetainStacksOnAccountRemoval>"))
.body(containsString("<Active>true</Active>"));
properties.remove("AutoDeployment");
properties.remove("ManagedExecution");
properties.remove("Description");
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Enabled>false</Enabled>"))
.body(containsString("<RetainStacksOnAccountRemoval>false</RetainStacksOnAccountRemoval>"))
.body(containsString("<Active>false</Active>"));
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
@Test
void removingRequiredParameterFailsBeforeChangingTheStackSet() {
String stack = "removed-required-" + UUID.randomUUID().toString().substring(0, 8);
String name = "set-" + stack;
ObjectMapper mapper = new ObjectMapper();
ObjectNode body = simpleStackSetTemplate(name);
ObjectNode properties = (ObjectNode) body.path("Resources").path("Set").path("Properties");
properties.put("TemplateBody", "{\"Parameters\":{\"Value\":{\"Type\":\"String\"}},"
+ "\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"}}}");
properties.set("Parameters", mapper.createArrayNode().add(mapper.createObjectNode()
.put("ParameterKey", "Value").put("ParameterValue", "original")));
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
properties.remove("Parameters");
properties.put("Description", "must-not-apply");
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack,
auth(MANAGEMENT, "cloudformation")).status());
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Description>original</Description>"))
.body(containsString("<ParameterValue>original</ParameterValue>"));
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
@Test
void conditionalDeploymentSettingsResolveTheirSelectedObjects() throws Exception {
String root = organizationsFixture.createWithTrustedAccess(MANAGEMENT);
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stack = "conditional-stackset-" + suffix;
String stackSet = "conditional-set-" + suffix;
ObjectMapper mapper = new ObjectMapper();
ObjectNode body = (ObjectNode) mapper.readTree(template(stackSet, "conditional-q-" + suffix));
body.set("Conditions", mapper.createObjectNode().set("Enabled", mapper.createObjectNode()
.set("Fn::Equals", mapper.createArrayNode().add("yes").add("yes"))));
ObjectNode properties = (ObjectNode) body.path("Resources").path("StackSet").path("Properties");
for (String key : new String[]{"AutoDeployment", "ManagedExecution"}) {
properties.set(key, mapper.createObjectNode().set("Fn::If", mapper.createArrayNode()
.add("Enabled").add(properties.get(key))
.add(mapper.createObjectNode().put("AutoDeployment".equals(key) ? "Enabled" : "Active", false))));
}
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString(),
"Parameters.member.1.ParameterKey", "Targets", "Parameters.member.1.ParameterValue", root)
.then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
cloudFormation("DescribeStackSet", "StackSetName", stackSet).then().statusCode(200)
.body(containsString("<Enabled>true</Enabled>"))
.body(containsString("<Active>true</Active>"));
body.set("Conditions", mapper.createObjectNode().set("Enabled", mapper.createObjectNode()
.set("Fn::Equals", mapper.createArrayNode().add("no").add("yes"))));
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString(),
"Parameters.member.1.ParameterKey", "Targets", "Parameters.member.1.ParameterValue", root)
.then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
cloudFormation("DescribeStackSet", "StackSetName", stackSet).then().statusCode(200)
.body(containsString("<Enabled>false</Enabled>"))
.body(containsString("<Active>false</Active>"));
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
@Test
void deletingAStaleResourceLeavesTheRecreatedStackSetAlone() {
String stack = "stale-delete-" + UUID.randomUUID().toString().substring(0, 8);
String name = "set-" + stack;
ObjectNode body = simpleStackSetTemplate(name);
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String original = output(stack, "Id");
String replacement = recreateStackSetOutsideItsParent(name);
assertNotEquals(original, replacement);
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<StackSetId>" + replacement + "</StackSetId>"));
cloudFormation("DeleteStackSet", "StackSetName", name).then().statusCode(200);
}
@Test
void updatingAStaleResourceDoesNotMutateTheRecreatedStackSet() {
String stack = "stale-update-" + UUID.randomUUID().toString().substring(0, 8);
String name = "set-" + stack;
ObjectNode body = simpleStackSetTemplate(name);
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String original = output(stack, "Id");
String replacement = recreateStackSetOutsideItsParent(name);
assertNotEquals(original, replacement);
((ObjectNode) body.path("Resources").path("Set").path("Properties")).put("Description", "requested");
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.StackState state = CfnStackWaits.awaitTerminal(stack, auth(MANAGEMENT, "cloudformation"));
assertNotEquals("UPDATE_COMPLETE", state.status());
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Description>replacement</Description>"))
.body(containsString("<StackSetId>" + replacement + "</StackSetId>"));
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
cloudFormation("DeleteStackSet", "StackSetName", name).then().statusCode(200);
}
private static ObjectNode simpleStackSetTemplate(String name) {
ObjectMapper mapper = new ObjectMapper();
ObjectNode properties = mapper.createObjectNode().put("StackSetName", name)
.put("PermissionModel", "SELF_MANAGED").put("Description", "original")
.put("TemplateBody", "{\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"}}}");
ObjectNode resource = mapper.createObjectNode().put("Type", "AWS::CloudFormation::StackSet");
resource.set("Properties", properties);
ObjectNode body = mapper.createObjectNode();
body.set("Resources", mapper.createObjectNode().set("Set", resource));
body.set("Outputs", mapper.createObjectNode().set("Id",
mapper.createObjectNode().set("Value", mapper.createObjectNode().put("Ref", "Set"))));
return body;
}
private static String recreateStackSetOutsideItsParent(String name) {
cloudFormation("DeleteStackSet", "StackSetName", name).then().statusCode(200);
return cloudFormation("CreateStackSet", "StackSetName", name, "PermissionModel", "SELF_MANAGED",
"Description", "replacement", "TemplateBody",
"{\"Resources\":{\"Queue\":{\"Type\":\"AWS::SQS::Queue\"}}}")
.then().statusCode(200).extract().xmlPath().getString("**.find { it.name() == 'StackSetId' }");
}
@Test
void replacementChangesIdentityWhenNameChanges() {
replacementRename(false);
}
@Test
void replacementHonorsUpdateReplacePolicyRetain() {
replacementRename(true);
}
private void replacementRename(boolean retain) {
String stack = "replace-name-" + UUID.randomUUID().toString().substring(0, 8);
String oldName = "old-" + stack;
String newName = "new-" + stack;
ObjectNode body = simpleStackSetTemplate(oldName);
if (retain) {
((ObjectNode) body.path("Resources").path("Set")).put("UpdateReplacePolicy", "Retain");
}
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String original = output(stack, "Id");
((ObjectNode) body.path("Resources").path("Set").path("Properties")).put("StackSetName", newName);
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
assertNotEquals(original, output(stack, "Id"));
assertThat(output(stack, "Id"), startsWith(newName + ":"));
cloudFormation("DescribeStackSet", "StackSetName", oldName).then().statusCode(retain ? 200 : 404);
cloudFormation("DescribeStackSet", "StackSetName", newName).then().statusCode(200);
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
if (retain) {
cloudFormation("DeleteStackSet", "StackSetName", oldName).then().statusCode(200);
}
}
@Test
void replacementChangesPermissionModelWithANewName() {
organizationsFixture.createWithTrustedAccess(MANAGEMENT);
String stack = "replace-model-" + UUID.randomUUID().toString().substring(0, 8);
ObjectNode body = simpleStackSetTemplate("before-" + stack);
ObjectNode properties = (ObjectNode) body.path("Resources").path("Set").path("Properties");
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String original = output(stack, "Id");
properties.put("PermissionModel", "SERVICE_MANAGED");
properties.put("StackSetName", "after-" + stack);
properties.set("AutoDeployment", new ObjectMapper().createObjectNode().put("Enabled", false));
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String replacement = output(stack, "Id");
assertNotEquals(original, replacement);
cloudFormation("DescribeStackSet", "StackSetName", replacement.substring(0, replacement.indexOf(':')))
.then().statusCode(200).body(containsString("<PermissionModel>SERVICE_MANAGED</PermissionModel>"));
cloudFormation("DescribeStackSet", "StackSetName", original.substring(0, original.indexOf(':')))
.then().statusCode(404);
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
@Test
void replacementRejectsSameCustomNameBeforeMutation() {
String stack = "replace-custom-" + UUID.randomUUID().toString().substring(0, 8);
String name = "set-" + stack;
ObjectNode body = simpleStackSetTemplate(name);
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String original = output(stack, "Id");
ObjectNode properties = (ObjectNode) body.path("Resources").path("Set").path("Properties");
properties.put("PermissionModel", "SERVICE_MANAGED").put("Description", "must-not-apply");
properties.set("AutoDeployment", new ObjectMapper().createObjectNode().put("Enabled", false));
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE", auth(MANAGEMENT, "cloudformation"));
assertEquals(original, output(stack, "Id"));
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Description>original</Description>"))
.body(containsString("<PermissionModel>SELF_MANAGED</PermissionModel>"));
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
@Test
void inPlaceRollbackFailureCanBeRetried() {
String stack = "inplace-retry-" + UUID.randomUUID().toString().substring(0, 8);
String name = "set-" + stack;
ObjectMapper mapper = new ObjectMapper();
ObjectNode body = simpleStackSetTemplate(name);
ObjectNode resources = (ObjectNode) body.path("Resources");
ObjectNode obstacle = mapper.createObjectNode().put("Type", "AWS::SSM::Parameter");
obstacle.set("Properties", mapper.createObjectNode().put("Name", stack)
.put("Type", "String").put("Value", "original"));
resources.set("Obstacle", obstacle);
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
Mockito.doThrow(new IllegalStateException("simulated restore failure")).doCallRealMethod()
.when(stackSets).updateStackSetResource(Mockito.eq(name), Mockito.anyString(), Mockito.anyMap(),
Mockito.anyList(), Mockito.anyMap(), Mockito.eq("original"), Mockito.any(), Mockito.any(),
Mockito.any());
try {
((ObjectNode) resources.path("Set").path("Properties")).put("Description", "attempted");
ObjectNode broken = obstacle.deepCopy();
broken.set("DependsOn", mapper.createArrayNode().add("Set").add("Obstacle"));
resources.set("Broken", broken);
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
assertEquals("UPDATE_ROLLBACK_FAILED", CfnStackWaits.awaitTerminal(stack,
auth(MANAGEMENT, "cloudformation")).status());
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Description>attempted</Description>"));
CfnStackWaits.continueUpdateRollback(stack, auth(MANAGEMENT, "cloudformation"));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack,
auth(MANAGEMENT, "cloudformation")).status());
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Description>original</Description>"));
} finally {
Mockito.reset(stackSets);
}
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
@Test
void inPlaceRollbackRestoresConfigurationAfterALaterResourceFails() {
String stack = "inplace-config-" + UUID.randomUUID().toString().substring(0, 8);
String name = "set-" + stack;
ObjectMapper mapper = new ObjectMapper();
ObjectNode body = simpleStackSetTemplate(name);
ObjectNode resources = (ObjectNode) body.path("Resources");
ObjectNode obstacle = mapper.createObjectNode().put("Type", "AWS::SSM::Parameter");
obstacle.set("Properties", mapper.createObjectNode().put("Name", stack)
.put("Type", "String").put("Value", "original"));
resources.set("Obstacle", obstacle);
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String original = output(stack, "Id");
ObjectNode properties = (ObjectNode) resources.path("Set").path("Properties");
properties.put("Description", "attempted");
properties.set("Tags", mapper.createArrayNode().add(mapper.createObjectNode()
.put("Key", "attempted").put("Value", "value")));
properties.set("Capabilities", mapper.createArrayNode().add("CAPABILITY_NAMED_IAM"));
ObjectNode broken = obstacle.deepCopy();
broken.set("DependsOn", mapper.createArrayNode().add("Set").add("Obstacle"));
resources.set("Broken", broken);
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack,
auth(MANAGEMENT, "cloudformation")).status());
assertEquals(original, output(stack, "Id"));
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Description>original</Description>"))
.body(not(containsString("<Key>attempted</Key>")))
.body(not(containsString("<member>CAPABILITY_NAMED_IAM</member>")));
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
@Test
void inPlaceRollbackRestoresTargetsAndInstancesAfterALaterResourceFails() {
rollbackInstances(false);
}
@Test
void inPlaceRollbackRemovesInstancesCreatedBeforeAnInvalidTargetFails() {
rollbackInstances(true);
}
private static void rollbackInstances(boolean invalidTarget) {
String stack = "inplace-targets-" + UUID.randomUUID().toString().substring(0, 8);
String name = "set-" + stack;
String oldAccount = "515151515151";
String newAccount = "525252525252";
ObjectMapper mapper = new ObjectMapper();
ObjectNode body = simpleStackSetTemplate(name);
ObjectNode resources = (ObjectNode) body.path("Resources");
ObjectNode properties = (ObjectNode) resources.path("Set").path("Properties");
ObjectNode inner = mapper.createObjectNode();
ObjectNode parameter = mapper.createObjectNode().put("Type", "AWS::SSM::Parameter");
ObjectNode innerProperties = mapper.createObjectNode().put("Name", stack)
.put("Type", "String").put("Value", "original");
parameter.set("Properties", innerProperties);
inner.set("Resources", mapper.createObjectNode().set("Parameter", parameter));
properties.put("TemplateBody", inner.toString());
ObjectNode group = mapper.createObjectNode();
group.set("DeploymentTargets", mapper.createObjectNode().set("Accounts", mapper.createArrayNode()
.add(oldAccount)));
group.set("Regions", mapper.createArrayNode().add(REGION));
properties.set("StackInstancesGroup", mapper.createArrayNode().add(group));
if (!invalidTarget) {
resources.set("Obstacle", parameter.deepCopy());
}
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
assertParameter(oldAccount, stack, "original");
innerProperties.put("Value", "attempted");
properties.put("TemplateBody", inner.toString()).put("Description", "attempted");
((ObjectNode) group.path("DeploymentTargets")).set("Accounts", mapper.createArrayNode().add(newAccount));
if (invalidTarget) {
ObjectNode badGroup = group.deepCopy();
((ObjectNode) badGroup.path("DeploymentTargets")).set("Accounts", mapper.createArrayNode()
.add("invalid-account"));
properties.set("StackInstancesGroup", mapper.createArrayNode().add(group).add(badGroup));
} else {
ObjectNode broken = parameter.deepCopy();
((ObjectNode) broken.path("Properties")).put("Value", "original");
broken.set("DependsOn", mapper.createArrayNode().add("Set").add("Obstacle"));
resources.set("Broken", broken);
}
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stack,
auth(MANAGEMENT, "cloudformation")).status());
assertParameter(oldAccount, stack, "original");
given().header("Authorization", auth(newAccount, "ssm")).header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType("application/x-amz-json-1.1").body("{\"Name\":\"" + stack + "\"}")
.post("/").then().statusCode(400).body(containsString("ParameterNotFound"));
cloudFormation("ListStackInstances", "StackSetName", name).then().statusCode(200)
.body(containsString("<Account>" + oldAccount + "</Account>"))
.body(not(containsString("<Account>" + newAccount + "</Account>")));
cloudFormation("DescribeStackSet", "StackSetName", name).then().statusCode(200)
.body(containsString("<Description>original</Description>"));
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
private static void assertParameter(String account, String name, String value) {
given().header("Authorization", auth(account, "ssm")).header("X-Amz-Target", "AmazonSSM.GetParameter")
.contentType("application/x-amz-json-1.1").body("{\"Name\":\"" + name + "\"}")
.post("/").then().statusCode(200).body("Parameter.Value", equalTo(value));
}
@Test
void replacementRollsBackWhenALaterResourceFails() {
String stack = "replace-rollback-" + UUID.randomUUID().toString().substring(0, 8);
String oldName = "old-" + stack;
String newName = "new-" + stack;
ObjectMapper mapper = new ObjectMapper();
ObjectNode body = simpleStackSetTemplate(oldName);
ObjectNode resources = (ObjectNode) body.path("Resources");
ObjectNode parameter = mapper.createObjectNode().put("Type", "AWS::SSM::Parameter");
parameter.set("Properties", mapper.createObjectNode().put("Name", stack)
.put("Type", "String").put("Value", "original"));
resources.set("Obstacle", parameter);
cloudFormation("CreateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "CREATE_COMPLETE", auth(MANAGEMENT, "cloudformation"));
String original = output(stack, "Id");
((ObjectNode) resources.path("Set").path("Properties")).put("StackSetName", newName);
ObjectNode broken = parameter.deepCopy();
broken.set("DependsOn", mapper.createArrayNode().add("Set").add("Obstacle"));
resources.set("Broken", broken);
cloudFormation("UpdateStack", "StackName", stack, "TemplateBody", body.toString()).then().statusCode(200);
CfnStackWaits.awaitStatus(stack, "UPDATE_ROLLBACK_COMPLETE", auth(MANAGEMENT, "cloudformation"));
assertEquals(original, output(stack, "Id"));
cloudFormation("DescribeStackSet", "StackSetName", oldName).then().statusCode(200);
cloudFormation("DescribeStackSet", "StackSetName", newName).then().statusCode(404);
CfnStackWaits.deleteStack(stack, auth(MANAGEMENT, "cloudformation"));
}
@AfterEach
void deleteOrganization() {
organizationsFixture.cleanup();
}
private static String template(String stackSet, String queue) throws JsonProcessingException {
String instanceTemplate = "{\"Parameters\":{\"QueueName\":{\"Type\":\"String\"}},"
+ "\"Resources\":{\"Q\":{\"Type\":\"AWS::SQS::Queue\",\"Properties\":{\"QueueName\":{\"Ref\":\"QueueName\"}}}}}";
return """
{
"Parameters": {
"Targets": { "Type": "String" },
"Regions": { "Type": "CommaDelimitedList", "Default": "us-east-1" }
},
"Resources": {
"StackSet": {
"Type": "AWS::CloudFormation::StackSet",
"Properties": {
"StackSetName": "%s",
"PermissionModel": "SERVICE_MANAGED",
"AutoDeployment": { "Enabled": true, "RetainStacksOnAccountRemoval": false },
"ManagedExecution": { "Active": true },
"Parameters": [ { "ParameterKey": "QueueName", "ParameterValue": "%s" } ],
"StackInstancesGroup": [ {
"DeploymentTargets": { "OrganizationalUnitIds": { "Fn::Split": [" ", { "Ref": "Targets" }] } },
"Regions": { "Ref": "Regions" }
} ],
"TemplateBody": %s
}
}
},
"Outputs": {
"StackSetRef": { "Value": { "Ref": "StackSet" } },
"StackSetId": { "Value": { "Fn::GetAtt": ["StackSet", "StackSetId"] } }
}
}
""".formatted(stackSet, queue, new ObjectMapper().writeValueAsString(instanceTemplate));
}
private static String output(String stack, String key) {
return cloudFormation("DescribeStacks", "StackName", stack).xmlPath().getString(
"DescribeStacksResponse.DescribeStacksResult.Stacks.member.Outputs.member"
+ ".find { it.OutputKey == '" + key + "' }.OutputValue");
}
private static void assertQueue(String account, String queue, boolean present) {
assertQueue(account, queue, REGION, present);
}
private static void assertQueue(String account, String queue, String region, boolean present) {
given()
.header("Authorization", auth(account, region, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueUrl")
.formParam("QueueName", queue)
.post("/").then().statusCode(present ? 200 : 400);
}
private static Response cloudFormation(String action, String... formParams) {
RequestSpecification request = CfnRequests.cfn(action, null)
.header("Authorization", auth(MANAGEMENT, "cloudformation"));
for (int i = 0; i < formParams.length; i += 2) {
request = request.formParam(formParams[i], formParams[i + 1]);
}
return request.when().post("/");
}
private Response organizations(String action, String body) {
return organizationsFixture.request(MANAGEMENT, action, body).post("/");
}
}
@@ -1,6 +1,7 @@
package io.floci.aws.services.cloudformation;
import com.fasterxml.jackson.core.type.TypeReference;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.storage.AccountAwareStorageBackend;
import io.floci.aws.core.storage.InMemoryStorage;
import io.floci.aws.core.storage.StorageBackend;
@@ -17,6 +18,7 @@ import java.util.Map;
import java.util.concurrent.CompletableFuture;
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.anyString;
import static org.mockito.Mockito.mock;
@@ -96,6 +98,32 @@ class StackSetServiceDeleteFailureTest {
.deleteStack(anyString(), anyString(), anyString());
}
@Test
void resourceDeleteFailureRetainsFailedInstanceAndStackSet() {
when(cfnService.deleteStack(anyString(), anyString(), anyString()))
.thenThrow(new IllegalStateException("Termination protection is enabled"));
assertThrows(AwsException.class, () -> service.deleteStackSetWithInstances(SET));
List<StackInstance> remaining = service.listStackInstances(SET, null, null);
assertEquals(1, remaining.size());
assertEquals("INOPERABLE", remaining.get(0).getStatus());
assertEquals("FAILED", remaining.get(0).getDetailedStatus());
assertEquals(SET, service.describeStackSet(SET).getStackSetName());
}
@Test
void resourceDeleteRemovesInstancesAndToleratesRepeatedDelete() {
when(cfnService.deleteStack(anyString(), anyString(), anyString()))
.thenReturn(CompletableFuture.completedFuture(null));
service.deleteStackSetWithInstances(SET);
service.deleteStackSetWithInstances(SET);
AwsException missing = assertThrows(AwsException.class, () -> service.describeStackSet(SET));
assertEquals("StackSetNotFoundException", missing.getErrorCode());
}
private static final class InMemoryStorageFactory extends StorageFactory {
private InMemoryStorageFactory() {
super(null, null);
@@ -0,0 +1,89 @@
package io.floci.aws.testing;
import io.restassured.path.json.JsonPath;
import io.restassured.specification.RequestSpecification;
import java.util.LinkedHashSet;
import java.util.Set;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
public final class OrganizationsFixture {
private final Set<String> owners = new LinkedHashSet<>();
public RequestSpecification request(String owner, String action, String body) {
if ("CreateOrganization".equals(action)) {
owners.add(owner);
}
return OrganizationsRequests.request(owner, action, body);
}
public String createWithTrustedAccess(String owner) {
request(owner, "CreateOrganization", "{\"FeatureSet\":\"ALL\"}")
.post("/").then().statusCode(200);
given().header("Authorization", EnforcementFixtures.auth(owner, "cloudformation"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "ActivateOrganizationsAccess")
.post("/").then().statusCode(200);
return request(owner, "ListRoots", "{}").post("/").then().statusCode(200)
.extract().jsonPath().getString("Roots[0].Id");
}
public String createOu(String owner, String parentId, String name) {
return request(owner, "CreateOrganizationalUnit",
"{\"ParentId\":\"" + parentId + "\",\"Name\":\"" + name + "\"}")
.post("/").then().statusCode(200)
.extract().jsonPath().getString("OrganizationalUnit.Id");
}
public String createAccount(String owner, String email, String name) {
return request(owner, "CreateAccount", "{\"Email\":\"" + email + "\",\"AccountName\":\"" + name + "\"}")
.post("/").then().statusCode(200)
.body("CreateAccountStatus.State", equalTo("SUCCEEDED"))
.extract().jsonPath().getString("CreateAccountStatus.AccountId");
}
public String createAccount(String owner, String email, String name, String parentId, String rootId) {
String account = createAccount(owner, email, name);
moveAccount(owner, account, rootId, parentId);
return account;
}
public void moveAccount(String owner, String account, String source, String destination) {
request(owner, "MoveAccount", "{\"AccountId\":\"" + account + "\",\"SourceParentId\":\"" + source
+ "\",\"DestinationParentId\":\"" + destination + "\"}")
.post("/").then().statusCode(200);
}
public void cleanup() {
for (String owner : owners) {
if (request(owner, "DescribeOrganization", "{}").post("/").statusCode() != 200) {
continue;
}
JsonPath accounts = request(owner, "ListAccounts", "{}").post("/").jsonPath();
for (String account : accounts.getList("Accounts.Id", String.class)) {
if (!owner.equals(account)) {
request(owner, "RemoveAccountFromOrganization", "{\"AccountId\":\"" + account + "\"}")
.post("/").then().statusCode(200);
}
}
JsonPath roots = request(owner, "ListRoots", "{}").post("/").jsonPath();
for (String root : roots.getList("Roots.Id", String.class)) {
deleteUnitsUnder(owner, root);
}
request(owner, "DeleteOrganization", "{}").post("/").then().statusCode(200);
}
owners.clear();
}
private void deleteUnitsUnder(String owner, String parent) {
JsonPath units = request(owner, "ListOrganizationalUnitsForParent", "{\"ParentId\":\"" + parent + "\"}")
.post("/").jsonPath();
for (String unit : units.getList("OrganizationalUnits.Id", String.class)) {
deleteUnitsUnder(owner, unit);
request(owner, "DeleteOrganizationalUnit", "{\"OrganizationalUnitId\":\"" + unit + "\"}")
.post("/").then().statusCode(200);
}
}
}
@@ -45,6 +45,7 @@ AWS::BedrockAgentCore::Runtime AgentRuntimeArn,AgentRuntimeId,AgentRuntimeVersio
AWS::BedrockAgentCore::RuntimeEndpoint AgentRuntimeArn,AgentRuntimeEndpointArn,CreatedAt,FailureReason,Id,LastUpdatedAt,LiveVersion,Status,TargetVersion AgentRuntimeId,AgentRuntimeVersion,Description,Name,Tags
AWS::CertificateManager::Certificate CertificateArn CertificateAuthorityArn,CertificateExport,CertificateTransparencyLoggingPreference,DomainName,DomainValidationOptions,KeyAlgorithm,SubjectAlternativeNames,Tags,ValidationMethod
AWS::CloudFormation::CustomResource Id ServiceTimeout,ServiceToken
AWS::CloudFormation::StackSet StackSetId AdministrationRoleARN,AutoDeployment,CallAs,Capabilities,Description,ExecutionRoleName,ManagedExecution,OperationPreferences,Parameters,PermissionModel,StackInstancesGroup,StackSetName,Tags,TemplateBody,TemplateURL
AWS::CloudFront::CachePolicy Id,LastModifiedTime CachePolicyConfig
AWS::CloudFront::Distribution DomainName,Id DistributionConfig,Tags
AWS::CloudFront::Function FunctionARN,Stage AutoPublish,FunctionCode,FunctionConfig,FunctionMetadata,Name,Tags
@@ -140,7 +141,7 @@ AWS::Lambda::EventInvokeConfig DestinationConfig,FunctionName,MaximumEventAgeIn
AWS::Lambda::EventSourceMapping EventSourceMappingArn,Id AmazonManagedKafkaEventSourceConfig,BatchSize,BisectBatchOnFunctionError,DestinationConfig,DocumentDBEventSourceConfig,Enabled,EventSourceArn,FilterCriteria,FunctionName,FunctionResponseTypes,KmsKeyArn,LoggingConfig,MaximumBatchingWindowInSeconds,MaximumRecordAgeInSeconds,MaximumRetryAttempts,MetricsConfig,ParallelizationFactor,ProvisionedPollerConfig,Queues,ScalingConfig,SelfManagedEventSource,SelfManagedKafkaEventSourceConfig,SourceAccessConfigurations,StartingPosition,StartingPositionTimestamp,Tags,Topics,TumblingWindowInSeconds
AWS::Lambda::Function Arn,SnapStartResponse Architectures,CapacityProviderConfig,Code,CodeSigningConfigArn,DeadLetterConfig,Description,DurableConfig,Environment,EphemeralStorage,FileSystemConfigs,FunctionName,FunctionScalingConfig,Handler,ImageConfig,KmsKeyArn,Layers,LoggingConfig,MemorySize,PackageType,PublishToLatestPublished,RecursiveLoop,ReservedConcurrentExecutions,Role,Runtime,RuntimeManagementConfig,SnapStart,Tags,TenancyConfig,Timeout,TracingConfig,VpcConfig
AWS::Lambda::LayerVersion LayerVersionArn CompatibleArchitectures,CompatibleRuntimes,Content,Description,LayerName,LicenseInfo
AWS::Lambda::MicrovmImage CreatedAt,ImageArn,LatestActiveImageVersion,LatestFailedImageVersion,State,UpdatedAt AdditionalOsCapabilities,BaseImageArn,BaseImageVersion,BuildRoleArn,CodeArtifact,CpuConfigurations,Description,EgressNetworkConnectors,EnvironmentVariables,Hooks,Logging,Name,Resources,Tags
AWS::Lambda::MicrovmImage CreatedAt,ImageArn,LatestActiveImageVersion,LatestFailedImageVersion,State,UpdatedAt AdditionalOsCapabilities,BaseImageArn,BaseImageVersion,BuildRoleArn,CodeArtifact,CpuConfigurations,Description,EgressNetworkConnectors,EnvironmentVariables,Hooks,KmsKeyIdentifier,Logging,Name,Resources,Tags
AWS::Lambda::NetworkConnector Arn,LatestVersion,LatestVersionArn,State Configuration,Name,OperatorRole,Tags
AWS::Lambda::Permission Id Action,EventSourceToken,FunctionName,FunctionUrlAuthType,InvokedViaFunctionUrl,Principal,PrincipalOrgID,SourceAccount,SourceArn
AWS::Lambda::Url FunctionArn,FunctionUrl AuthType,Cors,InvokeMode,Qualifier,TargetFunctionArn
1 AWS::ApiGateway::Account Id CloudWatchRoleArn
45 AWS::BedrockAgentCore::RuntimeEndpoint AgentRuntimeArn,AgentRuntimeEndpointArn,CreatedAt,FailureReason,Id,LastUpdatedAt,LiveVersion,Status,TargetVersion AgentRuntimeId,AgentRuntimeVersion,Description,Name,Tags
46 AWS::CertificateManager::Certificate CertificateArn CertificateAuthorityArn,CertificateExport,CertificateTransparencyLoggingPreference,DomainName,DomainValidationOptions,KeyAlgorithm,SubjectAlternativeNames,Tags,ValidationMethod
47 AWS::CloudFormation::CustomResource Id ServiceTimeout,ServiceToken
48 AWS::CloudFormation::StackSet StackSetId AdministrationRoleARN,AutoDeployment,CallAs,Capabilities,Description,ExecutionRoleName,ManagedExecution,OperationPreferences,Parameters,PermissionModel,StackInstancesGroup,StackSetName,Tags,TemplateBody,TemplateURL
49 AWS::CloudFront::CachePolicy Id,LastModifiedTime CachePolicyConfig
50 AWS::CloudFront::Distribution DomainName,Id DistributionConfig,Tags
51 AWS::CloudFront::Function FunctionARN,Stage AutoPublish,FunctionCode,FunctionConfig,FunctionMetadata,Name,Tags
141 AWS::Lambda::EventSourceMapping EventSourceMappingArn,Id AmazonManagedKafkaEventSourceConfig,BatchSize,BisectBatchOnFunctionError,DestinationConfig,DocumentDBEventSourceConfig,Enabled,EventSourceArn,FilterCriteria,FunctionName,FunctionResponseTypes,KmsKeyArn,LoggingConfig,MaximumBatchingWindowInSeconds,MaximumRecordAgeInSeconds,MaximumRetryAttempts,MetricsConfig,ParallelizationFactor,ProvisionedPollerConfig,Queues,ScalingConfig,SelfManagedEventSource,SelfManagedKafkaEventSourceConfig,SourceAccessConfigurations,StartingPosition,StartingPositionTimestamp,Tags,Topics,TumblingWindowInSeconds
142 AWS::Lambda::Function Arn,SnapStartResponse Architectures,CapacityProviderConfig,Code,CodeSigningConfigArn,DeadLetterConfig,Description,DurableConfig,Environment,EphemeralStorage,FileSystemConfigs,FunctionName,FunctionScalingConfig,Handler,ImageConfig,KmsKeyArn,Layers,LoggingConfig,MemorySize,PackageType,PublishToLatestPublished,RecursiveLoop,ReservedConcurrentExecutions,Role,Runtime,RuntimeManagementConfig,SnapStart,Tags,TenancyConfig,Timeout,TracingConfig,VpcConfig
143 AWS::Lambda::LayerVersion LayerVersionArn CompatibleArchitectures,CompatibleRuntimes,Content,Description,LayerName,LicenseInfo
144 AWS::Lambda::MicrovmImage CreatedAt,ImageArn,LatestActiveImageVersion,LatestFailedImageVersion,State,UpdatedAt AdditionalOsCapabilities,BaseImageArn,BaseImageVersion,BuildRoleArn,CodeArtifact,CpuConfigurations,Description,EgressNetworkConnectors,EnvironmentVariables,Hooks,Logging,Name,Resources,Tags AdditionalOsCapabilities,BaseImageArn,BaseImageVersion,BuildRoleArn,CodeArtifact,CpuConfigurations,Description,EgressNetworkConnectors,EnvironmentVariables,Hooks,KmsKeyIdentifier,Logging,Name,Resources,Tags
145 AWS::Lambda::NetworkConnector Arn,LatestVersion,LatestVersionArn,State Configuration,Name,OperatorRole,Tags
146 AWS::Lambda::Permission Id Action,EventSourceToken,FunctionName,FunctionUrlAuthType,InvokedViaFunctionUrl,Principal,PrincipalOrgID,SourceAccount,SourceArn
147 AWS::Lambda::Url FunctionArn,FunctionUrl AuthType,Cors,InvokeMode,Qualifier,TargetFunctionArn
@@ -46,6 +46,7 @@ AWS::BedrockAgentCore::RuntimeEndpoint BedrockAgentCoreCfnProvisioner
AWS::CDK::Metadata CdkMetadataCfnProvisioner
AWS::CertificateManager::Certificate AcmCfnProvisioner
AWS::CloudFormation::CustomResource CustomResourceCfnProvisioner
AWS::CloudFormation::StackSet StackSetCfnProvisioner
AWS::CloudFront::CachePolicy CloudFrontCfnProvisioner
AWS::CloudFront::Distribution CloudFrontCfnProvisioner
AWS::CloudFront::Function CloudFrontCfnProvisioner
1 AWS::ApiGateway::Account ApiGatewayAccountCfnProvisioner
46 AWS::CDK::Metadata CdkMetadataCfnProvisioner
47 AWS::CertificateManager::Certificate AcmCfnProvisioner
48 AWS::CloudFormation::CustomResource CustomResourceCfnProvisioner
49 AWS::CloudFormation::StackSet StackSetCfnProvisioner
50 AWS::CloudFront::CachePolicy CloudFrontCfnProvisioner
51 AWS::CloudFront::Distribution CloudFrontCfnProvisioner
52 AWS::CloudFront::Function CloudFrontCfnProvisioner
@@ -130,6 +130,10 @@ AWS::BedrockAgentCore::RuntimeEndpoint Tags accepted and not stored, a warning i
AWS::CertificateManager::Certificate CertificateAuthorityArn accepted and ignored
AWS::CertificateManager::Certificate DomainValidationOptions accepted and ignored, as the AcmCfnProvisioner javadoc records
AWS::CloudFormation::CustomResource ServiceTimeout accepted and ignored
AWS::CloudFormation::StackSet AdministrationRoleARN accepted and ignored; local StackSets deploy without assuming an administration role
AWS::CloudFormation::StackSet CallAs accepted and ignored; local StackSets do not model delegated administrator authorization
AWS::CloudFormation::StackSet ExecutionRoleName accepted and ignored; local StackSets deploy without assuming an execution role
AWS::CloudFormation::StackSet OperationPreferences accepted and ignored; explicit StackSet deployments execute locally without scheduling preferences
AWS::CloudFront::Distribution Tags accepted and ignored
AWS::CloudFront::Function FunctionMetadata accepted and ignored
AWS::CloudTrail::Trail AggregationConfigurations accepted and ignored
@@ -416,6 +420,7 @@ AWS::Lambda::MicrovmImage CpuConfigurations accepted and ignored
AWS::Lambda::MicrovmImage EgressNetworkConnectors accepted and ignored
AWS::Lambda::MicrovmImage EnvironmentVariables accepted and ignored
AWS::Lambda::MicrovmImage Hooks accepted and ignored
AWS::Lambda::MicrovmImage KmsKeyIdentifier accepted and ignored; local MicroVM image builds do not model KMS encryption
AWS::Lambda::MicrovmImage Logging accepted and ignored
AWS::Lambda::MicrovmImage Resources accepted and ignored
AWS::Lambda::MicrovmImage Tags accepted and ignored
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
130 AWS::CertificateManager::Certificate CertificateAuthorityArn accepted and ignored
131 AWS::CertificateManager::Certificate DomainValidationOptions accepted and ignored, as the AcmCfnProvisioner javadoc records
132 AWS::CloudFormation::CustomResource ServiceTimeout accepted and ignored
133 AWS::CloudFormation::StackSet AdministrationRoleARN accepted and ignored; local StackSets deploy without assuming an administration role
134 AWS::CloudFormation::StackSet CallAs accepted and ignored; local StackSets do not model delegated administrator authorization
135 AWS::CloudFormation::StackSet ExecutionRoleName accepted and ignored; local StackSets deploy without assuming an execution role
136 AWS::CloudFormation::StackSet OperationPreferences accepted and ignored; explicit StackSet deployments execute locally without scheduling preferences
137 AWS::CloudFront::Distribution Tags accepted and ignored
138 AWS::CloudFront::Function FunctionMetadata accepted and ignored
139 AWS::CloudTrail::Trail AggregationConfigurations accepted and ignored
420 AWS::Lambda::MicrovmImage EgressNetworkConnectors accepted and ignored
421 AWS::Lambda::MicrovmImage EnvironmentVariables accepted and ignored
422 AWS::Lambda::MicrovmImage Hooks accepted and ignored
423 AWS::Lambda::MicrovmImage KmsKeyIdentifier accepted and ignored; local MicroVM image builds do not model KMS encryption
424 AWS::Lambda::MicrovmImage Logging accepted and ignored
425 AWS::Lambda::MicrovmImage Resources accepted and ignored
426 AWS::Lambda::MicrovmImage Tags accepted and ignored