diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 16183d4fd8..a5c2efd8af 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -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.
diff --git a/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java b/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java
index 3b5129d181..604afa607e 100644
--- a/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java
+++ b/src/main/java/io/floci/aws/services/cloudformation/StackSetService.java
@@ -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.
+ *
+ *
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 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 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 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 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 ancestors) {
+ String name = stackSet.getStackSetName();
+ Map> 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 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> 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 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> 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 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 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;
}
diff --git a/src/main/java/io/floci/aws/services/organizations/AccountPlacementListener.java b/src/main/java/io/floci/aws/services/organizations/AccountPlacementListener.java
new file mode 100644
index 0000000000..80f01dc449
--- /dev/null
+++ b/src/main/java/io/floci/aws/services/organizations/AccountPlacementListener.java
@@ -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").
+ *
+ * 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);
+}
diff --git a/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java b/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java
index e9f93591dc..1b02a7abc4 100644
--- a/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java
+++ b/src/main/java/io/floci/aws/services/organizations/OrganizationsService.java
@@ -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 placementListeners;
@Inject
public OrganizationsService(StorageFactory storageFactory, ObjectMapper objectMapper,
EmulatorConfig config, RegionResolver regionResolver,
- AccountAccessRoleProvisioner accountAccessRoleProvisioner) {
+ AccountAccessRoleProvisioner accountAccessRoleProvisioner,
+ Instance 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