mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): deploy a service-managed stack set to accounts that join or leave its targets (#7243)
This commit is contained in:
1 parent
e0692092b5
commit
01c84245a7
6 files changed
+873
-28
No files matched your search
+312
-10
@@ -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) {
|
||||
|
||||
+342
@@ -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());
|
||||
}
|
||||
|
||||
}
|
||||
Reference in new issue
Block a user