feat(cloudformation): provision Application Auto Scaling targets and policies (#5407)

* feat(cloudformation): provision Application Auto Scaling targets and policies

AWS::ApplicationAutoScaling::ScalableTarget and ::ScalingPolicy had no
provisioner, so a template that scales an ECS service failed on those two
resources although the Application Auto Scaling service behind them, including
the ECS capacity adjuster, was already there. This wires the two together.

A scalable target has no name of its own: it is keyed by the triple of service
namespace, resource id and scalable dimension, and CloudFormation's Ref is those
three joined by a pipe. That composite is the physical id, which is also what a
policy's ScalingTargetId carries when a template points one at the other with
Ref, so the provisioner splits it back into the triple. A policy's Ref is its
ARN rather than its name, so deleting one resolves the ARN through
findPolicyByArn to recover the name and triple the service deletes by.

Because the target's id is derived from the triple, changing any part of it
replaces the target rather than updating it, so both types go through
ReplacementCleanup to deregister what they displaced. Deletes tolerate only
ObjectNotFoundException through CfnDeletes.safeDelete: a target takes its own
policies with it, so a stack teardown reaches an already-deleted policy by
ordinary ordering, while any other failure still surfaces as DELETE_FAILED.

The properties each schema marks required are enforced rather than defaulted.
MinCapacity and MaxCapacity on a target, and PolicyName and PolicyType on a
policy, would otherwise register a target that never scales or accept a template
CloudFormation itself rejects.

The two scaling configuration blocks are parsed by the same code the
PutScalingPolicy API path uses, extracted to ScalingConfigurationParser, since
CloudFormation spells their members exactly as the API does. One parser means a
template and an API call cannot disagree about what a policy means.

ScheduledActions on a target is logged rather than dropped silently: Floci does
not run scheduled scaling, and a template that scales on a clock should not look
fully provisioned when nothing is scheduled.

* fix(cloudformation): resolve intrinsics inside the scaling configuration blocks

Review on #5407: the two scaling configuration blocks and SuspendedState reached
the parser as raw template JSON, so an intrinsic inside one was never resolved.
That is worse than it sounds, because an intrinsic is still a non-null node:
hasNonNull passes and the value is read with asDouble, asText or asBoolean,
which answer 0, "" and false. A policy written as TargetValue: !Ref TargetCpu
registered as a policy targeting 0 percent rather than failing, a ResourceLabel
built with Fn::Join arrived empty, and a flag behind Fn::If read false.

Each block now goes through ctx.engine().resolveNode first, which is what
AutoScalingScalingPolicyCfnProvisioner already does with its own block. Only
nested objects were affected: the top-level properties were already read through
ctx.resolveOptional, which resolves.

A target's Tags were dropped as well, passed to the service as an empty map
rather than read with ctx.resolveTags.

ScheduledActions now carries a note in the generated resource-type table rather
than only a warning in the log, so the gap is visible before someone wonders why
their clock-based scaling never fires.

* test(cloudformation): make the SuspendedState intrinsic test fail without its fix

Review on #5407: anIntrinsicInsideSuspendedStateIsResolvedToo passed against the
previous commit too. REFS had no Suspend entry, so the flag resolved to an empty
string and read false either way, and assertNotNull held regardless because the
raw block was already an object. The test pinned nothing.

REFS now maps Suspend to true and the assertion is on
isDynamicScalingInSuspended(), so it fails with expected: <true> but was:
<false> when SuspendedState is read without resolveNode. The redundant copy of
the properties node is gone.
This commit is contained in:
Anders Wasen authored and GitHub committed 2026-10-11 12:19:25 -04:00
1 parent 3ad1a76507
commit bfa9c2fbcc
10 files changed
+853 -60

No files matched your search

@@ -7,6 +7,7 @@ import io.github.hectorvent.floci.core.common.docker.ContainerReachableEndpoint;
import io.github.hectorvent.floci.services.acm.AcmService;
import io.github.hectorvent.floci.services.apigateway.ApiGatewayService;
import io.github.hectorvent.floci.services.apigatewayv2.ApiGatewayV2Service;
import io.github.hectorvent.floci.services.applicationautoscaling.ApplicationAutoScalingService;
import io.github.hectorvent.floci.services.appsync.AppSyncService;
import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
import io.github.hectorvent.floci.services.backup.BackupService;
@@ -20,6 +21,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayUsagePlanCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayV2CfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AppSyncCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApplicationAutoScalingCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingGroupCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
@@ -186,6 +188,7 @@ final class CfnProvisionerFixture {
private EventBridgeService eventBridgeService;
private ApiGatewayService apiGatewayService;
private ApiGatewayV2Service apiGatewayV2Service;
private ApplicationAutoScalingService applicationAutoScalingService;
private EcrService ecrService;
private PipesService pipesService;
private CognitoService cognitoService;
@@ -358,6 +361,9 @@ final class CfnProvisionerFixture {
discovered.add(new ApiGatewayGatewayResponseCfnProvisioner(apiGatewayService));
discovered.add(new ApiGatewayRestApiCfnProvisioner(apiGatewayService, s3Service, objectMapper));
}
if (applicationAutoScalingService != null) {
discovered.add(new ApplicationAutoScalingCfnProvisioner(applicationAutoScalingService, objectMapper));
}
if (apiGatewayV2Service != null) {
discovered.add(new ApiGatewayV2CfnProvisioner(apiGatewayV2Service, s3Service, objectMapper));
}
@@ -516,6 +522,11 @@ final class CfnProvisionerFixture {
return this;
}
public Builder applicationAutoScaling(ApplicationAutoScalingService v) {
this.applicationAutoScalingService = v;
return this;
}
public Builder apiGatewayV2(ApiGatewayV2Service v) {
this.apiGatewayV2Service = v;
return this;
@@ -0,0 +1,190 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import io.restassured.config.EncoderConfig;
import io.restassured.http.ContentType;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.hamcrest.Matchers.not;
/**
* End-to-end check that CloudFormation provisions Application Auto Scaling for real rather than
* stubbing it.
*
* <p>An unmapped type is stubbed as {@code CREATE_COMPLETE} with a fake ARN, so asserting the
* stack status alone would pass against a type that was never wired. These assertions are on the
* {@code Fn::GetAtt} keys from the resource schemas ({@code Id} for the target, {@code Arn} for the
* policy) and on the entities being visible through the Application Auto Scaling API afterwards.
*/
@QuarkusTest
class CloudFormationApplicationAutoScalingIntegrationTest {
private static final String CFN_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/cloudformation/aws4_request";
private static final String AAS_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/application-autoscaling/aws4_request";
@Test
void createStackProvisionsAScalableTargetAndItsPolicy() {
String suffix = Long.toString(System.nanoTime(), 36);
String resourceId = "service/cfn-cluster-" + suffix + "/svc";
String stackName = "cfn-aas-stack-" + suffix;
String policyName = "cfn-aas-policy-" + suffix;
String template = """
{
"Resources": {
"Target": {
"Type": "AWS::ApplicationAutoScaling::ScalableTarget",
"Properties": {
"ServiceNamespace": "ecs",
"ResourceId": "%s",
"ScalableDimension": "ecs:service:DesiredCount",
"MinCapacity": 1,
"MaxCapacity": 4
}
},
"Policy": {
"Type": "AWS::ApplicationAutoScaling::ScalingPolicy",
"Properties": {
"PolicyName": "%s",
"PolicyType": "TargetTrackingScaling",
"ScalingTargetId": {"Ref": "Target"},
"TargetTrackingScalingPolicyConfiguration": {
"TargetValue": 60,
"PredefinedMetricSpecification": {
"PredefinedMetricType": "ECSServiceAverageCPUUtilization"
}
}
}
}
},
"Outputs": {
"TargetId": {"Value": {"Fn::GetAtt": ["Target", "Id"]}},
"PolicyArn": {"Value": {"Fn::GetAtt": ["Policy", "Arn"]}}
}
}
""".formatted(resourceId, policyName);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DescribeStacks")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
// Ref on a scalable target is resourceId|scalableDimension|serviceNamespace, and
// GetAtt Id is the same composite.
.body(containsString(resourceId + "|ecs:service:DesiredCount|ecs"))
.body(containsString(":scalingPolicy:"))
// An unwired type resolves Fn::GetAtt to the literal "LogicalId.Attr".
.body(not(containsString("Target.Id")))
.body(not(containsString("Policy.Arn")));
given()
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
.header("Authorization", AAS_AUTH)
.header("X-Amz-Target", "AnyScaleFrontendService.DescribeScalableTargets")
.contentType("application/x-amz-json-1.1")
.body("{\"ServiceNamespace\":\"ecs\",\"ResourceIds\":[\"" + resourceId + "\"]}")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString(resourceId))
.body(containsString("\"MinCapacity\":1"))
.body(containsString("\"MaxCapacity\":4"));
given()
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
.header("Authorization", AAS_AUTH)
.header("X-Amz-Target", "AnyScaleFrontendService.DescribeScalingPolicies")
.contentType("application/x-amz-json-1.1")
.body("{\"ServiceNamespace\":\"ecs\",\"ResourceId\":\"" + resourceId + "\"}")
.when()
.post("/")
.then()
.statusCode(200)
.body(containsString(policyName))
.body(containsString("TargetTrackingScaling"))
// The configuration reached the service rather than being dropped on the way through.
.body(containsString("ECSServiceAverageCPUUtilization"));
}
@Test
void deletingTheStackDeregistersTheTarget() {
String suffix = Long.toString(System.nanoTime(), 36);
String resourceId = "service/cfn-cluster-del-" + suffix + "/svc";
String stackName = "cfn-aas-del-stack-" + suffix;
String template = """
{
"Resources": {
"Target": {
"Type": "AWS::ApplicationAutoScaling::ScalableTarget",
"Properties": {
"ServiceNamespace": "ecs",
"ResourceId": "%s",
"ScalableDimension": "ecs:service:DesiredCount",
"MinCapacity": 1,
"MaxCapacity": 2
}
}
}
}
""".formatted(resourceId);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "CreateStack")
.formParam("StackName", stackName)
.formParam("TemplateBody", template)
.when()
.post("/")
.then()
.statusCode(200);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", CFN_AUTH)
.formParam("Action", "DeleteStack")
.formParam("StackName", stackName)
.when()
.post("/")
.then()
.statusCode(200);
given()
.config(RestAssured.config().encoderConfig(EncoderConfig.encoderConfig()
.encodeContentTypeAs("application/x-amz-json-1.1", ContentType.TEXT)))
.header("Authorization", AAS_AUTH)
.header("X-Amz-Target", "AnyScaleFrontendService.DescribeScalableTargets")
.contentType("application/x-amz-json-1.1")
.body("{\"ServiceNamespace\":\"ecs\",\"ResourceIds\":[\"" + resourceId + "\"]}")
.when()
.post("/")
.then()
.statusCode(200)
.body(not(containsString(resourceId)));
}
}
@@ -0,0 +1,320 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.applicationautoscaling.ApplicationAutoScalingService;
import io.github.hectorvent.floci.services.applicationautoscaling.model.ScalingPolicy;
import io.github.hectorvent.floci.services.applicationautoscaling.model.SuspendedState;
import io.github.hectorvent.floci.services.applicationautoscaling.model.TargetTrackingConfiguration;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.assertEquals;
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.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* The Application Auto Scaling CFN provisioner in isolation. The cases that matter are the
* composite target id, since that is both {@code Ref} and the link a policy follows to its target,
* and that the policy configuration blocks survive the trip from template to service unchanged.
*/
class ApplicationAutoScalingCfnProvisionerTest {
private static final String TARGET_ID = "service/my-cluster/my-service|ecs:service:DesiredCount|ecs";
private final ApplicationAutoScalingService service = mock(ApplicationAutoScalingService.class);
private final ObjectMapper mapper = new ObjectMapper();
private final ApplicationAutoScalingCfnProvisioner provisioner =
new ApplicationAutoScalingCfnProvisioner(service, mapper);
/** Stands in for the template's parameters, so {"Ref": "TargetCpu"} has something to become. */
private static final Map<String, String> REFS = Map.of("TargetCpu", "70", "Env", "prod", "Suspend", "true");
private ProvisionContext ctx() {
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
when(engine.resolve(any())).thenAnswer(inv -> {
JsonNode node = resolveNode(inv.getArgument(0));
return node == null || node.isNull() ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> resolveNode(inv.getArgument(0)));
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
}
/** The engine's job in miniature: replace every {"Ref": name} anywhere in the tree. */
private JsonNode resolveNode(JsonNode node) {
if (node == null || node.isNull() || node.isMissingNode()) {
return node;
}
if (node.isObject()) {
JsonNode ref = node.get("Ref");
if (ref != null && node.size() == 1) {
return mapper.getNodeFactory().textNode(REFS.getOrDefault(ref.asText(), ""));
}
ObjectNode out = mapper.createObjectNode();
node.fields().forEachRemaining(e -> out.set(e.getKey(), resolveNode(e.getValue())));
return out;
}
if (node.isArray()) {
ArrayNode out = mapper.createArrayNode();
node.forEach(child -> out.add(resolveNode(child)));
return out;
}
return node;
}
private StackResource resource(String type, String logicalId) {
StackResource r = new StackResource();
r.setLogicalId(logicalId);
r.setResourceType(type);
r.setAttributes(new HashMap<>());
return r;
}
private ObjectNode targetProps() {
return mapper.createObjectNode()
.put("ServiceNamespace", "ecs")
.put("ResourceId", "service/my-cluster/my-service")
.put("ScalableDimension", "ecs:service:DesiredCount")
.put("MinCapacity", 1)
.put("MaxCapacity", 4);
}
private ScalingPolicy aPolicy(String arn) {
ScalingPolicy policy = new ScalingPolicy();
policy.setPolicyArn(arn);
policy.setPolicyName("cpu-target-tracking");
policy.setServiceNamespace("ecs");
policy.setResourceId("service/my-cluster/my-service");
policy.setScalableDimension("ecs:service:DesiredCount");
return policy;
}
@Test
void aScalableTargetRegistersAndRefsAsTheCompositeId() {
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, "Target");
provisioner.provision(r, targetProps(), ctx());
verify(service).registerScalableTarget("ecs", "service/my-cluster/my-service",
"ecs:service:DesiredCount", 1, 4, null, null, java.util.Map.of(), "us-east-1");
// CloudFormation's Ref for a scalable target is resourceId|scalableDimension|serviceNamespace.
assertEquals(TARGET_ID, r.getPhysicalId());
assertEquals(TARGET_ID, r.getAttributes().get("Id"));
}
@Test
void aPolicyFollowsScalingTargetIdBackToItsTargetsTriple() {
when(service.putScalingPolicy(any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(aPolicy("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc"));
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
ObjectNode props = mapper.createObjectNode()
.put("PolicyName", "cpu-target-tracking")
.put("PolicyType", "TargetTrackingScaling")
// What `Ref: ServerpublicapiScalableTarget` resolves to.
.put("ScalingTargetId", TARGET_ID);
props.putObject("TargetTrackingScalingPolicyConfiguration")
.put("TargetValue", 60)
.putObject("PredefinedMetricSpecification")
.put("PredefinedMetricType", "ECSServiceAverageCPUUtilization");
provisioner.provision(r, props, ctx());
verify(service).putScalingPolicy(eq("cpu-target-tracking"), eq("TargetTrackingScaling"),
eq("ecs"), eq("service/my-cluster/my-service"), eq("ecs:service:DesiredCount"),
any(), isNull(), eq("us-east-1"));
// Ref on a scaling policy is its ARN, not its name.
assertEquals("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc", r.getPhysicalId());
assertEquals("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc", r.getAttributes().get("Arn"));
}
@Test
void theTargetTrackingConfigurationReachesTheServiceIntact() {
when(service.putScalingPolicy(any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(aPolicy("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc"));
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
ObjectNode props = mapper.createObjectNode()
.put("PolicyName", "cpu")
.put("PolicyType", "TargetTrackingScaling")
.put("ScalingTargetId", TARGET_ID);
props.putObject("TargetTrackingScalingPolicyConfiguration")
.put("TargetValue", 60)
.put("ScaleInCooldown", 300)
.putObject("PredefinedMetricSpecification")
.put("PredefinedMetricType", "ECSServiceAverageCPUUtilization");
provisioner.provision(r, props, ctx());
ArgumentCaptor<TargetTrackingConfiguration> captor =
ArgumentCaptor.forClass(TargetTrackingConfiguration.class);
verify(service).putScalingPolicy(any(), any(), any(), any(), any(), captor.capture(), isNull(), any());
assertEquals(60.0, captor.getValue().getTargetValue());
assertEquals(300, captor.getValue().getScaleInCooldown());
assertEquals("ECSServiceAverageCPUUtilization",
captor.getValue().getPredefinedMetricSpecification().getPredefinedMetricType());
}
@Test
void aPolicyMayNameItsTargetDirectlyInsteadOfReferencingIt() {
when(service.putScalingPolicy(any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(aPolicy("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc"));
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
ObjectNode props = targetProps().put("PolicyName", "step").put("PolicyType", "StepScaling");
props.putObject("StepScalingPolicyConfiguration").put("AdjustmentType", "ChangeInCapacity");
provisioner.provision(r, props, ctx());
verify(service).putScalingPolicy(eq("step"), eq("StepScaling"), eq("ecs"),
eq("service/my-cluster/my-service"), eq("ecs:service:DesiredCount"),
isNull(), any(), eq("us-east-1"));
}
@Test
void aScalingTargetIdThatIsNotTheCompositeIsRefused() {
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
ObjectNode props = mapper.createObjectNode()
.put("PolicyName", "cpu")
.put("PolicyType", "TargetTrackingScaling")
.put("ScalingTargetId", "just-a-service-name");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
assertTrue(e.getMessage().contains("resourceId|scalableDimension|serviceNamespace"), e.getMessage());
}
@Test
void deletingTheTargetDeregistersItsTriple() {
provisioner.delete(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, TARGET_ID, "us-east-1");
// Order matters: the composite is resourceId|dimension|namespace, the call is (namespace, id, dimension).
verify(service).deregisterScalableTarget("ecs", "service/my-cluster/my-service",
"ecs:service:DesiredCount", "us-east-1");
}
@Test
void deletingAPolicyResolvesItsArnBackToTheNameAndTriple() {
String arn = "arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc";
when(service.findPolicyByArn(arn, "us-east-1")).thenReturn(Optional.of(aPolicy(arn)));
provisioner.delete(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, arn, "us-east-1");
verify(service).deleteScalingPolicy("cpu-target-tracking", "ecs",
"service/my-cluster/my-service", "ecs:service:DesiredCount", "us-east-1");
}
@Test
void aPolicyAlreadyGoneIsNotAnError() {
String arn = "arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:gone";
when(service.findPolicyByArn(arn, "us-east-1")).thenReturn(Optional.empty());
// Deregistering a target takes its policies with it, so the stack's own policy delete that
// follows finds nothing. That is a normal teardown ordering, not a failure.
provisioner.delete(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, arn, "us-east-1");
}
@Test
void aTargetWithoutItsCapacityBoundsIsRefused() {
// MinCapacity and MaxCapacity are required by the resource schema. Registering without them
// would leave a target that never scales, which is worse than refusing the template.
for (String missing : new String[] {"MinCapacity", "MaxCapacity"}) {
ObjectNode props = targetProps();
props.remove(missing);
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, "Target");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
assertTrue(e.getMessage().contains(missing), e.getMessage());
}
}
@Test
void aPolicyWithoutItsNameOrTypeIsRefused() {
for (String missing : new String[] {"PolicyName", "PolicyType"}) {
ObjectNode props = mapper.createObjectNode()
.put("PolicyName", "cpu")
.put("PolicyType", "TargetTrackingScaling")
.put("ScalingTargetId", TARGET_ID);
props.remove(missing);
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(r, props, ctx()));
assertTrue(e.getMessage().contains(missing), e.getMessage());
}
}
@Test
void aTargetAlreadyDeregisteredIsNotAnError() {
doThrow(new AwsException("ObjectNotFoundException", "No scalable target found", 400))
.when(service).deregisterScalableTarget(any(), any(), any(), any());
// Its own policies deregister with it, so a stack teardown can reach this twice.
provisioner.delete(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, TARGET_ID, "us-east-1");
}
@Test
void anIntrinsicInsideTheTargetTrackingBlockIsResolvedRatherThanReadRaw() {
when(service.putScalingPolicy(any(), any(), any(), any(), any(), any(), any(), any()))
.thenReturn(aPolicy("arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:abc"));
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALING_POLICY, "Policy");
ObjectNode props = mapper.createObjectNode()
.put("PolicyName", "cpu")
.put("PolicyType", "TargetTrackingScaling")
.put("ScalingTargetId", TARGET_ID);
ObjectNode config = props.putObject("TargetTrackingScalingPolicyConfiguration");
config.putObject("TargetValue").put("Ref", "TargetCpu");
config.putObject("PredefinedMetricSpecification")
.put("PredefinedMetricType", "ECSServiceAverageCPUUtilization");
provisioner.provision(r, props, ctx());
ArgumentCaptor<TargetTrackingConfiguration> captor =
ArgumentCaptor.forClass(TargetTrackingConfiguration.class);
verify(service).putScalingPolicy(any(), any(), any(), any(), any(), captor.capture(), isNull(), any());
// Read raw, {"Ref": "TargetCpu"} is a non-null node whose asDouble() is 0, so the guard
// passes and the policy silently targets 0% rather than failing.
assertEquals(70.0, captor.getValue().getTargetValue());
}
@Test
void anIntrinsicInsideSuspendedStateIsResolvedToo() {
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, "Target");
ObjectNode props = targetProps();
props.putObject("SuspendedState").putObject("DynamicScalingInSuspended").put("Ref", "Suspend");
provisioner.provision(r, props, ctx());
ArgumentCaptor<SuspendedState> captor = ArgumentCaptor.forClass(SuspendedState.class);
verify(service).registerScalableTarget(any(), any(), any(), any(), any(), any(),
captor.capture(), any(), any());
// The flag itself, not just that a block arrived: read raw, {"Ref": "Suspend"} is an
// object whose asBoolean() is false, and the block is an object either way.
assertTrue(captor.getValue().isDynamicScalingInSuspended());
}
@Test
void theTargetsTagsAreRegisteredRatherThanDropped() {
StackResource r = resource(ApplicationAutoScalingCfnProvisioner.SCALABLE_TARGET, "Target");
ObjectNode props = targetProps();
ArrayNode tags = props.putArray("Tags");
tags.addObject().put("Key", "Owner").put("Value", "platform");
tags.addObject().put("Key", "Env").putObject("Value").put("Ref", "Env");
provisioner.provision(r, props, ctx());
verify(service).registerScalableTarget(any(), any(), any(), any(), any(), any(), any(),
eq(Map.of("Owner", "platform", "Env", "prod")), any());
}
}