feat(redshift): provision AWS::Redshift::Cluster through CloudFormation (#3427)

* feat(cloudformation): provision AWS::Redshift::Cluster (create path)

* feat(cloudformation): AWS::Redshift::Cluster update and replacement

* feat(cloudformation): force replacement on Redshift cluster createOnly property change

* feat(cloudformation): force replacement on Redshift cluster DBName change

* feat(cloudformation): provision Redshift parameter, subnet and security groups

* chore(cloudformation): register Redshift provisioner in inventory and docs

* test(cloudformation): end-to-end AWS::Redshift::Cluster stack

* docs(redshift): document CloudFormation cluster provisioning

* test(cloudformation): assert ClusterSubnetGroupNotFound error code on subnet group deletion

* fix(cloudformation): correct attribute handling for Redshift security group provisioning

* fix(cloudformation): apply Redshift parameter group Parameters and fix docs

ClusterParameterGroup silently dropped Properties.Parameters on both
create and update instead of calling ModifyClusterParameterGroup, and
did not replace the entity when Description or ParameterGroupFamily
changed, even though AWS marks both as replacement properties.

Also remove the Id GetAtt claim from the Cluster docs: neither the
provisioner nor AWS's own schema expose it for AWS::Redshift::Cluster.
This commit is contained in:
Vũ Thế Huy authored and GitHub committed 2026-09-13 18:45:40 -05:00
1 parent 55ada9b8a3
commit e5bd8be405
11 files changed
+1461 -1

No files matched your search

@@ -65,6 +65,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.LambdaVer
import io.github.hectorvent.floci.services.cloudformation.provisioners.LogsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.PipesCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.RdsCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.RedshiftClusterCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.Route53CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.S3CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.SchedulerScheduleGroupCfnProvisioner;
@@ -98,6 +99,7 @@ import io.github.hectorvent.floci.services.lambda.LambdaLayerService;
import io.github.hectorvent.floci.services.lambda.LambdaService;
import io.github.hectorvent.floci.services.pipes.PipesService;
import io.github.hectorvent.floci.services.rds.RdsService;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.route53.Route53Service;
import io.github.hectorvent.floci.services.s3.S3Service;
import io.github.hectorvent.floci.services.scheduler.SchedulerService;
@@ -184,6 +186,7 @@ final class CfnProvisionerFixture {
private SqsService sqsService;
private WafV2Service wafV2Service;
private BackupService backupService;
private RedshiftService redshiftService;
private CloudFormationResourceRegistry resourceRegistry;
private boolean registryChosenByTest;
private CfnDynamicReferences dynamicReferences;
@@ -355,6 +358,9 @@ final class CfnProvisionerFixture {
if (schedulerService != null) {
discovered.add(new SchedulerScheduleGroupCfnProvisioner(schedulerService));
}
if (redshiftService != null) {
discovered.add(new RedshiftClusterCfnProvisioner(redshiftService));
}
return discovered;
}
@@ -593,6 +599,15 @@ final class CfnProvisionerFixture {
return this;
}
public Builder redshiftService(RedshiftService s) {
this.redshiftService = s;
return this;
}
public Builder redshift(RedshiftService s) {
return redshiftService(s);
}
public Builder registry(CloudFormationResourceRegistry v) {
this.resourceRegistry = v;
this.registryChosenByTest = true;
@@ -0,0 +1,313 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.core.common.XmlParser;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.specification.RequestSpecification;
import org.awaitility.Awaitility;
import org.awaitility.core.ConditionTimeoutException;
import org.jboss.logging.Logger;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Assumptions;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.junit.jupiter.api.Assertions.fail;
/**
* End-to-end integration test provisioning AWS::Redshift::Cluster,
* AWS::Redshift::ClusterParameterGroup, AWS::Redshift::ClusterSubnetGroup,
* and AWS::Redshift::ClusterSecurityGroup through CloudFormation stacks.
*/
@QuarkusTest
class RedshiftClusterCfnIntegrationTest {
private static final Logger LOG = Logger.getLogger(RedshiftClusterCfnIntegrationTest.class);
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/cloudformation/aws4_request";
private static final String REDSHIFT_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260903/us-east-1/redshift/aws4_request";
private final List<String> stacksToCleanup = new ArrayList<>();
@BeforeAll
static void configure() {
Assumptions.assumeTrue(dockerAvailable(), "Docker is required for this integration test");
RestAssuredJsonUtils.configureAwsContentTypes();
}
private static boolean dockerAvailable() {
try {
Process p = new ProcessBuilder("docker", "version", "--format", "{{.Server.Version}}")
.redirectErrorStream(true).start();
return p.waitFor() == 0;
} catch (Exception e) {
return false;
}
}
@AfterEach
void cleanUp() {
for (String stack : stacksToCleanup) {
try {
cloudFormation(stack, "DeleteStack", null);
awaitStackDeleted(stack);
} catch (Exception e) {
LOG.warnv("Failed to clean up stack {0}: {1}", stack, e.getMessage());
}
}
stacksToCleanup.clear();
}
@Test
void createStackProvisionsRealClusterWithEndpointOutputs() throws Exception {
String stackName = "rs-cfn-it-" + System.currentTimeMillis();
String clusterId = stackName + "-wh";
stacksToCleanup.add(stackName);
String template = """
{
"Resources": {
"Warehouse": {
"Type": "AWS::Redshift::Cluster",
"Properties": {
"ClusterIdentifier": "%s",
"NodeType": "ra3.large",
"MasterUsername": "admin",
"MasterUserPassword": "Secret12345",
"ClusterType": "single-node",
"DBName": "dev"
}
}
},
"Outputs": {
"Addr": {"Value": {"Fn::GetAtt": ["Warehouse", "Endpoint.Address"]}},
"Port": {"Value": {"Fn::GetAtt": ["Warehouse", "Endpoint.Port"]}},
"Ns": {"Value": {"Fn::GetAtt": ["Warehouse", "ClusterNamespaceArn"]}}
}
}""".formatted(clusterId);
cloudFormation(stackName, "CreateStack", template);
String stacks = describeStacks(stackName, "CREATE_COMPLETE");
String addr = outputValue(stacks, "Addr");
String portStr = outputValue(stacks, "Port");
String ns = outputValue(stacks, "Ns");
assertNotNull(addr, "Endpoint.Address output must not be null");
assertFalse(addr.isBlank(), "Endpoint.Address output must not be blank");
assertNotNull(portStr, "Endpoint.Port output must not be null");
int port = Integer.parseInt(portStr);
assertTrue(port > 0, "Endpoint.Port must be a positive integer: " + port);
assertNotNull(ns, "ClusterNamespaceArn output must not be null");
assertTrue(ns.startsWith("arn:aws:redshift:"),
"ClusterNamespaceArn output must start with arn:aws:redshift:, got: " + ns);
// Fall back to 127.0.0.1 when hostname is host.docker.internal to avoid CI resolution issues
String connectHost = "host.docker.internal".equalsIgnoreCase(addr) ? "127.0.0.1" : addr;
try (Connection conn = waitForConnection(connectHost, port, "admin", "Secret12345");
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT 1")) {
assertTrue(rs.next());
assertEquals(1, rs.getInt(1));
}
cloudFormation(stackName, "DeleteStack", null);
awaitStackDeleted(stackName);
stacksToCleanup.remove(stackName);
assertClusterNotFound(clusterId);
}
@Test
void createStackProvisionsParameterAndSubnetGroups() throws Exception {
String stackName = "rs-groups-it-" + System.currentTimeMillis();
String pgName = stackName + "-pg";
String sgName = stackName + "-sg";
stacksToCleanup.add(stackName);
String template = """
{
"Resources": {
"ParamGroup": {
"Type": "AWS::Redshift::ClusterParameterGroup",
"Properties": {
"ParameterGroupName": "%s",
"ParameterGroupFamily": "redshift-1.0",
"Description": "Test parameter group for CFN integration"
}
},
"SubnetGroup": {
"Type": "AWS::Redshift::ClusterSubnetGroup",
"Properties": {
"ClusterSubnetGroupName": "%s",
"Description": "Test subnet group for CFN integration",
"SubnetIds": ["subnet-12345678", "subnet-87654321"]
}
},
"SecurityGroup": {
"Type": "AWS::Redshift::ClusterSecurityGroup",
"Properties": {
"Description": "Test security group for CFN integration"
}
}
},
"Outputs": {
"PgRef": {"Value": {"Ref": "ParamGroup"}},
"SgRef": {"Value": {"Ref": "SubnetGroup"}},
"SgName": {"Value": {"Fn::GetAtt": ["SubnetGroup", "ClusterSubnetGroupName"]}},
"SecurityGroupRef": {"Value": {"Ref": "SecurityGroup"}},
"SecurityGroupId": {"Value": {"Fn::GetAtt": ["SecurityGroup", "Id"]}}
}
}""".formatted(pgName, sgName);
cloudFormation(stackName, "CreateStack", template);
String stacks = describeStacks(stackName, "CREATE_COMPLETE");
assertEquals(pgName, outputValue(stacks, "PgRef"));
assertEquals(sgName, outputValue(stacks, "SgRef"));
assertEquals(sgName, outputValue(stacks, "SgName"));
assertEquals(outputValue(stacks, "SecurityGroupRef"), outputValue(stacks, "SecurityGroupId"));
assertParameterGroupExists(pgName, "redshift-1.0");
assertSubnetGroupExists(sgName);
cloudFormation(stackName, "DeleteStack", null);
awaitStackDeleted(stackName);
stacksToCleanup.remove(stackName);
assertParameterGroupNotFound(pgName);
assertSubnetGroupNotFound(sgName);
}
private static Connection waitForConnection(String host, int port, String username, String password) throws SQLException {
try {
return Awaitility.await()
.atMost(Duration.ofSeconds(30))
.pollInterval(Duration.ofMillis(500))
.ignoreExceptions()
.until(() -> DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/dev", username, password), Objects::nonNull);
} catch (ConditionTimeoutException e) {
return DriverManager.getConnection("jdbc:postgresql://" + host + ":" + port + "/dev", username, password);
}
}
private static void cloudFormation(String stack, String action, String templateBody) {
RequestSpecification request = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", action)
.formParam("StackName", stack);
if (templateBody != null) {
request.formParam("TemplateBody", templateBody);
}
request.when().post("/").then().statusCode(200);
}
private static String describeStacks(String stack, String expectedStatus) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().asString();
}
private static void awaitStackDeleted(String stack) throws InterruptedException {
for (int i = 0; i < 100; i++) {
String body = given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stack)
.when().post("/").then().extract().asString();
if (body.contains("does not exist")) {
return;
}
if (body.contains("<StackStatus>DELETE_FAILED</StackStatus>")) {
fail("Stack delete failed: " + body);
}
Thread.sleep(50);
}
fail("Stack " + stack + " was not deleted within the timeout");
}
private static void assertClusterNotFound(String clusterId) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", REDSHIFT_AUTH)
.formParam("Action", "DescribeClusters")
.formParam("ClusterIdentifier", clusterId)
.when().post("/").then()
.statusCode(404)
.body(containsString("<Code>ClusterNotFound</Code>"));
}
private static void assertParameterGroupExists(String pgName, String expectedFamily) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", REDSHIFT_AUTH)
.formParam("Action", "DescribeClusterParameterGroups")
.formParam("ParameterGroupName", pgName)
.when().post("/").then()
.statusCode(200)
.body(containsString("<ParameterGroupName>" + pgName + "</ParameterGroupName>"))
.body(containsString("<ParameterGroupFamily>" + expectedFamily + "</ParameterGroupFamily>"));
}
private static void assertParameterGroupNotFound(String pgName) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", REDSHIFT_AUTH)
.formParam("Action", "DescribeClusterParameterGroups")
.formParam("ParameterGroupName", pgName)
.when().post("/").then()
.statusCode(404)
.body(containsString("<Code>ClusterParameterGroupNotFound</Code>"));
}
private static void assertSubnetGroupExists(String sgName) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", REDSHIFT_AUTH)
.formParam("Action", "DescribeClusterSubnetGroups")
.formParam("ClusterSubnetGroupName", sgName)
.when().post("/").then()
.statusCode(200)
.body(containsString("<ClusterSubnetGroupName>" + sgName + "</ClusterSubnetGroupName>"));
}
private static void assertSubnetGroupNotFound(String sgName) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", REDSHIFT_AUTH)
.formParam("Action", "DescribeClusterSubnetGroups")
.formParam("ClusterSubnetGroupName", sgName)
.when().post("/").then()
.statusCode(404)
.body(containsString("<Code>ClusterSubnetGroupNotFound</Code>"));
}
private static String outputValue(String xml, String key) {
return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
}
}
@@ -0,0 +1,606 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.redshift.RedshiftService;
import io.github.hectorvent.floci.services.redshift.model.Cluster;
import io.github.hectorvent.floci.services.redshift.model.ClusterParameterGroup;
import io.github.hectorvent.floci.services.redshift.model.Endpoint;
import io.github.hectorvent.floci.services.redshift.model.Parameter;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
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.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
class RedshiftClusterCfnProvisionerTest {
private static final ObjectMapper MAPPER = new ObjectMapper();
private ProvisionContext ctx(String priorPhysicalId) {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode n = inv.getArgument(0);
return n == null || n.isNull() ? null : n.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.resolveStringList(any())).thenAnswer(inv -> {
JsonNode n = inv.getArgument(0);
List<String> out = new ArrayList<>();
if (n != null && n.isArray()) {
n.forEach(e -> out.add(e.asText()));
}
return out;
});
return new ProvisionContext(engine, "us-east-1", "000000000000", "test-stack", priorPhysicalId);
}
private Cluster availableCluster(String id) {
Cluster c = new Cluster();
c.setClusterIdentifier(id);
c.setEndpoint(new Endpoint("host-" + id, 5439));
return c;
}
private JsonNode json(String raw) {
try {
return MAPPER.readTree(raw);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Test
void resourceTypesCoversAllFour() {
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(mock(RedshiftService.class));
assertEquals(Set.of("AWS::Redshift::Cluster", "AWS::Redshift::ClusterParameterGroup",
"AWS::Redshift::ClusterSubnetGroup", "AWS::Redshift::ClusterSecurityGroup"),
p.resourceTypes());
}
@Test
void provisionThrowsOnUnknownResourceType() {
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(mock(RedshiftService.class));
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::UnknownType");
r.setLogicalId("Unknown");
assertThrows(IllegalStateException.class, () -> p.provision(r, json("{}"), ctx(null)));
}
@Test
void provisionParameterGroupMapsToService() {
RedshiftService service = mock(RedshiftService.class);
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
r.setLogicalId("Params");
p.provision(r, json("""
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-1.0","Description":"d"}"""), ctx(null));
verify(service).createClusterParameterGroup("pg1", "redshift-1.0", "d");
assertEquals("pg1", r.getPhysicalId());
}
@Test
void provisionParameterGroupWithGeneratedNameAndTags() {
RedshiftService service = mock(RedshiftService.class);
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
r.setLogicalId("Params");
p.provision(r, json("""
{"ParameterGroupFamily":"redshift-1.0","Description":"d",
"Tags":[{"Key":"env","Value":"test"}]}"""), ctx(null));
assertNotNull(r.getPhysicalId());
verify(service).createClusterParameterGroup(eq(r.getPhysicalId()), eq("redshift-1.0"), eq("d"));
verify(service).createTags(r.getPhysicalId(), Map.of("env", "test"));
}
@Test
void provisionParameterGroupReusesPriorEntityWithoutCallingCreate() {
RedshiftService service = mock(RedshiftService.class);
ClusterParameterGroup existing = new ClusterParameterGroup("pg1", "redshift-1.0", "d");
when(service.getClusterParameterGroup("pg1")).thenReturn(Optional.of(existing));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
r.setLogicalId("Params");
p.provision(r, json("""
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-1.0","Description":"d",
"Parameters":[{"ParameterName":"wlm_json_configuration","ParameterValue":"[]"}]}"""), ctx("pg1"));
verify(service, never()).createClusterParameterGroup(anyString(), anyString(), anyString());
assertEquals("pg1", r.getPhysicalId());
ArgumentCaptor<List<Parameter>> captor = ArgumentCaptor.forClass(List.class);
verify(service).modifyClusterParameterGroup(eq("pg1"), captor.capture());
assertEquals(1, captor.getValue().size());
assertEquals("wlm_json_configuration", captor.getValue().get(0).getParameterName());
assertEquals("[]", captor.getValue().get(0).getParameterValue());
}
@Test
void provisionParameterGroupAppliesParametersOnCreate() {
RedshiftService service = mock(RedshiftService.class);
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
r.setLogicalId("Params");
p.provision(r, json("""
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-1.0","Description":"d",
"Parameters":[{"ParameterName":"enable_user_activity_logging","ParameterValue":"true"}]}"""), ctx(null));
verify(service).createClusterParameterGroup("pg1", "redshift-1.0", "d");
ArgumentCaptor<List<Parameter>> captor = ArgumentCaptor.forClass(List.class);
verify(service).modifyClusterParameterGroup(eq("pg1"), captor.capture());
assertEquals(1, captor.getValue().size());
assertEquals("enable_user_activity_logging", captor.getValue().get(0).getParameterName());
assertEquals("true", captor.getValue().get(0).getParameterValue());
}
@Test
void changingParameterGroupDescriptionTriggersReplacement() {
RedshiftService service = mock(RedshiftService.class);
ClusterParameterGroup existing = new ClusterParameterGroup("pg1", "redshift-1.0", "old description");
when(service.getClusterParameterGroup("pg1")).thenReturn(Optional.of(existing));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
r.setLogicalId("Params");
r.setPhysicalId("pg1");
p.provision(r, json("""
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-1.0","Description":"new description"}"""),
ctx("pg1"));
assertNotEquals("pg1", r.getPhysicalId());
assertEquals("pg1", p.updateCleanupPhysicalId(r));
assertTrue(p.hasReplacementUpdate(r));
verify(service).createClusterParameterGroup(eq(r.getPhysicalId()), eq("redshift-1.0"), eq("new description"));
}
@Test
void changingParameterGroupFamilyTriggersReplacement() {
RedshiftService service = mock(RedshiftService.class);
ClusterParameterGroup existing = new ClusterParameterGroup("pg1", "redshift-1.0", "d");
when(service.getClusterParameterGroup("pg1")).thenReturn(Optional.of(existing));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::ClusterParameterGroup");
r.setLogicalId("Params");
r.setPhysicalId("pg1");
p.provision(r, json("""
{"ParameterGroupName":"pg1","ParameterGroupFamily":"redshift-2.0","Description":"d"}"""), ctx("pg1"));
assertNotEquals("pg1", r.getPhysicalId());
assertEquals("pg1", p.updateCleanupPhysicalId(r));
assertTrue(p.hasReplacementUpdate(r));
}
@Test
void deleteParameterGroupToleratesNotFound() {
RedshiftService service = mock(RedshiftService.class);
doThrow(new AwsException("ClusterParameterGroupNotFound", "gone", 404))
.when(service).deleteClusterParameterGroup("pg1");
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterParameterGroup", "pg1", "us-east-1"));
}
@Test
void deleteParameterGroupAndSubnetGroupTolerateFaultSuffix() {
RedshiftService service = mock(RedshiftService.class);
doThrow(new AwsException("ClusterParameterGroupNotFoundFault", "gone", 404))
.when(service).deleteClusterParameterGroup("pg1");
doThrow(new AwsException("ClusterSubnetGroupNotFoundFault", "gone", 404))
.when(service).deleteClusterSubnetGroup("sg1");
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterParameterGroup", "pg1", "us-east-1"));
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterSubnetGroup", "sg1", "us-east-1"));
}
@Test
void deleteParameterGroupPropagatesUnexpectedError() {
RedshiftService service = mock(RedshiftService.class);
doThrow(new AwsException("InternalFailure", "boom", 500))
.when(service).deleteClusterParameterGroup("pg1");
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
assertThrows(AwsException.class,
() -> p.delete("AWS::Redshift::ClusterParameterGroup", "pg1", "us-east-1"));
}
@Test
void provisionSubnetGroupMapsToServiceAndReconcilesOnUpdate() {
RedshiftService service = mock(RedshiftService.class);
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::ClusterSubnetGroup");
r.setLogicalId("Subnets");
p.provision(r, json("""
{"ClusterSubnetGroupName":"sg1","Description":"d","SubnetIds":["subnet-a","subnet-b"]}"""), ctx(null));
verify(service).createClusterSubnetGroup("sg1", "d", null, List.of("subnet-a", "subnet-b"));
assertEquals("sg1", r.getPhysicalId());
assertEquals("sg1", r.getAttributes().get("ClusterSubnetGroupName"));
p.provision(r, json("""
{"ClusterSubnetGroupName":"sg1","Description":"d2","SubnetIds":["subnet-a"]}"""), ctx("sg1"));
verify(service).modifyClusterSubnetGroup("sg1", "d2", List.of("subnet-a"));
assertEquals("sg1", r.getPhysicalId());
}
@Test
void provisionSubnetGroupWithGeneratedName() {
RedshiftService service = mock(RedshiftService.class);
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::ClusterSubnetGroup");
r.setLogicalId("Subnets");
p.provision(r, json("""
{"Description":"d","SubnetIds":["subnet-1"]}"""), ctx(null));
assertNotNull(r.getPhysicalId());
assertEquals(r.getPhysicalId(), r.getAttributes().get("ClusterSubnetGroupName"));
verify(service).createClusterSubnetGroup(eq(r.getPhysicalId()), eq("d"), isNull(), eq(List.of("subnet-1")));
}
@Test
void deleteSubnetGroupToleratesNotFound() {
RedshiftService service = mock(RedshiftService.class);
doThrow(new AwsException("ClusterSubnetGroupNotFound", "gone", 404))
.when(service).deleteClusterSubnetGroup("sg1");
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterSubnetGroup", "sg1", "us-east-1"));
}
@Test
void deleteSubnetGroupPropagatesUnexpectedError() {
RedshiftService service = mock(RedshiftService.class);
doThrow(new AwsException("InternalFailure", "boom", 500))
.when(service).deleteClusterSubnetGroup("sg1");
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
assertThrows(AwsException.class,
() -> p.delete("AWS::Redshift::ClusterSubnetGroup", "sg1", "us-east-1"));
}
@Test
void provisionSecurityGroupIsAcceptOnly() {
RedshiftService service = mock(RedshiftService.class);
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::ClusterSecurityGroup");
r.setLogicalId("SecGroup");
p.provision(r, json("""
{"Description":"sg desc"}"""), ctx(null));
assertNotNull(r.getPhysicalId());
assertEquals(r.getPhysicalId(), r.getAttributes().get("Id"));
verifyNoInteractions(service);
assertDoesNotThrow(() -> p.delete("AWS::Redshift::ClusterSecurityGroup", r.getPhysicalId(), "us-east-1"));
}
@Test
void provisionCreatesClusterAndSetsRefAndEndpointAttributes() {
RedshiftService service = mock(RedshiftService.class);
when(service.createCluster(eq("my-cluster"), eq("ra3.large"), eq("admin"), eq("Secret123"),
isNull(), anyList())).thenReturn(availableCluster("my-cluster"));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("Warehouse");
JsonNode props = json("""
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large",
"MasterUsername":"admin","MasterUserPassword":"Secret123",
"ClusterType":"single-node","DBName":"dev"}""");
p.provision(r, props, ctx(null));
assertEquals("my-cluster", r.getPhysicalId());
assertEquals("host-my-cluster", r.getAttributes().get("Endpoint.Address"));
assertEquals("5439", r.getAttributes().get("Endpoint.Port"));
assertFalse(r.getAttributes().containsKey("Id"));
assertTrue(r.getAttributes().get("ClusterNamespaceArn")
.startsWith("arn:aws:redshift:us-east-1:000000000000:namespace:"));
}
@Test
void provisionGeneratesLowercaseIdentifierWhenAbsent() {
RedshiftService service = mock(RedshiftService.class);
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList()))
.thenAnswer(inv -> availableCluster(inv.getArgument(0)));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("MyWarehouse");
p.provision(r, json("""
{"NodeType":"ra3.large","MasterUsername":"admin","MasterUserPassword":"Secret123"}"""),
ctx(null));
assertEquals(r.getPhysicalId().toLowerCase(), r.getPhysicalId());
assertTrue(r.getPhysicalId().length() <= 63);
}
@Test
void provisionRejectsManageMasterPassword() {
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(mock(RedshiftService.class));
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
AwsException ex = assertThrows(AwsException.class, () -> p.provision(r, json("""
{"NodeType":"ra3.large","MasterUsername":"admin","ManageMasterPassword":true}"""), ctx(null)));
assertEquals("ValidationException", ex.getErrorCode());
}
@Test
void provisionRejectsMissingMasterPassword() {
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(mock(RedshiftService.class));
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
AwsException ex = assertThrows(AwsException.class, () -> p.provision(r, json("""
{"NodeType":"ra3.large","MasterUsername":"admin"}"""), ctx(null)));
assertEquals("ValidationException", ex.getErrorCode());
}
@Test
void provisionAppliesTags() {
RedshiftService service = mock(RedshiftService.class);
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList()))
.thenReturn(availableCluster("my-cluster"));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
p.provision(r, json("""
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large","MasterUsername":"admin",
"MasterUserPassword":"Secret123","Tags":[{"Key":"env","Value":"dev"}]}"""), ctx(null));
verify(service).createTags("my-cluster", Map.of("env", "dev"));
}
@Test
void deleteCallsDeleteClusterAndToleratesNotFound() {
RedshiftService service = mock(RedshiftService.class);
doThrow(new AwsException("ClusterNotFound", "gone", 404)).when(service).deleteCluster("my-cluster");
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
assertDoesNotThrow(() -> p.delete("AWS::Redshift::Cluster", "my-cluster", "us-east-1"));
}
@Test
void deletePropagatesUnexpectedError() {
RedshiftService service = mock(RedshiftService.class);
doThrow(new AwsException("InternalFailure", "boom", 500)).when(service).deleteCluster("my-cluster");
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
assertThrows(AwsException.class,
() -> p.delete("AWS::Redshift::Cluster", "my-cluster", "us-east-1"));
}
@Test
void updateInPlaceCallsModifyCluster() {
RedshiftService service = mock(RedshiftService.class);
when(service.modifyCluster(eq("my-cluster"), eq("ra3.4xlarge"), isNull(), eq("NewSecret9"),
isNull(), anyList())).thenReturn(availableCluster("my-cluster"));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
p.provision(r, json("""
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.4xlarge","MasterUsername":"admin",
"MasterUserPassword":"NewSecret9"}"""), ctx("my-cluster"));
verify(service).modifyCluster(eq("my-cluster"), eq("ra3.4xlarge"), isNull(), eq("NewSecret9"),
isNull(), anyList());
verify(service, never()).createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList());
}
@Test
void replacementCreatesNewClusterAndReportsOldIdForCleanup() {
RedshiftService service = mock(RedshiftService.class);
when(service.createCluster(eq("new-name"), anyString(), anyString(), anyString(), any(), anyList()))
.thenReturn(availableCluster("new-name"));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
// prior id "old-name" differs from the template's new ClusterIdentifier "new-name"
p.provision(r, json("""
{"ClusterIdentifier":"new-name","NodeType":"ra3.large","MasterUsername":"admin",
"MasterUserPassword":"Secret123"}"""), ctx("old-name"));
assertEquals("new-name", r.getPhysicalId());
assertEquals("old-name", p.updateCleanupPhysicalId(r));
assertTrue(p.hasReplacementUpdate(r));
when(service.deleteCluster("old-name")).thenReturn(null);
UpdateCleanupResult result = p.completeUpdate(r);
verify(service).deleteCluster("old-name");
assertEquals(new UpdateCleanupResult(true, true, "old-name", 0, null), result);
}
@Test
void replacementCleanupToleratesAlreadyDeletedOldCluster() {
RedshiftService service = mock(RedshiftService.class);
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList()))
.thenReturn(availableCluster("new-name"));
doThrow(new AwsException("ClusterNotFound", "gone", 404)).when(service).deleteCluster("old-name");
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
p.provision(r, json("""
{"ClusterIdentifier":"new-name","NodeType":"ra3.large","MasterUsername":"admin",
"MasterUserPassword":"Secret123"}"""), ctx("old-name"));
assertDoesNotThrow(() -> p.completeUpdate(r));
}
@Test
void clearUpdateDropsCleanupRecord() {
RedshiftService service = mock(RedshiftService.class);
when(service.createCluster(eq("new-name"), anyString(), anyString(), anyString(), any(), anyList()))
.thenReturn(availableCluster("new-name"));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
p.provision(r, json("""
{"ClusterIdentifier":"new-name","NodeType":"ra3.large","MasterUsername":"admin",
"MasterUserPassword":"Secret123"}"""), ctx("old-name"));
assertTrue(p.hasReplacementUpdate(r));
p.completeUpdate(r);
p.clearUpdate(r);
assertFalse(p.hasReplacementUpdate(r));
assertNull(p.updateCleanupPhysicalId(r));
}
@Test
void rollbackUpdateRestoresPriorPhysicalIdAndDeletesReplacement() {
RedshiftService service = mock(RedshiftService.class);
when(service.createCluster(eq("new-name"), anyString(), anyString(), anyString(), any(), anyList()))
.thenReturn(availableCluster("new-name"));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
r.setPhysicalId("old-name");
r.getAttributes().put("Id", "old-name");
p.provision(r, json("""
{"ClusterIdentifier":"new-name","NodeType":"ra3.large","MasterUsername":"admin",
"MasterUserPassword":"Secret123"}"""), ctx("old-name"));
assertEquals("new-name", r.getPhysicalId());
assertTrue(p.rollbackUpdate(r));
assertEquals("old-name", r.getPhysicalId());
verify(service).deleteCluster("new-name");
}
@Test
void changingMasterUsernameTriggersReplacement() {
RedshiftService service = mock(RedshiftService.class);
Cluster existing = availableCluster("my-cluster");
existing.setMasterUsername("admin");
when(service.describeClusters("my-cluster")).thenReturn(List.of(existing));
when(service.createCluster(anyString(), anyString(), eq("newadmin"), anyString(), any(), anyList()))
.thenAnswer(inv -> availableCluster(inv.getArgument(0)));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
p.provision(r, json("""
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large","MasterUsername":"newadmin",
"MasterUserPassword":"Secret123"}"""), ctx("my-cluster"));
assertNotEquals("my-cluster", r.getPhysicalId());
assertTrue(r.getPhysicalId().startsWith("my-cluster-"));
assertEquals("my-cluster", p.updateCleanupPhysicalId(r));
assertTrue(p.hasReplacementUpdate(r));
when(service.deleteCluster("my-cluster")).thenReturn(null);
UpdateCleanupResult result = p.completeUpdate(r);
verify(service).deleteCluster("my-cluster");
assertEquals(new UpdateCleanupResult(true, true, "my-cluster", 0, null), result);
}
@Test
void changingClusterSubnetGroupTriggersReplacement() {
RedshiftService service = mock(RedshiftService.class);
Cluster existing = availableCluster("my-cluster");
existing.setMasterUsername("admin");
existing.setClusterSubnetGroupName("subnet-group-1");
when(service.describeClusters("my-cluster")).thenReturn(List.of(existing));
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), eq("subnet-group-2"), anyList()))
.thenAnswer(inv -> availableCluster(inv.getArgument(0)));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
p.provision(r, json("""
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large","MasterUsername":"admin",
"MasterUserPassword":"Secret123","ClusterSubnetGroupName":"subnet-group-2"}"""), ctx("my-cluster"));
assertNotEquals("my-cluster", r.getPhysicalId());
assertEquals("my-cluster", p.updateCleanupPhysicalId(r));
assertTrue(p.hasReplacementUpdate(r));
}
@Test
void changingDBNameTriggersReplacement() {
RedshiftService service = mock(RedshiftService.class);
Cluster existing = availableCluster("my-cluster");
existing.setMasterUsername("admin");
when(service.describeClusters("my-cluster")).thenReturn(List.of(existing));
when(service.createCluster(anyString(), anyString(), anyString(), anyString(), any(), anyList()))
.thenAnswer(inv -> availableCluster(inv.getArgument(0)));
RedshiftClusterCfnProvisioner p = new RedshiftClusterCfnProvisioner(service);
StackResource r = new StackResource();
r.setResourceType("AWS::Redshift::Cluster");
r.setLogicalId("W");
r.setPhysicalId("my-cluster");
r.getAttributes().put("Floci::DBName", "dev");
p.provision(r, json("""
{"ClusterIdentifier":"my-cluster","NodeType":"ra3.large","MasterUsername":"admin",
"MasterUserPassword":"Secret123","DBName":"analytics"}"""), ctx("my-cluster"));
assertNotEquals("my-cluster", r.getPhysicalId());
assertEquals("my-cluster", p.updateCleanupPhysicalId(r));
assertTrue(p.hasReplacementUpdate(r));
assertEquals("analytics", r.getAttributes().get("Floci::DBName"));
}
}