feat(cloudformation): add StackSets with account-aware provisioning (#1551)

* feat(cloudformation): add StackSets with account-aware provisioning

Implement CloudFormation StackSets so a template can be deployed across
target accounts and regions, and make CloudFormation provisioning land
resources in the correct account.

Provisioning previously ran on a background executor thread with no request
scope, so the downstream service calls fell back to the default account — a
stack created by account B materialised its resources under 000000000000.
executeChangeSet/deleteStack now run the provisioning under a synthetic
request scope bound to the deploying account (the caller's account for a
single stack, the target account for a StackSet instance), mirroring the
pattern other background workers already use. Single-stack resources now
land in the caller's account.

StackSet actions are wired through CloudFormationQueryHandler and
AwsQueryController: CreateStackSet, DescribeStackSet, ListStackSets,
UpdateStackSet, DeleteStackSet, CreateStackInstances, ListStackInstances,
DeleteStackInstances, ListStackSetOperations. CreateStackInstances drives
the existing single-stack engine once per target (account, region),
provisioning each instance into that account's namespace; the stack set,
its instances and its operation history live in the administration account.

Tests: an integration test deploying a StackSet from an admin account into
accounts B and C asserts the resources materialise in B and C and are
invisible to the admin/default account, exercises describe/list/operations
and instance deletion, and covers the not-found / already-exists /
not-empty error paths. A single-stack test asserts resources now land in
the caller's account.

Design aligned with maintainers in floci-io/floci#1550.

* fix(cloudformation): await StackSet instance deletion; test UpdateStackSet

Make the account-scoped deleteStack overload return its Future so
DeleteStackInstances completes synchronously before the operation returns,
rather than racing the async resource removal. Add integration coverage for
UpdateStackSet re-applying the template to existing instances.

* test(cloudformation): add SDK compatibility test for StackSets

Adds an sdk-test-java compatibility test exercising StackSets through the real
AWS SDK CloudFormationClient (CreateStackSet, CreateStackInstances,
DescribeStackSet, ListStackInstances, ListStackSetOperations,
DeleteStackInstances, DeleteStackSet). It asserts the management responses
unmarshal cleanly and that instances provision into each target account's
namespace (verified via per-account SQS clients), per the project's policy of
validating management APIs with AWS SDK clients. Runs in the compatibility CI
on pull requests.

* feat(cloudformation): add DescribeStackInstance and DescribeStackSetOperation

Complete the StackSets API surface with the singular describe operations:
DescribeStackInstance (used by orchestration that polls a single instance's
status) and DescribeStackSetOperation (companion to ListStackSetOperations).
Covered by the integration test and the SDK compatibility test, which confirm
the StackInstance / StackSetOperation response shapes unmarshal through the
real AWS SDK.

* feat(cloudformation): resolve TemplateURL and report StackInstanceStatus.DetailedStatus for StackSets

StackSet create/update now resolve a TemplateURL (fetched from S3) in addition
to an inline TemplateBody, matching how orchestration tools reference templates
staged in S3. DescribeStackInstance and ListStackInstances now also report the
nested StackInstanceStatus.DetailedStatus that AWS returns and that pollers read
to determine when an instance operation has completed.

* feat(cloudformation): derive StackSet operation status and honor RetainStacks

Address review feedback on #1551:

- Operation status is now derived from instance outcomes: CreateStackInstances
  and UpdateStackSet report FAILED if any instance fails to deploy, instead of
  always SUCCEEDED. deployInstance also recognizes a rolled-back create
  (ROLLBACK_COMPLETE, not *_FAILED) as a failed/INOPERABLE instance, which was
  previously mis-reported as SUCCEEDED.
- DeleteStackInstances honors RetainStacks: when true, the instance is detached
  from the stack set but its underlying stack and resources are left in place.
- UpdateStackSet now persists the refreshed instance records.

Tests: RetainStacks retention and the FAILED-operation path; docs updated.

* fix(cloudformation): restore account on active scope; log StackSets test teardown

Greptile review on #1551:
- runUnderAccount now saves and restores the previous account ID when it runs
  inside an already-active request scope, so it can't leave the overridden
  account behind on a reused thread. (Background workers normally have no active
  scope, so this only hardens the synchronous-caller path.)
- CloudFormationStackSetsTest teardown no longer swallows exceptions silently;
  it logs them, per the AGENTS.md no-empty-catch rule.

* fix(cloudformation): report a failed StackSet instance delete as FAILED

deleteStackInstances awaited the underlying deleteStack via a helper that
swallows the failure, then removed the instance record unconditionally and
hardcoded the operation status to SUCCEEDED. A failed non-retained delete was
therefore reported as a success with the instance silently dropped.

await() now returns whether the future completed cleanly. On a non-retained
delete failure the instance record is retained (marked INOPERABLE/FAILED) and
the operation status is derived via deriveOperationStatus, so it reports FAILED
— matching AWS, which does not detach an instance whose stack delete failed.

Adds StackSetServiceDeleteFailureTest covering the failure, success, and
RetainStacks paths.

* fix(cloudformation): reject templateless CreateStackSet and restore interrupt in await

CreateStackSet now rejects a request with neither TemplateBody nor TemplateURL (ValidationError,
matching AWS) instead of storing a null template — which would otherwise make a later
CreateStackInstances deploy empty stacks into every target account. Also handle
InterruptedException separately in await(Future) and restore the thread's interrupt flag, so a
shutdown signal to the backing ExecutorService propagates instead of being swallowed. Adds a
CreateStackSet-without-template integration test.
This commit is contained in:
Alex Banna authored and GitHub committed 2026-07-01 23:11:16 -05:00
1 parent a27971c7d5
commit 058e02630a
12 files changed
+1642 -12

No files matched your search

@@ -0,0 +1,169 @@
package com.floci.test;
import org.junit.jupiter.api.*;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.*;
import software.amazon.awssdk.services.sqs.SqsClient;
import software.amazon.awssdk.services.sqs.model.QueueDoesNotExistException;
import java.util.List;
import static org.assertj.core.api.Assertions.*;
/**
* Verifies CloudFormation StackSets through the real AWS SDK: a stack set created in the
* administration account provisions instances into target accounts, the management responses
* unmarshal cleanly, and the provisioned resources land in each target account's namespace.
*/
@DisplayName("CloudFormation StackSets cross-account provisioning")
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class CloudFormationStackSetsTest {
private static final String ACCOUNT_B = "222222222222";
private static final String ACCOUNT_C = "333333333333";
private static final String REGION = "us-east-1";
private static CloudFormationClient cfn;
private static String stackSetName;
private static String queueName;
@BeforeAll
static void setup() {
cfn = TestFixtures.cloudFormationClient();
stackSetName = TestFixtures.uniqueName("compat-stackset");
queueName = TestFixtures.uniqueName("compat-ss-queue");
}
@AfterAll
static void teardown() {
try {
cfn.deleteStackInstances(r -> r.stackSetName(stackSetName)
.accounts(ACCOUNT_B, ACCOUNT_C).regions(REGION).retainStacks(false));
} catch (Exception e) {
System.err.println("teardown: deleteStackInstances for " + stackSetName + " failed: " + e.getMessage());
}
try {
cfn.deleteStackSet(r -> r.stackSetName(stackSetName));
} catch (Exception e) {
System.err.println("teardown: deleteStackSet for " + stackSetName + " failed: " + e.getMessage());
}
cfn.close();
}
private static SqsClient sqsFor(String account) {
return SqsClient.builder()
.endpointOverride(TestFixtures.endpoint())
.region(Region.US_EAST_1)
.credentialsProvider(StaticCredentialsProvider.create(
AwsBasicCredentials.create(account, "test")))
.build();
}
private static String queueTemplate(String queue) {
return "{\"Resources\":{\"Q\":{\"Type\":\"AWS::SQS::Queue\","
+ "\"Properties\":{\"QueueName\":\"" + queue + "\"}}}}";
}
@Test
@Order(1)
void createStackSet() {
CreateStackSetResponse resp = cfn.createStackSet(r -> r
.stackSetName(stackSetName)
.templateBody(queueTemplate(queueName)));
assertThat(resp.stackSetId()).isNotBlank();
}
@Test
@Order(2)
void describeStackSetReturnsDefinition() {
DescribeStackSetResponse resp = cfn.describeStackSet(r -> r.stackSetName(stackSetName));
StackSet ss = resp.stackSet();
assertThat(ss.stackSetName()).isEqualTo(stackSetName);
assertThat(ss.status()).isEqualTo(StackSetStatus.ACTIVE);
assertThat(ss.templateBody()).contains(queueName);
}
@Test
@Order(3)
void createStackInstancesProvisionsIntoTargetAccounts() {
CreateStackInstancesResponse resp = cfn.createStackInstances(r -> r
.stackSetName(stackSetName)
.accounts(ACCOUNT_B, ACCOUNT_C)
.regions(REGION));
assertThat(resp.operationId()).isNotBlank();
// The queue materializes in each target account's namespace...
try (SqsClient b = sqsFor(ACCOUNT_B); SqsClient c = sqsFor(ACCOUNT_C)) {
assertThat(b.getQueueUrl(g -> g.queueName(queueName)).queueUrl())
.contains("/" + ACCOUNT_B + "/" + queueName);
assertThat(c.getQueueUrl(g -> g.queueName(queueName)).queueUrl())
.contains("/" + ACCOUNT_C + "/" + queueName);
}
// ...and not in the administration account.
try (SqsClient admin = TestFixtures.sqsClient()) {
assertThatThrownBy(() -> admin.getQueueUrl(g -> g.queueName(queueName)))
.isInstanceOf(QueueDoesNotExistException.class);
}
}
@Test
@Order(4)
void listStackInstancesReportsTargets() {
List<StackInstanceSummary> summaries = cfn.listStackInstances(r -> r.stackSetName(stackSetName))
.summaries();
assertThat(summaries).hasSize(2);
assertThat(summaries).extracting(StackInstanceSummary::account)
.containsExactlyInAnyOrder(ACCOUNT_B, ACCOUNT_C);
assertThat(summaries).allSatisfy(s -> assertThat(s.region()).isEqualTo(REGION));
// DescribeStackInstance (singular) — the operation DPS's state machine actually calls.
StackInstance inst = cfn.describeStackInstance(r -> r.stackSetName(stackSetName)
.stackInstanceAccount(ACCOUNT_B).stackInstanceRegion(REGION)).stackInstance();
assertThat(inst.account()).isEqualTo(ACCOUNT_B);
assertThat(inst.region()).isEqualTo(REGION);
assertThat(inst.stackId()).isNotBlank();
}
@Test
@Order(5)
void listStackSetOperationsRecordsCreate() {
List<StackSetOperationSummary> ops = cfn.listStackSetOperations(r -> r.stackSetName(stackSetName))
.summaries();
assertThat(ops).isNotEmpty();
assertThat(ops).extracting(StackSetOperationSummary::action)
.contains(StackSetOperationAction.CREATE);
String opId = ops.stream().filter(o -> o.action() == StackSetOperationAction.CREATE)
.findFirst().orElseThrow().operationId();
StackSetOperation op = cfn.describeStackSetOperation(r -> r.stackSetName(stackSetName)
.operationId(opId)).stackSetOperation();
assertThat(op.operationId()).isEqualTo(opId);
assertThat(op.action()).isEqualTo(StackSetOperationAction.CREATE);
assertThat(op.status()).isEqualTo(StackSetOperationStatus.SUCCEEDED);
}
@Test
@Order(6)
void deleteStackInstancesRemovesResources() {
cfn.deleteStackInstances(r -> r.stackSetName(stackSetName)
.accounts(ACCOUNT_B, ACCOUNT_C).regions(REGION).retainStacks(false));
assertThat(cfn.listStackInstances(r -> r.stackSetName(stackSetName)).summaries()).isEmpty();
try (SqsClient b = sqsFor(ACCOUNT_B)) {
assertThatThrownBy(() -> b.getQueueUrl(g -> g.queueName(queueName)))
.isInstanceOf(QueueDoesNotExistException.class);
}
}
@Test
@Order(7)
void deleteStackSetSucceedsWhenEmpty() {
cfn.deleteStackSet(r -> r.stackSetName(stackSetName));
assertThatThrownBy(() -> cfn.describeStackSet(r -> r.stackSetName(stackSetName)))
.isInstanceOf(StackSetNotFoundException.class);
}
}