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

@@ -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;
}