fix(cloudformation): deploy a service-managed stack set to accounts that join or leave its targets (#7243)

This commit is contained in:
galsuchetzky-act authored and GitHub committed 2026-11-08 18:01:22 -04:00
1 parent e0692092b5
commit 01c84245a7
6 files changed
+873 -28

No files matched your search

+2
View File
@@ -66,6 +66,8 @@ changing credentials already issued.
StackSets support both `SELF_MANAGED` and the Cloud Launchpad `SERVICE_MANAGED` workflow. `ActivateOrganizationsAccess` requires an Organizations management account with all features enabled and enables trusted access for `stacksets.cloudformation.amazonaws.com`. Service-managed organizational-unit deployment targets are resolved from the caller's actual Organizations state rather than converted into synthetic account IDs. Targeting an OU includes eligible accounts directly in that OU and in all descendant OUs, while excluding the organization management account, matching AWS StackSets targeting semantics. `DescribeStackSet` returns the stack set's `Tags` and, for a service-managed stack set, the root and OU ids its instances were created for as `OrganizationalUnitIds`.
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.
`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.
@@ -16,16 +16,19 @@ 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 io.floci.aws.services.iam.PassedRoleLookup;
import io.floci.aws.services.organizations.AccountPlacementListener;
import io.floci.aws.services.organizations.OrganizationsService;
import io.floci.aws.services.organizations.model.Organization;
import io.floci.aws.services.organizations.model.OrganizationAccount;
import io.floci.aws.services.organizations.model.OrganizationalUnit;
import jakarta.annotation.PreDestroy;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
@@ -34,7 +37,11 @@ import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.function.Supplier;
import java.util.regex.Pattern;
/**
@@ -45,9 +52,13 @@ import java.util.regex.Pattern;
* single-stack engine ({@link CloudFormationService}) once per target {@code (account, region)},
* provisioning the resources into each target account's namespace. The StackSet, instance and
* operation records themselves live in the administration (caller) account's namespace.
*
* <p>A service-managed stack set with automatic deployment follows the accounts of the organization: an
* account created in, invited into or moved under one of its targets gets an instance in every Region
* that target was given, and one no target covers any more loses its instances.
*/
@ApplicationScoped
public class StackSetService implements PassedRoleLookup {
public class StackSetService implements PassedRoleLookup, AccountPlacementListener {
private static final Logger LOG = Logger.getLogger(StackSetService.class);
private static final String STACKSETS_SERVICE_PRINCIPAL = ServicePrincipals.of("stacksets.cloudformation");
@@ -68,6 +79,17 @@ public class StackSetService implements PassedRoleLookup {
private final StorageBackend<String, StackSetAutoDeploymentTarget> autoDeploymentTargets;
private final OrganizationsService organizationsService;
private final RegionResolver regionResolver;
private final ExecutorService accountPlacementExecutor = newAccountPlacementExecutor();
private static ExecutorService newAccountPlacementExecutor() {
ThreadFactory factory = Thread.ofPlatform().daemon(true).inheritInheritableThreadLocals(false)
.name("floci-stack-set-auto-deployment-", 0).factory();
return Executors.newSingleThreadExecutor(task -> {
Thread worker = factory.newThread(task);
worker.setContextClassLoader(Thread.currentThread().getContextClassLoader());
return worker;
});
}
StackSetService(CloudFormationService cfnService, StorageFactory storageFactory) {
this(cfnService, storageFactory, null, new RegionResolver("us-east-1", "000000000000")); // partition-literal: test-shaped constructor default
@@ -389,6 +411,135 @@ public class StackSetService implements PassedRoleLookup {
.toList();
}
@Override
public void accountPlacementChanged(String managementAccountId, String accountId) {
String region = regionResolver.getRegion();
accountPlacementExecutor.execute(() -> RequestScopes.runAs(managementAccountId, region,
() -> reconcileAccountPlacement(managementAccountId, accountId)));
}
private synchronized void reconcileAccountPlacement(String managementAccountId, String accountId) {
Set<String> ancestors = ancestorsOf(managementAccountId, accountId);
for (StackSet stackSet : stackSets.scan(key -> true)) {
if ("SERVICE_MANAGED".equals(stackSet.getPermissionModel()) && stackSet.isAutoDeploymentEnabled()) {
try {
autoDeploy(stackSet, accountId, ancestors);
} catch (RuntimeException e) {
LOG.warnv(e, "Automatic deployment failed for StackSet {0}, account {1}",
stackSet.getStackSetName(), accountId);
}
}
}
}
@PreDestroy
void stopAccountPlacementExecutor() {
accountPlacementExecutor.shutdownNow();
}
/** The root and OUs above an active member account, empty for the management account or one outside the organization. */
private Set<String> ancestorsOf(String managementAccountId, String accountId) {
if (managementAccountId.equals(accountId)) {
return Set.of();
}
try {
if (!"ACTIVE".equals(organizationsService.describeAccount(managementAccountId, accountId).getStatus())) {
return Set.of();
}
Set<String> ancestors = new LinkedHashSet<>(Arrays.asList(
organizationsService.organizationPath(managementAccountId, accountId).split("/")));
ancestors.remove(accountId);
return ancestors;
} catch (AwsException e) {
if ("AccountNotFoundException".equals(e.getErrorCode())
|| "AWSOrganizationsNotInUseException".equals(e.getErrorCode())) {
return Set.of();
}
throw e;
}
}
private void autoDeploy(StackSet stackSet, String accountId, Set<String> ancestors) {
String name = stackSet.getStackSetName();
Map<String, Set<String>> targetsByRegion = new LinkedHashMap<>();
for (StackSetAutoDeploymentTarget target : listStackSetAutoDeploymentTargets(name)) {
if (ancestors.contains(target.getOrganizationalUnitId())) {
for (String region : target.getRegions()) {
targetsByRegion.computeIfAbsent(region, ignored -> new LinkedHashSet<>())
.add(target.getOrganizationalUnitId());
}
}
}
List<StackInstance> removed = listStackInstances(name, accountId, null).stream()
.filter(instance -> !targetsByRegion.containsKey(instance.getRegion()))
.toList();
if (!removed.isEmpty()) {
runAutomaticOperation(name, "DELETE", () -> {
for (StackInstance instance : removed) {
removeInstance(stackSet, instance, stackSet.isRetainStacksOnAccountRemoval());
}
return removed;
});
}
Map<String, Set<String>> regionsToCreate = new LinkedHashMap<>();
targetsByRegion.forEach((region, targets) -> {
String key = instanceKey(name, accountId, region);
StackInstance existing = instances.get(key).orElse(null);
if (existing != null && !"OUTDATED".equals(existing.getStatus())) {
applyDeploymentTargets(existing, targets);
instances.put(key, existing);
} else {
regionsToCreate.put(region, targets);
}
});
if (!regionsToCreate.isEmpty()) {
runAutomaticOperation(name, "CREATE", () -> {
List<StackInstance> created = new ArrayList<>();
regionsToCreate.forEach((region, targets) -> {
StackInstance instance = deployInstance(stackSet, accountId, region, INSTANCE_CHANGE_SET, "CREATE");
applyDeploymentTargets(instance, targets);
instances.put(instanceKey(name, accountId, region), instance);
created.add(instance);
});
return created;
});
}
}
private void runAutomaticOperation(String name, String action, Supplier<List<StackInstance>> deployment) {
String operationId = reserveOperation(name, action, null).getOperationId();
try {
completeOperation(name, operationId, deriveOperationStatus(deployment.get()));
} catch (RuntimeException e) {
completeOperation(name, operationId, "FAILED");
throw e;
}
}
private void removeInstance(StackSet stackSet, StackInstance instance, boolean retainStacks) {
String key = instanceKey(stackSet.getStackSetName(), instance.getAccount(), instance.getRegion());
try {
if (!retainStacks
&& !await(cfnService.deleteStack(instance.getStackName(), instance.getRegion(), instance.getAccount()))) {
instance.setStatus("INOPERABLE");
instance.setDetailedStatus("FAILED");
instance.setStatusReason("Stack instance deletion failed");
instances.put(key, instance);
return;
}
} catch (RuntimeException e) {
instance.setStatus("INOPERABLE");
instance.setDetailedStatus("FAILED");
instance.setStatusReason(e.getMessage());
instances.put(key, instance);
LOG.warnv(e, "Deletion failed for StackSet {0}, account {1}, Region {2}",
stackSet.getStackSetName(), instance.getAccount(), instance.getRegion());
return;
}
instance.setDetailedStatus("SUCCEEDED");
instances.delete(key);
}
public List<StackInstance> listStackInstances(String name, String accountFilter, String regionFilter) {
getStackSetOrThrow(name);
String prefix = name + ":";
@@ -472,19 +623,7 @@ public class StackSetService implements PassedRoleLookup {
continue;
}
}
if (!retainStacks && !await(cfnService.deleteStack(inst.getStackName(), region, account))) {
// The underlying stack delete failed. Match AWS: retain the instance record
// (now INOPERABLE) and report the operation as FAILED, rather than silently
// dropping the instance and claiming success.
inst.setStatus("INOPERABLE");
inst.setDetailedStatus("FAILED");
inst.setStatusReason("Stack instance deletion failed");
instances.put(key, inst);
results.add(inst);
continue;
}
inst.setDetailedStatus("SUCCEEDED");
instances.delete(key);
removeInstance(stackSet, inst, retainStacks);
results.add(inst);
}
String operationStatus = deriveOperationStatus(results);
@@ -554,8 +693,12 @@ public class StackSetService implements PassedRoleLookup {
for (String ou : organizationalUnits) {
collectOrganizationTargets(caller, organization, ou, ou, targets);
if (persistTargets) {
autoDeploymentTargets.put(stackSetName + "::" + ou,
new StackSetAutoDeploymentTarget(stackSetName, ou, regions));
String key = stackSetName + "::" + ou;
LinkedHashSet<String> targetRegions = new LinkedHashSet<>(autoDeploymentTargets.get(key)
.map(StackSetAutoDeploymentTarget::getRegions).orElse(List.of()));
targetRegions.addAll(regions);
autoDeploymentTargets.put(key,
new StackSetAutoDeploymentTarget(stackSetName, ou, List.copyOf(targetRegions)));
}
}
return new ArrayList<>(targets.values());
@@ -664,7 +807,7 @@ public class StackSetService implements PassedRoleLookup {
*/
private StackInstance deployInstance(StackSet ss, String account, String region,
String changeSetName, String changeSetType) {
String stackName = instanceStackName(ss.getStackSetName(), account);
String stackName = resolveInstanceStackName(ss.getStackSetName(), account, region);
// Preflight the change set in the target account so AWS::AccountId-based conditions are
// evaluated against the same account the instance executes in (createChangeSet otherwise runs
// in the administrator request scope).
@@ -759,6 +902,20 @@ public class StackSetService implements PassedRoleLookup {
return "StackSet-" + stackSetName + "-" + account;
}
private String resolveInstanceStackName(String stackSetName, String account, String region) {
StackInstance existing = instances.get(instanceKey(stackSetName, account, region)).orElse(null);
if (existing != null && existing.getStackName() != null) {
return existing.getStackName();
}
String name = instanceStackName(stackSetName, account);
String status = cfnService.stackStatus(name, region, account);
if (status != null && !"DELETE_COMPLETE".equals(status)) {
String suffix = "-" + UUID.randomUUID();
return name.substring(0, Math.min(name.length(), 128 - suffix.length())) + suffix;
}
return name;
}
private static String instanceKey(String stackSetName, String account, String region) {
return stackSetName + ":" + account + ":" + region;
}
@@ -0,0 +1,20 @@
package io.floci.aws.services.organizations;
/**
* Told when a member account takes a new place in an organization or leaves it. CloudFormation StackSets
* follows the account there: a service-managed stack set with automatic deployment deploys to an account
* added to a target organizational unit and removes its stack instances when the account leaves every
* target (CloudFormation User Guide, "Enable or disable automatic deployments for StackSets in AWS
* Organizations").
*
* <p>Organizations says where the account is now; the listener owns what follows from it, the way
* {@link AccountAccessRoleProvisioner} keeps Organizations apart from IAM.
*/
public interface AccountPlacementListener {
/**
* {@code accountId} was created in, invited into, moved within or removed from the organization that
* {@code managementAccountId} manages. Called once the change is stored, in the request that made it.
*/
void accountPlacementChanged(String managementAccountId, String accountId);
}
@@ -23,6 +23,7 @@ import io.floci.aws.services.organizations.model.OrganizationalUnit;
import io.floci.aws.services.organizations.model.PolicyTypeSummary;
import io.floci.aws.services.organizations.model.Root;
import jakarta.enterprise.context.ApplicationScoped;
import jakarta.enterprise.inject.Instance;
import jakarta.inject.Inject;
import org.jboss.logging.Logger;
@@ -172,11 +173,13 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
private final boolean scpEnforcementEnabled;
private final String managementAccountEmail;
private final AccountAccessRoleProvisioner accountAccessRoleProvisioner;
private final Iterable<AccountPlacementListener> placementListeners;
@Inject
public OrganizationsService(StorageFactory storageFactory, ObjectMapper objectMapper,
EmulatorConfig config, RegionResolver regionResolver,
AccountAccessRoleProvisioner accountAccessRoleProvisioner) {
AccountAccessRoleProvisioner accountAccessRoleProvisioner,
Instance<AccountPlacementListener> placementListeners) {
EmulatorConfig.OrganizationsServiceConfig organizationsConfig = config.services().organizations();
this.scpEnforcementEnabled = organizationsConfig.scpEnforcementEnabled();
this.managementAccountEmail = organizationsConfig.managementAccountEmail()
@@ -185,6 +188,7 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
this.objectMapper = objectMapper;
this.regionResolver = regionResolver;
this.accountAccessRoleProvisioner = accountAccessRoleProvisioner;
this.placementListeners = placementListeners;
this.organizations = storageFactory.create("organizations", "organizations-organizations.json",
new TypeReference<Map<String, Organization>>() {});
this.accounts = storageFactory.create("organizations", "organizations-accounts.json",
@@ -263,6 +267,7 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
? null
: requireValidConfiguredEmail(managementAccountEmail);
this.accountAccessRoleProvisioner = accountAccessRoleProvisioner;
this.placementListeners = List.of();
}
/** A parent reference as returned by {@code ListParents}. */
@@ -655,9 +660,20 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
createAccountStatuses.putForAccount(organization.getMasterAccountId(), status.getId(), status);
LOG.infov("Created account {0} ({1}) in organization {2}", newAccountId, accountName, organization.getId());
placementChanged(organization, newAccountId);
return status;
}
private void placementChanged(Organization organization, String accountId) {
for (AccountPlacementListener listener : placementListeners) {
try {
listener.accountPlacementChanged(organization.getMasterAccountId(), accountId);
} catch (RuntimeException e) {
LOG.warnv(e, "Account placement notification failed for account {0}", accountId);
}
}
}
public CreateAccountStatus describeCreateAccountStatus(String callerAccountId, String requestId) {
Organization organization = requireManagementAccount(callerAccountId);
return createAccountStatuses.getForAccount(organization.getMasterAccountId(), requestId)
@@ -722,6 +738,7 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
}
account.setParentId(destinationParentId);
accounts.putForAccount(organization.getMasterAccountId(), accountId, account);
placementChanged(organization, accountId);
}
public void removeAccountFromOrganization(String callerAccountId, String accountId) {
@@ -733,6 +750,7 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
}
detachAllPoliciesFrom(organization, account.getId());
accounts.deleteForAccount(organization.getMasterAccountId(), account.getId());
placementChanged(organization, account.getId());
}
public void leaveOrganization(String callerAccountId) {
@@ -744,6 +762,7 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
OrganizationAccount account = requireAccount(organization, callerAccountId);
detachAllPoliciesFrom(organization, account.getId());
accounts.deleteForAccount(organization.getMasterAccountId(), account.getId());
placementChanged(organization, account.getId());
}
public OrganizationAccount closeAccount(String callerAccountId, String accountId) {
@@ -1366,6 +1385,9 @@ public class OrganizationsService implements ScpProvider, RootAccessOrganization
handshake.setState(HANDSHAKE_ACCEPTED);
handshakes.putForAccount(organization.getMasterAccountId(), handshakeId, handshake);
if (!HANDSHAKE_ENABLE_ALL_FEATURES.equals(handshake.getAction())) {
placementChanged(organization, callerAccountId);
}
return handshake;
}
@@ -8,16 +8,20 @@ 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.restassured.RestAssured.given;
import static org.awaitility.Awaitility.await;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.not;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
/** AWS Organizations semantics required by service-managed CloudFormation StackSets. */
@QuarkusTest
@@ -479,22 +483,320 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
.body(containsString("<member>" + targetOu + "</member>"));
}
private String createAccount(String email, String name) {
JsonPath response = organizations("CreateAccount",
@Test
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 suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "auto-ou-" + suffix;
String queue = "auto-ou-q-" + suffix;
createAutoDeployingStackSet(management, stackSet, queue, "false");
createStackInstances(management, stackSet, targetOu, REGION);
createStackInstances(management, stackSet, targetOu, "us-west-2");
cloudFormation(management, "ListStackSetAutoDeploymentTargets")
.formParam("StackSetName", stackSet)
.post("/").then().statusCode(200)
.body(containsString("<member>" + REGION + "</member>"))
.body(containsString("<member>us-west-2</member>"));
String account = createAccount(management, "auto-ou-" + suffix + "@example.com", "AutoOu");
assertQueueAbsent(account, queue);
assertNoInstance(management, stackSet, account);
moveAccount(management, account, rootId, childOu);
assertQueueVisible(account, queue);
assertEquals(3, operationIds(management, stackSet).size());
cloudFormation(management, "ListStackInstances")
.formParam("StackSetName", stackSet)
.formParam("StackInstanceAccount", account)
.post("/").then().statusCode(200)
.body(containsString("<Region>" + REGION + "</Region>"))
.body(containsString("<Region>us-west-2</Region>"))
.body(containsString("<OrganizationalUnitId>" + targetOu + "</OrganizationalUnitId>"))
.body(containsString("<DetailedStatus>SUCCEEDED</DetailedStatus>"));
moveAccount(management, account, childOu, targetOu);
assertQueueVisible(account, queue);
assertEquals(3, operationIds(management, stackSet).size());
moveAccount(management, account, targetOu, otherOu);
assertQueueAbsent(account, queue);
assertNoInstance(management, stackSet, account);
assertEquals(4, operationIds(management, stackSet).size());
}
@Test
void automaticDeploymentOperationsCanBeListedAndDescribed() {
String management = "666666666666";
String rootId = createOrganizationWithTrustedAccess(management);
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "auto-operations-" + suffix;
createAutoDeployingStackSet(management, stackSet, "auto-operations-q-" + suffix, "false");
createStackInstances(management, stackSet, rootId, REGION);
List<String> initialOperations = operationIds(management, stackSet);
assertEquals(1, initialOperations.size());
String account = 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);
assertEquals(2, afterCreate.size());
String createOperation = afterCreate.stream()
.filter(id -> !initialOperations.contains(id)).findFirst().orElseThrow();
assertOperation(management, stackSet, createOperation, "CREATE", "SUCCEEDED");
organizations(management, "RemoveAccountFromOrganization", "{\"AccountId\":\"" + account + "\"}")
.post("/").then().statusCode(200);
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
assertEquals(3, operationIds(management, stackSet).size()));
List<String> afterDelete = operationIds(management, stackSet);
assertEquals(3, afterDelete.size());
String deleteOperation = afterDelete.stream()
.filter(id -> !afterCreate.contains(id)).findFirst().orElseThrow();
assertOperation(management, stackSet, deleteOperation, "DELETE", "SUCCEEDED");
}
@Test
void deletingOneTargetRegionPreservesAutomaticDeploymentToTheOtherRegion() {
String management = "676767676767";
String rootId = createOrganizationWithTrustedAccess(management);
String targetOu = 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,
"auto-region-existing-" + suffix + "@example.com", "ExistingRegion");
moveAccount(management, existingAccount, rootId, targetOu);
createAutoDeployingStackSet(management, stackSet, queue, "false");
createStackInstances(management, stackSet, targetOu, REGION);
createStackInstances(management, stackSet, targetOu, "us-west-2");
cloudFormation(management, "DeleteStackInstances")
.formParam("StackSetName", stackSet)
.formParam("DeploymentTargets.OrganizationalUnitIds.member.1", targetOu)
.formParam("Regions.member.1", "us-west-2")
.post("/").then().statusCode(200);
assertQueueVisible(existingAccount, queue);
cloudFormation(management, "ListStackSetAutoDeploymentTargets")
.formParam("StackSetName", stackSet)
.post("/").then().statusCode(200)
.body(containsString("<OrganizationalUnitId>" + targetOu + "</OrganizationalUnitId>"))
.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);
assertQueueVisible(account, queue);
cloudFormation(management, "ListStackInstances")
.formParam("StackSetName", stackSet)
.formParam("StackInstanceAccount", account)
.post("/").then().statusCode(200)
.body(containsString("<Region>" + REGION + "</Region>"))
.body(not(containsString("<Region>us-west-2</Region>")));
}
@Test
void autoDeploymentToTheRootCoversNewAccountsAndRemovesThoseThatLeave() {
String management = "636363636363";
String rootId = createOrganizationWithTrustedAccess(management);
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "auto-root-" + suffix;
String queue = "auto-root-q-" + suffix;
createAutoDeployingStackSet(management, stackSet, queue, "false");
createStackInstances(management, stackSet, rootId, REGION);
String account = createAccount(management, "auto-root-" + suffix + "@example.com", "AutoRoot");
assertQueueVisible(account, queue);
assertQueueAbsent(management, queue);
organizations(management, "RemoveAccountFromOrganization", "{\"AccountId\":\"" + account + "\"}")
.post("/").then().statusCode(200);
assertQueueAbsent(account, queue);
assertNoInstance(management, stackSet, account);
}
@Test
void autoDeploymentRetainsTheStackOfAnAccountThatLeavesItsTargets() {
String management = "646464646464";
String rootId = createOrganizationWithTrustedAccess(management);
String targetOu = 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);
assertQueueVisible(account, queue);
moveAccount(management, account, targetOu, rootId);
assertNoInstance(management, stackSet, account);
assertQueueVisible(account, queue);
}
@Test
void returningAccountGetsANewStackWithoutAdoptingItsRetainedStack() {
String management = "707070707070";
String rootId = createOrganizationWithTrustedAccess(management);
String targetOu = createOu(management, rootId, "RetainedReturn");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "retained-return-" + suffix;
cloudFormation(management, "CreateStackSet")
.formParam("StackSetName", stackSet)
.formParam("TemplateBody", "{\"Resources\":{\"Q\":{\"Type\":\"AWS::SQS::Queue\"}}}")
.formParam("PermissionModel", "SERVICE_MANAGED")
.formParam("AutoDeployment.Enabled", "true")
.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 retained = stackIdForInstance(management, stackSet, account);
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);
String replacement = stackIdForInstance(management, stackSet, account);
assertNotEquals(retained, replacement);
cloudFormation(account, "DescribeStacks")
.formParam("StackName", retained)
.post("/").then().statusCode(200)
.body(containsString("CREATE_COMPLETE"));
}
@Test
void stackSetWithoutAutoDeploymentIgnoresAccountsMovedIntoItsTargets() {
String management = "656565656565";
String rootId = createOrganizationWithTrustedAccess(management);
String targetOu = createOu(management, rootId, "ManualTarget");
String suffix = UUID.randomUUID().toString().substring(0, 8);
String stackSet = "manual-" + suffix;
String queue = "manual-q-" + suffix;
cloudFormation(management, "CreateStackSet")
.formParam("StackSetName", stackSet)
.formParam("TemplateBody", queueTemplate(queue))
.formParam("PermissionModel", "SERVICE_MANAGED")
.formParam("AutoDeployment.Enabled", "false")
.post("/").then().statusCode(200);
createStackInstances(management, stackSet, targetOu, REGION);
String account = createAccount(management, "manual-" + suffix + "@example.com", "Manual");
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");
}
private List<String> operationIds(String management, String stackSet) {
return cloudFormation(management, "ListStackSetOperations")
.formParam("StackSetName", stackSet)
.post("/").then().statusCode(200)
.extract().xmlPath().getList(
"ListStackSetOperationsResponse.ListStackSetOperationsResult.Summaries.member.OperationId",
String.class);
}
private void assertOperation(String management, String stackSet, String operationId, String action, String status) {
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> cloudFormation(management, "DescribeStackSetOperation")
.formParam("StackSetName", stackSet)
.formParam("OperationId", operationId)
.post("/").then().statusCode(200)
.body(containsString("<Action>" + action + "</Action>"))
.body(containsString("<Status>" + status + "</Status>"))
.body(containsString("<CreationTimestamp>"))
.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")
.formParam("StackSetName", stackSet)
.formParam("TemplateBody", queueTemplate(queue))
.formParam("PermissionModel", "SERVICE_MANAGED")
.formParam("AutoDeployment.Enabled", "true")
.formParam("AutoDeployment.RetainStacksOnAccountRemoval", retainStacks)
.post("/").then().statusCode(200);
}
private void createStackInstances(String management, String stackSet, String target, String region) {
cloudFormation(management, "CreateStackInstances")
.formParam("StackSetName", stackSet)
.formParam("DeploymentTargets.OrganizationalUnitIds.member.1", target)
.formParam("Regions.member.1", region)
.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();
return response.getString("CreateAccountStatus.AccountId");
.extract().jsonPath().getString("CreateAccountStatus.AccountId");
}
private void moveAccount(String accountId, String sourceParent, String destinationParent) {
organizations("MoveAccount",
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")
.formParam("StackSetName", stackSet)
.formParam("StackInstanceAccount", account)
.post("/").then().statusCode(200)
.body(not(containsString("<Account>" + account + "</Account>"))));
}
private String stackIdForInstance(String management, String stackSet, String account) {
await().atMost(Duration.ofSeconds(10)).untilAsserted(() ->
cloudFormation(management, "DescribeStackInstance")
.formParam("StackSetName", stackSet)
.formParam("StackInstanceAccount", account)
.formParam("StackInstanceRegion", REGION)
.post("/").then().statusCode(200));
return cloudFormation(management, "DescribeStackInstance")
.formParam("StackSetName", stackSet)
.formParam("StackInstanceAccount", account)
.formParam("StackInstanceRegion", REGION)
.post("/").then().statusCode(200)
.extract().xmlPath().getString(
"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);
}
@@ -561,23 +863,23 @@ class CloudFormationServiceManagedStackSetsIntegrationTest {
}
private void assertQueueVisible(String account, String queueName) {
given()
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> given()
.header("Authorization", auth(account, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueUrl")
.formParam("QueueName", queueName)
.post("/").then().statusCode(200)
.body(containsString("/" + account + "/" + queueName));
.body(containsString("/" + account + "/" + queueName)));
}
private void assertQueueAbsent(String account, String queueName) {
given()
await().atMost(Duration.ofSeconds(10)).untilAsserted(() -> given()
.header("Authorization", auth(account, "sqs"))
.contentType("application/x-www-form-urlencoded")
.formParam("Action", "GetQueueUrl")
.formParam("QueueName", queueName)
.post("/").then().statusCode(400)
.body(containsString("AWS.SimpleQueueService.NonExistentQueue"));
.body(containsString("AWS.SimpleQueueService.NonExistentQueue")));
}
private static String queueTemplate(String queueName) {
@@ -0,0 +1,342 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.cloudformation.model.Stack;
import io.floci.aws.services.cloudformation.model.StackSetOperation;
import io.floci.aws.services.organizations.OrganizationsService;
import io.floci.aws.services.organizations.model.Organization;
import io.floci.aws.services.organizations.model.OrganizationAccount;
import io.floci.aws.testing.InMemoryStorageFactory;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.time.Duration;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import static org.awaitility.Awaitility.await;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
import static org.junit.jupiter.api.Assertions.assertTimeoutPreemptively;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.argThat;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class StackSetAutoDeploymentOperationTest {
private static final String MANAGEMENT = "111111111111";
private static final String ACCOUNT = "222222222222";
private static final String REGION = "us-east-1";
private static final String TARGET = "ou-abcd-abcdefgh";
private static final String SET = "auto-operations";
private CloudFormationService cloudFormation;
private OrganizationsService organizations;
private StackSetService service;
private Stack stack;
@BeforeEach
void setUp() {
cloudFormation = mock(CloudFormationService.class);
organizations = mock(OrganizationsService.class);
Organization organization = new Organization();
organization.setMasterAccountId(MANAGEMENT);
organization.setFeatureSet("ALL");
when(organizations.describeOrganization(MANAGEMENT)).thenReturn(organization);
when(organizations.listAccountsForParent(MANAGEMENT, TARGET)).thenReturn(List.of());
when(organizations.listOrganizationalUnitsForParent(MANAGEMENT, TARGET)).thenReturn(List.of());
OrganizationAccount account = new OrganizationAccount();
account.setId(ACCOUNT);
account.setStatus("ACTIVE");
doReturn(account).when(organizations).describeAccount(MANAGEMENT, ACCOUNT);
when(organizations.organizationPath(MANAGEMENT, ACCOUNT)).thenReturn("r-abcd/" + TARGET + "/" + ACCOUNT);
when(cloudFormation.executeChangeSet(anyString(), anyString(), anyString(), anyString()))
.thenReturn(CompletableFuture.completedFuture(null));
stack = new Stack();
stack.setStackId("stack-id");
stack.setStatus("CREATE_COMPLETE");
when(cloudFormation.describeStacks(anyString(), anyString(), anyString())).thenReturn(List.of(stack));
service = new StackSetService(cloudFormation, new InMemoryStorageFactory(MANAGEMENT), organizations,
new RegionResolver(REGION, MANAGEMENT));
service.activateOrganizationsAccess();
service.createStackSet(SET, "{\"Resources\":{}}", null, null, null, null,
"SERVICE_MANAGED", true, false, false);
service.createStackInstances(SET, List.of(), List.of(REGION), List.of(TARGET), null);
}
@AfterEach
void stopAccountPlacementExecutor() {
service.stopAccountPlacementExecutor();
}
@Test
void failedAutomaticCreateRecordsFailedOperation() {
stack.setStatus("ROLLBACK_COMPLETE");
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertAutomaticOperation("CREATE", "FAILED", 2));
assertEquals("FAILED", service.describeStackInstance(SET, ACCOUNT, REGION).getDetailedStatus());
}
@Test
void failedAutomaticDeleteRecordsFailedOperationAndKeepsInstance() {
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertAutomaticOperation("CREATE", "SUCCEEDED", 2));
when(organizations.describeAccount(MANAGEMENT, ACCOUNT))
.thenThrow(new AwsException("AccountNotFoundException", "Account left the organization", 404));
when(cloudFormation.deleteStack(anyString(), anyString(), anyString()))
.thenReturn(CompletableFuture.failedFuture(new IllegalStateException("Delete failed")));
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertAutomaticOperation("DELETE", "FAILED", 3));
assertEquals("INOPERABLE", service.describeStackInstance(SET, ACCOUNT, REGION).getStatus());
}
@Test
void automaticCreateExceptionCompletesOperationAsFailed() {
when(cloudFormation.createChangeSet(anyString(), anyString(), anyString(), anyString(),
isNull(), any(), any(), any(), anyString(), anyString()))
.thenThrow(new AwsException("ValidationError", "Invalid deployment", 400));
assertDoesNotThrow(() -> service.accountPlacementChanged(MANAGEMENT, ACCOUNT));
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertAutomaticOperation("CREATE", "FAILED", 2));
}
@Test
void stackExecutionCanNotifyAccountPlacementWhileTheCallerWaits() {
OrganizationAccount account = organizations.describeAccount(MANAGEMENT, ACCOUNT);
when(organizations.listAccountsForParent(MANAGEMENT, TARGET)).thenReturn(List.of(account));
when(cloudFormation.executeChangeSet(anyString(), anyString(), anyString(), anyString()))
.thenAnswer(ignored -> CompletableFuture.runAsync(() ->
service.accountPlacementChanged(MANAGEMENT, ACCOUNT)));
assertTimeoutPreemptively(Duration.ofSeconds(3), () ->
service.createStackInstances(SET, List.of(), List.of(REGION), List.of(TARGET), null));
}
@Test
void aFailedDeploymentDoesNotPreventAnotherStackSetFromDeploying() {
String healthy = "healthy-auto";
service.createStackSet(healthy, "{\"Resources\":{}}", null, null, null, null,
"SERVICE_MANAGED", true, false, false);
service.createStackInstances(healthy, List.of(), List.of(REGION), List.of(TARGET), null);
when(cloudFormation.createChangeSet(argThat(name -> name != null && name.startsWith("StackSet-" + SET + "-")),
anyString(), anyString(), anyString(), isNull(), any(), any(), any(), anyString(), anyString()))
.thenThrow(new AwsException("ValidationError", "Invalid deployment", 400));
assertDoesNotThrow(() -> service.accountPlacementChanged(MANAGEMENT, ACCOUNT));
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
assertAutomaticOperation("CREATE", "FAILED", 2);
assertEquals(1, service.listStackInstances(healthy, ACCOUNT, REGION).size());
assertEquals("SUCCEEDED", service.describeStackInstance(healthy, ACCOUNT, REGION).getDetailedStatus());
});
}
@Test
void accountWorkerKeepsTheRuntimeClassLoaderWithoutInheritingRequestThreadLocals() throws Exception {
OrganizationAccount account = organizations.describeAccount(MANAGEMENT, ACCOUNT);
ClassLoader original = Thread.currentThread().getContextClassLoader();
ClassLoader runtime = new ClassLoader(original) {};
InheritableThreadLocal<String> requestValue = new InheritableThreadLocal<>();
CompletableFuture<WorkerContext> observed = new CompletableFuture<>();
when(organizations.describeAccount(MANAGEMENT, ACCOUNT)).thenAnswer(ignored -> {
observed.complete(new WorkerContext(Thread.currentThread().getContextClassLoader(), requestValue.get()));
return account;
});
requestValue.set("request");
Thread.currentThread().setContextClassLoader(runtime);
try {
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
WorkerContext context = observed.get(5, TimeUnit.SECONDS);
assertSame(runtime, context.classLoader());
assertNull(context.requestValue());
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertAutomaticOperation("CREATE", "SUCCEEDED", 2));
} finally {
Thread.currentThread().setContextClassLoader(original);
requestValue.remove();
}
}
private record WorkerContext(ClassLoader classLoader, String requestValue) {}
@Test
void aRemovedOrganizationDoesNotPreventAutomaticDeletionOfItsAccountInstances() {
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertAutomaticOperation("CREATE", "SUCCEEDED", 2));
when(organizations.describeAccount(MANAGEMENT, ACCOUNT))
.thenThrow(new AwsException("AWSOrganizationsNotInUseException", "The organization was deleted", 400));
when(cloudFormation.deleteStack(anyString(), anyString(), anyString()))
.thenReturn(CompletableFuture.completedFuture(null));
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
assertAutomaticOperation("DELETE", "SUCCEEDED", 3);
assertEquals(0, service.listStackInstances(SET, ACCOUNT, REGION).size());
});
}
@Test
void aRejectedAutomaticDeleteMarksTheInstanceFailed() {
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertAutomaticOperation("CREATE", "SUCCEEDED", 2));
when(organizations.describeAccount(MANAGEMENT, ACCOUNT))
.thenThrow(new AwsException("AccountNotFoundException", "Account left the organization", 404));
when(cloudFormation.deleteStack(anyString(), anyString(), anyString()))
.thenThrow(new AwsException("ValidationError", "Termination protection is enabled", 400));
assertDoesNotThrow(() -> service.accountPlacementChanged(MANAGEMENT, ACCOUNT));
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
assertAutomaticOperation("DELETE", "FAILED", 3);
assertEquals("INOPERABLE", service.describeStackInstance(SET, ACCOUNT, REGION).getStatus());
assertEquals("Termination protection is enabled",
service.describeStackInstance(SET, ACCOUNT, REGION).getStatusReason());
});
}
@Test
void aRetainedStackDoesNotPreventAnAccountReturningToItsTarget() {
service.describeStackSet(SET).setRetainStacksOnAccountRemoval(true);
OrganizationAccount account = organizations.describeAccount(MANAGEMENT, ACCOUNT);
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertAutomaticOperation("CREATE", "SUCCEEDED", 2));
String retainedName = service.describeStackInstance(SET, ACCOUNT, REGION).getStackName();
when(organizations.describeAccount(MANAGEMENT, ACCOUNT))
.thenThrow(new AwsException("AccountNotFoundException", "Account left the organization", 404));
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() ->
assertAutomaticOperation("DELETE", "SUCCEEDED", 3));
doReturn(account).when(organizations).describeAccount(MANAGEMENT, ACCOUNT);
when(cloudFormation.stackStatus(retainedName, REGION, ACCOUNT)).thenReturn("CREATE_COMPLETE");
when(cloudFormation.createChangeSet(eq(retainedName), anyString(), anyString(), anyString(),
isNull(), any(), any(), any(), anyString(), anyString()))
.thenThrow(new AwsException("AlreadyExistsException", "The retained stack exists", 400));
service.accountPlacementChanged(MANAGEMENT, ACCOUNT);
await().atMost(Duration.ofSeconds(5)).untilAsserted(() -> {
assertAutomaticOperation("CREATE", "SUCCEEDED", 4);
assertNotEquals(retainedName, service.describeStackInstance(SET, ACCOUNT, REGION).getStackName());
});
}
@Test
void aRejectedExplicitDeleteRecordsFailureAndContinuesOtherInstances() {
String protectedAccount = "333333333333";
String otherAccount = "444444444444";
OrganizationAccount first = organizations.describeAccount(MANAGEMENT, ACCOUNT);
OrganizationAccount protectedMember = new OrganizationAccount();
protectedMember.setId(protectedAccount);
protectedMember.setStatus("ACTIVE");
OrganizationAccount other = new OrganizationAccount();
other.setId(otherAccount);
other.setStatus("ACTIVE");
when(organizations.listAccountsForParent(MANAGEMENT, TARGET))
.thenReturn(List.of(first, protectedMember, other));
service.createStackInstances(SET, List.of(), List.of(REGION), List.of(TARGET), null);
service.describeStackSet(SET).setRetainStacksOnAccountRemoval(true);
when(cloudFormation.deleteStack(anyString(), eq(REGION), anyString()))
.thenReturn(CompletableFuture.completedFuture(null));
when(cloudFormation.deleteStack(anyString(), eq(REGION), eq(protectedAccount)))
.thenThrow(new AwsException("ValidationError", "Termination protection is enabled", 400));
StackSetOperation operation = assertDoesNotThrow(() ->
service.deleteStackInstances(SET, List.of(), List.of(REGION), List.of(TARGET), false));
assertEquals("FAILED", operation.getStatus());
assertEquals("FAILED",
service.describeStackSetOperation(SET, operation.getOperationId()).getStatus());
assertNotNull(operation.getCreationTimestamp());
assertNotNull(operation.getEndTimestamp());
assertEquals(1, service.listStackInstances(SET, null, null).size());
assertEquals("INOPERABLE", service.describeStackInstance(SET, protectedAccount, REGION).getStatus());
assertEquals("FAILED", service.describeStackInstance(SET, protectedAccount, REGION).getDetailedStatus());
assertEquals("Termination protection is enabled",
service.describeStackInstance(SET, protectedAccount, REGION).getStatusReason());
assertEquals(1, service.listStackSetAutoDeploymentTargets(SET).size());
verify(cloudFormation).deleteStack(anyString(), eq(REGION), eq(ACCOUNT));
verify(cloudFormation).deleteStack(anyString(), eq(REGION), eq(otherAccount));
doReturn(CompletableFuture.completedFuture(null)).when(cloudFormation)
.deleteStack(anyString(), eq(REGION), eq(protectedAccount));
StackSetOperation retry = service.deleteStackInstances(
SET, List.of(), List.of(REGION), List.of(TARGET), false);
assertEquals("SUCCEEDED", retry.getStatus());
assertEquals(0, service.listStackInstances(SET, null, null).size());
assertEquals(0, service.listStackSetAutoDeploymentTargets(SET).size());
}
@Test
void anExplicitRetainedDeleteDoesNotUseTheAutomaticRemovalFlag() {
OrganizationAccount account = organizations.describeAccount(MANAGEMENT, ACCOUNT);
when(organizations.listAccountsForParent(MANAGEMENT, TARGET)).thenReturn(List.of(account));
service.createStackInstances(SET, List.of(), List.of(REGION), List.of(TARGET), null);
StackSetOperation operation = service.deleteStackInstances(
SET, List.of(), List.of(REGION), List.of(TARGET), true);
assertEquals("SUCCEEDED", operation.getStatus());
assertEquals(0, service.listStackInstances(SET, null, null).size());
assertEquals(0, service.listStackSetAutoDeploymentTargets(SET).size());
verify(cloudFormation, never()).deleteStack(anyString(), anyString(), anyString());
}
@Test
void aRejectedSelfManagedDeleteRecordsTheFailedInstanceAndOperation() {
String name = "explicit-self-managed";
service.createStackSet(name, "{\"Resources\":{}}", null, null, null, null);
service.createStackInstances(name, List.of(ACCOUNT), List.of(REGION));
when(cloudFormation.deleteStack(anyString(), anyString(), anyString()))
.thenThrow(new AwsException("ValidationError", "Termination protection is enabled", 400));
StackSetOperation operation = assertDoesNotThrow(() ->
service.deleteStackInstances(name, List.of(ACCOUNT), List.of(REGION), false));
assertEquals("FAILED", operation.getStatus());
assertEquals("FAILED",
service.describeStackSetOperation(name, operation.getOperationId()).getStatus());
assertEquals("INOPERABLE", service.describeStackInstance(name, ACCOUNT, REGION).getStatus());
assertEquals("FAILED", service.describeStackInstance(name, ACCOUNT, REGION).getDetailedStatus());
assertEquals("Termination protection is enabled",
service.describeStackInstance(name, ACCOUNT, REGION).getStatusReason());
}
private void assertAutomaticOperation(String action, String status, int count) {
List<StackSetOperation> operations = service.listStackSetOperations(SET);
assertEquals(count, operations.size());
StackSetOperation operation = operations.getFirst();
assertEquals(action, operation.getAction());
assertEquals(status, operation.getStatus());
assertNotNull(operation.getCreationTimestamp());
assertNotNull(operation.getEndTimestamp());
assertEquals(operation.getOperationId(),
service.describeStackSetOperation(SET, operation.getOperationId()).getOperationId());
}
}