fix(cloudformation): keep Route 53 routing policies and provision health checks (#6191)

A Route 53 RecordSet resource now writes Region, Failover, Weight and
HealthCheckId into the record, as ChangeResourceRecordSets stores them.

A HealthCheck resource creates a health check with its tags, and its Ref
and HealthCheckId attribute return the check's id. An unknown Type is
refused before any check is created. Changing Type, RequestInterval or
MeasureLatency replaces the check, and the old one is deleted once the
update commits, or kept under UpdateReplacePolicy: Retain. Any other
change updates the check in place, and a failed stack update puts back
its earlier settings and tags.
This commit is contained in:
lex00 authored and GitHub committed 2026-10-21 23:09:42 -04:00
1 parent f757d29aa0
commit 5beb8d47b9
7 files changed
+876 -4

No files matched your search

@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.CfnStackWaits;
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.response.Response;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
@@ -12,6 +13,7 @@ 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.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
/**
@@ -262,6 +264,241 @@ class CloudFormationRoute53RecordSetIntegrationTest {
.when().post("/").then().statusCode(200);
}
@Test
void latencyRecordsKeepTheirRoutingPolicyAndHealthCheck() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "r53-routing-" + suffix;
String zoneName = suffix + ".cfn-routing-it.example.test";
String template = """
{
"Resources": {
"Zone": {
"Type": "AWS::Route53::HostedZone",
"Properties": {"Name": "%1$s"}
},
"Check": {
"Type": "AWS::Route53::HealthCheck",
"Properties": {
"HealthCheckConfig": {"Type": "HTTPS", "FullyQualifiedDomainName": "app.example.net",
"ResourcePath": "/", "RequestInterval": 10, "FailureThreshold": 2},
"HealthCheckTags": [{"Key": "cloud", "Value": "aws"}]
}
},
"Latency": {
"Type": "AWS::Route53::RecordSet",
"Properties": {
"HostedZoneId": {"Ref": "Zone"},
"Name": "www.%1$s.",
"Type": "CNAME",
"TTL": "60",
"SetIdentifier": "aws",
"Region": "us-east-1",
"HealthCheckId": {"Ref": "Check"},
"ResourceRecords": ["app.example.net"]
}
},
"Weighted": {
"Type": "AWS::Route53::RecordSet",
"Properties": {
"HostedZoneId": {"Ref": "Zone"},
"Name": "api.%1$s.",
"Type": "A",
"TTL": "60",
"SetIdentifier": "blue",
"Weight": 70,
"ResourceRecords": ["10.0.0.7"]
}
},
"Primary": {
"Type": "AWS::Route53::RecordSet",
"Properties": {
"HostedZoneId": {"Ref": "Zone"},
"Name": "db.%1$s.",
"Type": "A",
"TTL": "60",
"SetIdentifier": "primary",
"Failover": "PRIMARY",
"HealthCheckId": {"Fn::GetAtt": ["Check", "HealthCheckId"]},
"ResourceRecords": ["10.0.0.8"]
}
},
"CheckRef": {
"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "/r53-routing/%2$s/ref", "Type": "String", "Value": {"Ref": "Check"}}
},
"CheckAttr": {
"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "/r53-routing/%2$s/attr", "Type": "String",
"Value": {"Fn::GetAtt": ["Check", "HealthCheckId"]}}
},
"ZoneParam": {
"Type": "AWS::SSM::Parameter",
"Properties": {"Name": "/r53-routing/%2$s/zone", "Type": "String", "Value": {"Ref": "Zone"}}
}
}
}
""".formatted(zoneName, suffix);
createStack(stackName, template);
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String checkId = parameterValue("/r53-routing/" + suffix + "/ref");
try {
assertEquals(checkId, parameterValue("/r53-routing/" + suffix + "/attr"));
assertFalse(checkId.startsWith("arn:aws:stub"), "health check was stubbed: " + checkId);
String check = given()
.header("Authorization", ROUTE53_AUTH)
.when().get("/2013-04-01/healthcheck/" + checkId)
.then().statusCode(200)
.extract().asString();
assertTrue(check.contains("<Type>HTTPS</Type>"), check);
assertTrue(check.contains("<FullyQualifiedDomainName>app.example.net</FullyQualifiedDomainName>"), check);
assertTrue(check.contains("<RequestInterval>10</RequestInterval>"), check);
assertTrue(check.contains("<FailureThreshold>2</FailureThreshold>"), check);
String tags = given()
.header("Authorization", ROUTE53_AUTH)
.when().get("/2013-04-01/tags/healthcheck/" + checkId)
.then().statusCode(200)
.extract().asString();
assertTrue(tags.contains("<Key>cloud</Key>") && tags.contains("<Value>aws</Value>"), tags);
String records = listResourceRecordSets(parameterValue("/r53-routing/" + suffix + "/zone"));
assertTrue(records.contains("<SetIdentifier>aws</SetIdentifier><Region>us-east-1</Region>"), records);
assertTrue(records.contains("<SetIdentifier>blue</SetIdentifier><Weight>70</Weight>"), records);
assertTrue(records.contains("<SetIdentifier>primary</SetIdentifier><Failover>PRIMARY</Failover>"), records);
assertEquals(2, records.split("<HealthCheckId>" + checkId + "</HealthCheckId>", -1).length - 1, records);
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
given()
.header("Authorization", ROUTE53_AUTH)
.when().get("/2013-04-01/healthcheck/" + checkId)
.then().statusCode(404);
}
@Test
void requestIntervalChangeReplacesTheCheckAndDeletesTheOldOneOnceTheUpdateCommits() {
String stackName = "r53-hc-replace-" + Long.toString(System.nanoTime(), 36);
createStack(stackName, healthCheckTemplate(30, false, false));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String oldId = physicalId(stackName, "Check");
try {
updateStack(stackName, healthCheckTemplate(10, false, false));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String newId = physicalId(stackName, "Check");
assertNotEquals(oldId, newId);
assertTrue(healthCheck(newId).contains("<RequestInterval>10</RequestInterval>"));
healthCheckRequest(oldId).then().statusCode(404);
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
}
@Test
void retainedCheckOutlivesItsReplacement() {
String stackName = "r53-hc-retain-" + Long.toString(System.nanoTime(), 36);
createStack(stackName, healthCheckTemplate(30, true, false));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String oldId = physicalId(stackName, "Check");
try {
updateStack(stackName, healthCheckTemplate(10, true, false));
assertEquals("UPDATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertNotEquals(oldId, physicalId(stackName, "Check"));
assertTrue(healthCheck(oldId).contains("<RequestInterval>30</RequestInterval>"));
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
given().header("Authorization", ROUTE53_AUTH)
.when().delete("/2013-04-01/healthcheck/" + oldId);
}
}
@Test
void failedUpdateRollsBackToTheOldCheck() {
String stackName = "r53-hc-rollback-" + Long.toString(System.nanoTime(), 36);
createStack(stackName, healthCheckTemplate(30, false, false));
assertEquals("CREATE_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
String oldId = physicalId(stackName, "Check");
try {
updateStack(stackName, healthCheckTemplate(10, false, true));
assertEquals("UPDATE_ROLLBACK_COMPLETE", CfnStackWaits.awaitTerminal(stackName).status());
assertEquals(oldId, physicalId(stackName, "Check"));
assertTrue(healthCheck(oldId).contains("<RequestInterval>30</RequestInterval>"));
String checks = given().header("Authorization", ROUTE53_AUTH)
.when().get("/2013-04-01/healthcheck")
.then().statusCode(200)
.extract().asString();
assertEquals(1, checks.split("<CallerReference>" + stackName + "/Check/", -1).length - 1, checks);
} finally {
deleteStack(stackName);
CfnStackWaits.awaitStackDeleted(stackName);
}
}
/**
* One TCP health check; {@code failing} adds a record set in a zone that does not exist, created
* after the check, so the update fails once the check has been replaced.
*/
private static String healthCheckTemplate(int requestInterval, boolean retain, boolean failing) {
String policy = retain ? ", \"UpdateReplacePolicy\": \"Retain\"" : "";
String broken = !failing ? "" : """
,
"Broken": {
"Type": "AWS::Route53::RecordSet",
"DependsOn": "Check",
"Properties": {"HostedZoneId": "ZNOSUCHZONE00", "Name": "x.example.test.", "Type": "A",
"TTL": "60", "ResourceRecords": ["10.0.0.1"]}
}""";
return """
{
"Resources": {
"Check": {
"Type": "AWS::Route53::HealthCheck"%s,
"Properties": {
"HealthCheckConfig": {"Type": "TCP", "IPAddress": "10.0.0.5", "Port": 22,
"RequestInterval": %d}
}
}%s
}
}
""".formatted(policy, requestInterval, broken);
}
private void updateStack(String stackName, String template) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "UpdateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when().post("/").then().statusCode(200);
}
private String physicalId(String stackName, String logicalId) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStackResource")
.formParam("StackName", stackName)
.formParam("LogicalResourceId", logicalId)
.when().post("/").then().statusCode(200)
.extract().xmlPath().getString("**.find { it.name() == 'PhysicalResourceId' }");
}
private Response healthCheckRequest(String id) {
return given().header("Authorization", ROUTE53_AUTH)
.when().get("/2013-04-01/healthcheck/" + id);
}
private String healthCheck(String id) {
return healthCheckRequest(id).then().statusCode(200).extract().asString();
}
private String listResourceRecordSets(String zoneId) {
return given()
.header("Authorization", ROUTE53_AUTH)
@@ -6,6 +6,8 @@ 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.route53.Route53Service;
import io.github.hectorvent.floci.services.route53.model.HealthCheck;
import io.github.hectorvent.floci.services.route53.model.HealthCheckConfig;
import io.github.hectorvent.floci.services.route53.model.HostedZone;
import io.github.hectorvent.floci.services.route53.model.ResourceRecord;
import io.github.hectorvent.floci.services.route53.model.ResourceRecordSet;
@@ -14,11 +16,13 @@ import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
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.assertNull;
import static org.junit.jupiter.api.Assertions.assertSame;
@@ -700,6 +704,335 @@ class Route53CfnProvisionerTest {
verifyNoInteractions(service);
}
@Test
void recordSetCarriesItsRoutingPolicy() {
Route53Service service = mock(Route53Service.class);
JsonNode props = new ObjectMapper().createObjectNode()
.put("HostedZoneId", "Z1")
.put("Name", "www.example.test.")
.put("Type", "CNAME")
.put("TTL", "60")
.put("SetIdentifier", "aws")
.put("Region", "us-east-1")
.put("Failover", "PRIMARY")
.put("Weight", "10")
.put("HealthCheckId", "hc-1");
StackResource resource = new StackResource();
resource.setLogicalId("Record");
resource.setResourceType("AWS::Route53::RecordSet");
new Route53CfnProvisioner(service).provision(resource, props,
new ProvisionContext(recordEngine(), "us-east-1", "000000000000", "dns-stack"));
@SuppressWarnings("unchecked")
ArgumentCaptor<List<Map<String, Object>>> captor = ArgumentCaptor.forClass(List.class);
verify(service).changeResourceRecordSets(eq("Z1"), captor.capture(), any());
ResourceRecordSet rrs = (ResourceRecordSet) captor.getValue().get(0).get("rrs");
assertEquals("us-east-1", rrs.getRegion());
assertEquals("PRIMARY", rrs.getFailover());
assertEquals(Long.valueOf(10), rrs.getWeight());
assertEquals("hc-1", rrs.getHealthCheckId());
}
@Test
void recordSetWithANonNumericWeightIsRejected() {
assertRecordSetRejected("{\"HostedZoneId\":\"Z1\",\"Name\":\"a.example.com\",\"Type\":\"A\","
+ "\"SetIdentifier\":\"a\",\"Weight\":\"heavy\"}");
}
@Test
void healthCheckIsCreatedWithItsConfigTagsAndExactAttributes() throws Exception {
Route53Service service = mock(Route53Service.class);
when(service.createHealthCheck(any(), any(), any()))
.thenAnswer(inv -> new HealthCheck("hc-1", inv.getArgument(0), inv.getArgument(1), inv.getArgument(2)));
JsonNode props = new ObjectMapper().readTree("""
{"HealthCheckConfig": {"Type": "HTTPS", "FullyQualifiedDomainName": "app.example.net",
"ResourcePath": "/", "Port": 443, "RequestInterval": 10, "FailureThreshold": 2},
"HealthCheckTags": [{"Key": "team", "Value": "web"}]}""");
StackResource resource = new StackResource();
resource.setLogicalId("Check");
resource.setResourceType("AWS::Route53::HealthCheck");
new Route53CfnProvisioner(service).provision(resource, props, healthCheckContext(null));
assertEquals("hc-1", resource.getPhysicalId());
assertEquals(Set.of("HealthCheckId"), publicAttributes(resource));
assertEquals("hc-1", resource.getAttributes().get("HealthCheckId"));
ArgumentCaptor<HealthCheckConfig> config = ArgumentCaptor.forClass(HealthCheckConfig.class);
verify(service).createHealthCheck(argThat(ref -> ref.startsWith("dns-stack/Check/")), config.capture(), any());
assertEquals("HTTPS", config.getValue().getType());
assertEquals("app.example.net", config.getValue().getFullyQualifiedDomainName());
assertEquals("/", config.getValue().getResourcePath());
assertEquals(Integer.valueOf(443), config.getValue().getPort());
assertEquals(Integer.valueOf(10), config.getValue().getRequestInterval());
assertEquals(Integer.valueOf(2), config.getValue().getFailureThreshold());
verify(service).changeTagsForResource("healthcheck", "hc-1",
List.of(Map.of("Key", "team", "Value", "web")), List.of());
}
@Test
void healthCheckUpdateKeepsTheCheckAndDropsRemovedTags() throws Exception {
Route53Service service = mock(Route53Service.class);
HealthCheckConfig priorConfig = new HealthCheckConfig();
priorConfig.setType("HTTP");
HealthCheck prior = new HealthCheck("hc-1", "ref", priorConfig, "");
when(service.getHealthCheck("hc-1")).thenReturn(prior);
when(service.updateHealthCheck(eq("hc-1"), any())).thenReturn(prior);
when(service.listTagsForResource("healthcheck", "hc-1")).thenReturn(Map.of("old", "x"));
JsonNode props = new ObjectMapper().readTree("""
{"HealthCheckConfig": {"Type": "HTTP", "IPAddress": "10.0.0.5", "Port": 8080}}""");
StackResource resource = new StackResource();
resource.setLogicalId("Check");
resource.setResourceType("AWS::Route53::HealthCheck");
resource.setPhysicalId("hc-1");
new Route53CfnProvisioner(service).provision(resource, props, healthCheckContext("hc-1"));
assertEquals("hc-1", resource.getPhysicalId());
verify(service, never()).createHealthCheck(any(), any(), any());
verify(service).updateHealthCheck(eq("hc-1"), argThat(cfg -> "10.0.0.5".equals(cfg.getIpAddress())
&& Integer.valueOf(8080).equals(cfg.getPort())));
verify(service).changeTagsForResource("healthcheck", "hc-1", List.of(), List.of("old"));
}
@Test
void healthCheckTypeChangeReplacesTheCheckAndDeletesTheOldOneOnlyOnceTheUpdateCommits() throws Exception {
Route53Service service = replacingService();
StackResource resource = existingCheck();
new Route53CfnProvisioner(service).provision(resource, healthCheckProps("TCP", null), healthCheckContext("hc-1"));
assertEquals("hc-2", resource.getPhysicalId());
assertEquals("hc-2", resource.getAttributes().get("HealthCheckId"));
verify(service, never()).updateHealthCheck(any(), any());
verify(service, never()).deleteHealthCheck(any());
Route53CfnProvisioner provisioner = new Route53CfnProvisioner(service);
assertTrue(provisioner.hasReplacementUpdate(resource));
assertEquals("hc-1", provisioner.updateCleanupPhysicalId(resource));
assertTrue(provisioner.completeUpdate(resource).complete());
verify(service).deleteHealthCheck("hc-1");
}
@Test
void healthCheckRequestIntervalChangeReplacesTheCheck() throws Exception {
Route53Service service = replacingService();
StackResource resource = existingCheck();
new Route53CfnProvisioner(service).provision(resource, healthCheckProps("HTTP", 10), healthCheckContext("hc-1"));
assertEquals("hc-2", resource.getPhysicalId());
verify(service, never()).updateHealthCheck(any(), any());
}
@Test
void healthCheckMeasureLatencyChangeReplacesTheCheck() throws Exception {
Route53Service service = replacingService();
StackResource resource = existingCheck();
new Route53CfnProvisioner(service).provision(resource, healthCheckProps("HTTP", null), healthCheckContext("hc-1"));
assertEquals("hc-1", resource.getPhysicalId());
JsonNode props = new ObjectMapper().readTree("""
{"HealthCheckConfig": {"Type": "HTTP", "IPAddress": "10.0.0.5", "Port": 80, "MeasureLatency": true}}""");
new Route53CfnProvisioner(service).provision(resource, props, healthCheckContext("hc-1"));
assertEquals("hc-2", resource.getPhysicalId());
}
@Test
void retainedHealthCheckIsKeptWhenAReplacementCommits() throws Exception {
Route53Service service = replacingService();
StackResource resource = existingCheck();
resource.setUpdateReplacePolicy("Retain");
Route53CfnProvisioner provisioner = new Route53CfnProvisioner(service);
provisioner.provision(resource, healthCheckProps("TCP", null), healthCheckContext("hc-1"));
assertNull(provisioner.updateCleanupPhysicalId(resource));
provisioner.completeUpdate(resource);
verify(service, never()).deleteHealthCheck("hc-1");
}
@Test
void rollingBackAReplacementDeletesTheNewCheckAndPointsBackAtTheOldOne() throws Exception {
Route53Service service = replacingService();
StackResource resource = existingCheck();
Route53CfnProvisioner provisioner = new Route53CfnProvisioner(service);
provisioner.provision(resource, healthCheckProps("TCP", null), healthCheckContext("hc-1"));
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals("hc-1", resource.getPhysicalId());
assertEquals("hc-1", resource.getAttributes().get("HealthCheckId"));
verify(service).deleteHealthCheck("hc-2");
verify(service, never()).deleteHealthCheck("hc-1");
}
@Test
void rollingBackAnInPlaceUpdatePutsBackTheConfigAndTags() throws Exception {
Route53Service service = mock(Route53Service.class);
HealthCheckConfig priorConfig = new HealthCheckConfig();
priorConfig.setType("HTTP");
priorConfig.setIpAddress("10.0.0.5");
priorConfig.setPort(80);
HealthCheck prior = new HealthCheck("hc-1", "ref", priorConfig, "");
when(service.getHealthCheck("hc-1")).thenReturn(prior);
when(service.updateHealthCheck(eq("hc-1"), any())).thenReturn(prior);
when(service.listTagsForResource("healthcheck", "hc-1")).thenReturn(Map.of("team", "web"));
StackResource resource = existingCheck();
Route53CfnProvisioner provisioner = new Route53CfnProvisioner(service);
JsonNode props = new ObjectMapper().readTree("""
{"HealthCheckConfig": {"Type": "HTTP", "IPAddress": "10.0.0.9", "Port": 8080}}""");
provisioner.provision(resource, props, healthCheckContext("hc-1"));
when(service.listTagsForResource("healthcheck", "hc-1")).thenReturn(Map.of());
assertTrue(provisioner.rollbackUpdate(resource));
verify(service).updateHealthCheck(eq("hc-1"), argThat(cfg -> "10.0.0.5".equals(cfg.getIpAddress())
&& Integer.valueOf(80).equals(cfg.getPort())));
verify(service).changeTagsForResource("healthcheck", "hc-1",
List.of(Map.of("Key", "team", "Value", "web")), List.of());
assertFalse(resource.getAttributes().containsKey(CfnRollback.HEALTH_CHECK_UPDATE_SNAPSHOT_ATTR));
}
@Test
void anInPlaceUpdateThatFailsPartWayPutsTheCheckBack() throws Exception {
Route53Service service = mock(Route53Service.class);
HealthCheckConfig priorConfig = new HealthCheckConfig();
priorConfig.setType("HTTP");
priorConfig.setIpAddress("10.0.0.5");
HealthCheck prior = new HealthCheck("hc-1", "ref", priorConfig, "");
when(service.getHealthCheck("hc-1")).thenReturn(prior);
when(service.updateHealthCheck(eq("hc-1"), any())).thenReturn(prior);
when(service.listTagsForResource("healthcheck", "hc-1")).thenReturn(Map.of());
org.mockito.Mockito.doThrow(new AwsException("Throttling", "slow down", 400)).doNothing()
.when(service).changeTagsForResource(eq("healthcheck"), eq("hc-1"), any(), any());
StackResource resource = existingCheck();
JsonNode props = new ObjectMapper().readTree("""
{"HealthCheckConfig": {"Type": "HTTP", "IPAddress": "10.0.0.9"},
"HealthCheckTags": [{"Key": "team", "Value": "web"}]}""");
assertThrows(AwsException.class, () -> new Route53CfnProvisioner(service)
.provision(resource, props, healthCheckContext("hc-1")));
verify(service).updateHealthCheck(eq("hc-1"), argThat(cfg -> "10.0.0.5".equals(cfg.getIpAddress())));
assertEquals("true", resource.getAttributes().get(CfnRollback.UPDATE_ROLLBACK_RESTORED_ATTR));
}
@Test
void aNewHealthCheckWhoseTaggingFailsIsDeleted() throws Exception {
Route53Service service = mock(Route53Service.class);
when(service.createHealthCheck(any(), any(), any()))
.thenAnswer(inv -> new HealthCheck("hc-1", inv.getArgument(0), inv.getArgument(1), inv.getArgument(2)));
org.mockito.Mockito.doThrow(new AwsException("Throttling", "slow down", 400))
.when(service).changeTagsForResource(any(), any(), any(), any());
JsonNode props = new ObjectMapper().readTree("""
{"HealthCheckConfig": {"Type": "TCP", "IPAddress": "10.0.0.5", "Port": 22},
"HealthCheckTags": [{"Key": "team", "Value": "web"}]}""");
StackResource resource = new StackResource();
resource.setLogicalId("Check");
resource.setResourceType("AWS::Route53::HealthCheck");
assertThrows(AwsException.class, () -> new Route53CfnProvisioner(service)
.provision(resource, props, healthCheckContext(null)));
verify(service).deleteHealthCheck("hc-1");
assertNull(resource.getPhysicalId());
}
@Test
void healthCheckWithAnUnknownTypeIsRejected() throws Exception {
Route53Service service = mock(Route53Service.class);
JsonNode props = new ObjectMapper().readTree("{\"HealthCheckConfig\": {\"Type\": \"PING\"}}");
StackResource resource = new StackResource();
resource.setLogicalId("Check");
resource.setResourceType("AWS::Route53::HealthCheck");
AwsException error = assertThrows(AwsException.class, () -> new Route53CfnProvisioner(service)
.provision(resource, props, healthCheckContext(null)));
assertEquals("ValidationError", error.getErrorCode());
verifyNoInteractions(service);
}
@Test
void otherRoute53TypesKeepTheDefaultRollback() {
StackResource zone = new StackResource();
zone.setLogicalId("Zone");
zone.setResourceType("AWS::Route53::HostedZone");
assertFalse(new Route53CfnProvisioner(mock(Route53Service.class)).rollbackUpdate(zone));
}
/** A service holding check hc-1 (HTTP on 10.0.0.5:80) that creates hc-2. */
private static Route53Service replacingService() {
Route53Service service = mock(Route53Service.class);
HealthCheckConfig priorConfig = new HealthCheckConfig();
priorConfig.setType("HTTP");
priorConfig.setIpAddress("10.0.0.5");
priorConfig.setPort(80);
when(service.getHealthCheck("hc-1")).thenReturn(new HealthCheck("hc-1", "ref", priorConfig, ""));
when(service.createHealthCheck(any(), any(), any()))
.thenAnswer(inv -> new HealthCheck("hc-2", inv.getArgument(0), inv.getArgument(1), inv.getArgument(2)));
return service;
}
private static StackResource existingCheck() {
StackResource resource = new StackResource();
resource.setLogicalId("Check");
resource.setResourceType("AWS::Route53::HealthCheck");
resource.setPhysicalId("hc-1");
resource.getAttributes().put("HealthCheckId", "hc-1");
return resource;
}
private static JsonNode healthCheckProps(String type, Integer requestInterval) throws Exception {
String interval = requestInterval == null ? "" : ", \"RequestInterval\": " + requestInterval;
return new ObjectMapper().readTree("{\"HealthCheckConfig\": {\"Type\": \"" + type
+ "\", \"IPAddress\": \"10.0.0.5\", \"Port\": 80" + interval + "}}");
}
private static Set<String> publicAttributes(StackResource resource) {
Set<String> keys = new HashSet<>(resource.getAttributes().keySet());
keys.removeIf(key -> key.startsWith("__Floci"));
return keys;
}
@Test
void healthCheckWithoutAConfigTypeIsRejected() throws Exception {
Route53Service service = mock(Route53Service.class);
JsonNode props = new ObjectMapper().readTree("{\"HealthCheckConfig\": {\"Port\": 80}}");
StackResource resource = new StackResource();
resource.setLogicalId("Check");
resource.setResourceType("AWS::Route53::HealthCheck");
assertThrows(AwsException.class, () -> new Route53CfnProvisioner(service)
.provision(resource, props, healthCheckContext(null)));
verifyNoInteractions(service);
}
@Test
void deletingAHealthCheckAlreadyGoneIsTolerated() {
Route53Service service = mock(Route53Service.class);
org.mockito.Mockito.doThrow(new AwsException("NoSuchHealthCheck", "gone", 404))
.when(service).deleteHealthCheck("hc-1");
StackResource resource = new StackResource();
resource.setLogicalId("Check");
resource.setResourceType("AWS::Route53::HealthCheck");
resource.setPhysicalId("hc-1");
new Route53CfnProvisioner(service).delete(resource, "us-east-1");
verify(service).deleteHealthCheck("hc-1");
}
private static ProvisionContext healthCheckContext(String priorPhysicalId) {
CloudFormationTemplateEngine engine = recordEngine();
when(engine.resolveNode(any())).thenAnswer(invocation -> invocation.getArgument(0));
return priorPhysicalId == null
? new ProvisionContext(engine, "us-east-1", "000000000000", "dns-stack")
: new ProvisionContext(engine, "us-east-1", "000000000000", "dns-stack", priorPhysicalId);
}
private static CloudFormationTemplateEngine recordEngine() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(invocation -> {