Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(cloudformation): provision AWS::AutoScaling::ScalingPolicy (#3124)

lex0017af9590c796
diff --git a/docs/services/cloudformation.md b/docs/services/cloudformation.md
index 8601eee9fb..b3b1046141 100644
--- a/docs/services/cloudformation.md
+++ b/docs/services/cloudformation.md
@@ -82,7 +82,7 @@ cross-resource references.
| RDS | `DBInstance` (starts a real container), `DBCluster` (starts a real container), `DBSubnetGroup`, `DBParameterGroup`, `DBClusterParameterGroup`, `DBProxy`, `DBProxyTargetGroup` |
| EC2 | `VPC`, `Subnet`, `SecurityGroup` (inline `SecurityGroupIngress`/`SecurityGroupEgress` supported), `SecurityGroupIngress`, `SecurityGroupEgress`, `InternetGateway`, `RouteTable`, `SubnetRouteTableAssociation`, `Route`, `NatGateway`, `EIP`, `Instance`, `LaunchTemplate`, `VPCGatewayAttachment`, `VPCEndpoint`, `NetworkAcl`, `NetworkAclEntry`, `SubnetNetworkAclAssociation`, `FlowLog` |
| Elastic Load Balancing v2 | `LoadBalancer`, `TargetGroup`, `Listener`, `ListenerRule` |
-| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook` |
+| Auto Scaling | `LaunchConfiguration`, `AutoScalingGroup`, `LifecycleHook`, `ScalingPolicy` |
| Route 53 | `HostedZone`, `RecordSet` |
| API Gateway (v1) | `RestApi`, `Resource`, `Authorizer`, `Method`, `Deployment`, `Stage`, `Account`, `DomainName`, `BasePathMapping`, `ApiKey` |
| API Gateway v2 | `Api`, `Authorizer`, `Route`, `Integration`, `Stage`, `Deployment` |
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingScalingPolicyCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingScalingPolicyCfnProvisioner.java
new file mode 100644
index 0000000000..a95be46a36
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingScalingPolicyCfnProvisioner.java
@@ -0,0 +1,138 @@
+package io.github.hectorvent.floci.services.cloudformation.provisioners;
+
+import com.fasterxml.jackson.databind.JsonNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
+import io.github.hectorvent.floci.services.autoscaling.model.ScalingPolicy;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+
+import java.util.Set;
+
+/**
+ * CloudFormation provisioning for {@code AWS::AutoScaling::ScalingPolicy}, backed by
+ * {@link AutoScalingService}. {@code Ref} and {@code Fn::GetAtt Arn} are the policy ARN and
+ * {@code Fn::GetAtt PolicyName} the generated name, matching AWS, which offers no PolicyName
+ * property and names the policy after the stack and logical id.
+ *
+ * <p>PutScalingPolicy is an upsert keyed by group and name, so an update reuses the name recorded
+ * at create time and rewrites the policy in place. AutoScalingGroupName is createOnly: moving the
+ * policy to another group is refused as a replacement rather than left behind on the old group.
+ * StepAdjustments, MinAdjustmentMagnitude, MetricAggregationType, PredictiveScalingConfiguration
+ * and the customized-metric and DisableScaleIn parts of TargetTrackingConfiguration have no
+ * counterpart in {@link ScalingPolicy} and are accepted without effect.
+ */
+@ApplicationScoped
+public class AutoScalingScalingPolicyCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final String TYPE = "AWS::AutoScaling::ScalingPolicy";
+ /** The Auto Scaling API's limit on a policy name. */
+ private static final int POLICY_NAME_MAX = 255;
+ /** The defaults the Query handler applies when PutScalingPolicy omits these, kept in step with it. */
+ private static final int DEFAULT_SCALING_ADJUSTMENT = 0;
+ private static final int DEFAULT_COOLDOWN = 300;
+
+ private final AutoScalingService autoScalingService;
+
+ @Inject
+ public AutoScalingScalingPolicyCfnProvisioner(AutoScalingService autoScalingService) {
+ this.autoScalingService = autoScalingService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(TYPE);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String asgName = ctx.resolveOptional(props, "AutoScalingGroupName");
+ String policyName = priorAttribute(r, ctx, "PolicyName");
+ if (policyName != null) {
+ // Identity comes from the group recorded at create time, not from finding the name on
+ // the group the template now asks for. A same-named policy already on the destination
+ // group is somebody else's: reading it as this resource would overwrite it and orphan
+ // the original. A resource provisioned before this attribute existed has no prior group
+ // and keeps the old behaviour of trusting the template.
+ String priorAsgName = priorAttribute(r, ctx, "AutoScalingGroupName");
+ if (priorAsgName != null && !priorAsgName.equals(asgName)) {
+ throw new AwsException("ValidationError",
+ "Updating AutoScalingGroupName requires resource replacement, which is not supported.", 400);
+ }
+ } else {
+ policyName = ctx.generatePhysicalName(r.getLogicalId(), POLICY_NAME_MAX, false);
+ }
+
+ ScalingPolicy policy = autoScalingService.putScalingPolicy(ctx.region(), asgName, policyName,
+ ctx.resolveOptional(props, "PolicyType"),
+ ctx.resolveOptional(props, "AdjustmentType"),
+ intOrDefault(ctx.resolveOptional(props, "ScalingAdjustment"), DEFAULT_SCALING_ADJUSTMENT),
+ intOrDefault(ctx.resolveOptional(props, "Cooldown"), DEFAULT_COOLDOWN),
+ nullableInt(ctx.resolveOptional(props, "EstimatedInstanceWarmup")),
+ targetTracking(props, ctx));
+
+ r.setPhysicalId(policy.getPolicyArn());
+ r.getAttributes().put("Arn", policy.getPolicyArn());
+ r.getAttributes().put("PolicyName", policyName);
+ // Not a Fn::GetAtt attribute of the type. It is the record of which group owns this policy,
+ // which the next update needs to tell a rewrite from a move.
+ r.getAttributes().put("AutoScalingGroupName", asgName);
+ }
+
+ /**
+ * An attribute this resource recorded on an earlier provision, or null on a first create. The
+ * name and the group are read from here rather than parsed out of the ARN, so the ARN's shape
+ * stays the service's business. Generating a fresh name on every UpdateStack would put a second
+ * policy on the group and orphan the first, which then outlives the stack.
+ */
+ private static String priorAttribute(StackResource r, ProvisionContext ctx, String name) {
+ if (!ctx.isUpdate() || r.getAttributes() == null) {
+ return null;
+ }
+ String prior = r.getAttributes().get(name);
+ return prior == null || prior.isBlank() ? null : prior;
+ }
+
+ private static ScalingPolicy.TargetTrackingConfiguration targetTracking(JsonNode props, ProvisionContext ctx) {
+ if (props == null || !props.hasNonNull("TargetTrackingConfiguration")) {
+ return null;
+ }
+ JsonNode node = ctx.engine().resolveNode(props.get("TargetTrackingConfiguration"));
+ if (node == null || node.isNull()) {
+ return null;
+ }
+ ScalingPolicy.TargetTrackingConfiguration configuration = new ScalingPolicy.TargetTrackingConfiguration();
+ String targetValue = ctx.engine().resolve(node.path("TargetValue"));
+ if (targetValue != null && !targetValue.isBlank()) {
+ configuration.setTargetValue(Double.parseDouble(targetValue));
+ }
+ JsonNode predefined = node.get("PredefinedMetricSpecification");
+ if (predefined != null && !predefined.isNull()) {
+ ScalingPolicy.PredefinedMetricSpecification specification = new ScalingPolicy.PredefinedMetricSpecification();
+ specification.setPredefinedMetricType(ctx.engine().resolve(predefined.path("PredefinedMetricType")));
+ configuration.setPredefinedMetricSpecification(specification);
+ }
+ return configuration;
+ }
+
+ private static int intOrDefault(String value, int fallback) {
+ return value == null || value.isBlank() ? fallback : Integer.parseInt(value.trim());
+ }
+
+ private static Integer nullableInt(String value) {
+ return value == null || value.isBlank() ? null : Integer.valueOf(value.trim());
+ }
+
+ /**
+ * Without this the policy outlives its stack and keeps showing up in DescribePolicies. The
+ * service matches by name or ARN and already treats a missing policy as nothing to do.
+ */
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ if (physicalId == null || physicalId.isBlank()) {
+ return;
+ }
+ autoScalingService.deletePolicy(region, null, physicalId);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/AutoScalingScalingPolicyCfnIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AutoScalingScalingPolicyCfnIntegrationTest.java
new file mode 100644
index 0000000000..bc406a4b5b
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/AutoScalingScalingPolicyCfnIntegrationTest.java
@@ -0,0 +1,211 @@
+package io.github.hectorvent.floci.services.cloudformation;
+
+import io.github.hectorvent.floci.core.common.XmlParser;
+import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
+import io.github.hectorvent.floci.services.autoscaling.model.ScalingPolicy;
+import io.quarkus.test.junit.QuarkusTest;
+import io.restassured.response.ValidatableResponse;
+import io.restassured.specification.RequestSpecification;
+import jakarta.inject.Inject;
+import org.junit.jupiter.api.Test;
+
+import java.util.List;
+import java.util.Map;
+
+import static io.restassured.RestAssured.given;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.not;
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertTrue;
+import static org.junit.jupiter.api.Assertions.fail;
+
+/**
+ * Provisions two {@code AWS::AutoScaling::ScalingPolicy} resources on a group the same stack
+ * creates: a target-tracking policy and a simple-scaling one. Asserts that {@code Ref} and
+ * {@code Fn::GetAtt Arn} are the ARN {@code DescribePolicies} reports and {@code Fn::GetAtt
+ * PolicyName} the generated name, that an update rewrites both policies in place under the same
+ * name and ARN, and that deleting the stack removes them from the group.
+ */
+@QuarkusTest
+class AutoScalingScalingPolicyCfnIntegrationTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String CFN_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/cloudformation/aws4_request";
+ private static final String ASG_AUTH =
+ "AWS4-HMAC-SHA256 Credential=test/20260905/us-east-1/autoscaling/aws4_request";
+ private static final String STACK = "asg-policy-cfn-it";
+ private static final String ASG = "asg-policy-cfn-it-group";
+
+ private static final String TEMPLATE = """
+ {
+ "Parameters": {
+ "TargetValue": {"Type": "String"},
+ "Cooldown": {"Type": "String"}
+ },
+ "Resources": {
+ "Vpc": {"Type": "AWS::EC2::VPC", "Properties": {"CidrBlock": "10.81.0.0/16"}},
+ "Subnet": {
+ "Type": "AWS::EC2::Subnet",
+ "Properties": {"VpcId": {"Ref": "Vpc"}, "CidrBlock": "10.81.1.0/24"}
+ },
+ "Lc": {
+ "Type": "AWS::AutoScaling::LaunchConfiguration",
+ "Properties": {"ImageId": "ami-11111111", "InstanceType": "t3.micro"}
+ },
+ "Asg": {
+ "Type": "AWS::AutoScaling::AutoScalingGroup",
+ "Properties": {
+ "AutoScalingGroupName": "%s",
+ "MinSize": "0", "MaxSize": "0", "DesiredCapacity": "0",
+ "LaunchConfigurationName": {"Ref": "Lc"},
+ "VPCZoneIdentifier": [{"Ref": "Subnet"}]
+ }
+ },
+ "Tracking": {
+ "Type": "AWS::AutoScaling::ScalingPolicy",
+ "Properties": {
+ "AutoScalingGroupName": {"Ref": "Asg"},
+ "PolicyType": "TargetTrackingScaling",
+ "EstimatedInstanceWarmup": 120,
+ "TargetTrackingConfiguration": {
+ "PredefinedMetricSpecification": {"PredefinedMetricType": "ASGAverageCPUUtilization"},
+ "TargetValue": {"Ref": "TargetValue"}
+ }
+ }
+ },
+ "Simple": {
+ "Type": "AWS::AutoScaling::ScalingPolicy",
+ "Properties": {
+ "AutoScalingGroupName": {"Ref": "Asg"},
+ "AdjustmentType": "ChangeInCapacity",
+ "ScalingAdjustment": 1,
+ "Cooldown": {"Ref": "Cooldown"}
+ }
+ }
+ },
+ "Outputs": {
+ "TrackingRef": {"Value": {"Ref": "Tracking"}},
+ "TrackingArn": {"Value": {"Fn::GetAtt": ["Tracking", "Arn"]}},
+ "TrackingName": {"Value": {"Fn::GetAtt": ["Tracking", "PolicyName"]}},
+ "SimpleRef": {"Value": {"Ref": "Simple"}},
+ "SimpleName": {"Value": {"Fn::GetAtt": ["Simple", "PolicyName"]}}
+ }
+ }
+ """.formatted(ASG);
+
+ @Inject
+ AutoScalingService autoScalingService;
+
+ @Test
+ void createUpdateAndDeleteScalingPolicies() throws InterruptedException {
+ cloudFormation("CreateStack", Map.of("TargetValue", "50", "Cooldown", "60"));
+ String created = describeStacks("CREATE_COMPLETE");
+ String trackingArn = outputValue(created, "TrackingRef");
+ String trackingName = outputValue(created, "TrackingName");
+ String simpleArn = outputValue(created, "SimpleRef");
+ String simpleName = outputValue(created, "SimpleName");
+
+ // Ref and Fn::GetAtt Arn agree, and the name is CloudFormation-style, not a template property.
+ assertEquals(trackingArn, outputValue(created, "TrackingArn"));
+ assertTrue(trackingName.startsWith(STACK + "-Tracking-"), trackingName);
+ assertTrue(simpleName.startsWith(STACK + "-Simple-"), simpleName);
+ assertTrue(trackingArn.endsWith(":scalingPolicy:" + ASG + ":" + trackingName), trackingArn);
+
+ // Both policies are live on the group, with the values the template asked for.
+ describePolicies()
+ .body(containsString("<PolicyName>" + trackingName + "</PolicyName>"))
+ .body(containsString("<PolicyARN>" + simpleArn + "</PolicyARN>"))
+ .body(containsString("<PolicyType>TargetTrackingScaling</PolicyType>"))
+ .body(containsString("<Cooldown>60</Cooldown>"))
+ .body(containsString("<EstimatedInstanceWarmup>120</EstimatedInstanceWarmup>"));
+ assertEquals(50.0, tracking(trackingName).getTargetTrackingConfiguration().getTargetValue());
+ assertEquals("ASGAverageCPUUtilization",
+ tracking(trackingName).getTargetTrackingConfiguration().getPredefinedMetricSpecification()
+ .getPredefinedMetricType());
+
+ cloudFormation("UpdateStack", Map.of("TargetValue", "70", "Cooldown", "120"));
+ String updated = describeStacks("UPDATE_COMPLETE");
+
+ // Same names and ARNs, new values: the policies were rewritten, not replaced.
+ assertEquals(trackingArn, outputValue(updated, "TrackingRef"));
+ assertEquals(trackingName, outputValue(updated, "TrackingName"));
+ assertEquals(simpleArn, outputValue(updated, "SimpleRef"));
+ describePolicies()
+ .body(containsString("<Cooldown>120</Cooldown>"))
+ .body(not(containsString("<Cooldown>60</Cooldown>")));
+ assertEquals(70.0, tracking(trackingName).getTargetTrackingConfiguration().getTargetValue());
+ assertEquals(2, autoScalingService.describePolicies(REGION, ASG, null).size());
+
+ cloudFormation("DeleteStack", Map.of());
+ awaitStackDeleted();
+
+ assertEquals(List.of(), autoScalingService.describePolicies(REGION, null, List.of(trackingName, simpleName)));
+ }
+
+ private ScalingPolicy tracking(String name) {
+ return autoScalingService.describePolicies(REGION, ASG, List.of(name)).get(0);
+ }
+
+ private static void cloudFormation(String action, Map<String, String> parameters) {
+ RequestSpecification request = given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", CFN_AUTH)
+ .formParam("Action", action)
+ .formParam("StackName", STACK);
+ if (!"DeleteStack".equals(action)) {
+ request.formParam("TemplateBody", TEMPLATE);
+ }
+ int index = 1;
+ for (Map.Entry<String, String> parameter : parameters.entrySet()) {
+ request.formParam("Parameters.member." + index + ".ParameterKey", parameter.getKey());
+ request.formParam("Parameters.member." + index + ".ParameterValue", parameter.getValue());
+ index++;
+ }
+ request.when().post("/").then().statusCode(200);
+ }
+
+ private static String describeStacks(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();
+ }
+
+ /** DeleteStack runs asynchronously; a successful delete removes the stack entirely. */
+ private static void awaitStackDeleted() 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 String outputValue(String xml, String key) {
+ return XmlParser.extractPairs(xml, "Outputs", "OutputKey", "OutputValue").get(key);
+ }
+
+ private static ValidatableResponse describePolicies() {
+ return given()
+ .contentType("application/x-www-form-urlencoded")
+ .header("Authorization", ASG_AUTH)
+ .formParam("Action", "DescribePolicies")
+ .formParam("AutoScalingGroupName", ASG)
+ .when().post("/").then().statusCode(200);
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
index b388b32f41..a7eba52361 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CfnProvisionerFixture.java
@@ -26,6 +26,7 @@ import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewa
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayApiKeyCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayDomainCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingLifecycleHookCfnProvisioner;
+import io.github.hectorvent.floci.services.cloudformation.provisioners.AutoScalingScalingPolicyCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CdkMetadataCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CloudWatchCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.CognitoCfnProvisioner;
@@ -248,6 +249,7 @@ final class CfnProvisionerFixture {
}
if (autoScalingService != null) {
discovered.add(new AutoScalingLifecycleHookCfnProvisioner(autoScalingService));
+ discovered.add(new AutoScalingScalingPolicyCfnProvisioner(autoScalingService));
}
if (acmService != null) {
discovered.add(new AcmCfnProvisioner(acmService));
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingScalingPolicyCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingScalingPolicyCfnProvisionerTest.java
new file mode 100644
index 0000000000..000351fb54
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingScalingPolicyCfnProvisionerTest.java
@@ -0,0 +1,218 @@
+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.ObjectNode;
+import io.github.hectorvent.floci.core.common.AwsException;
+import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
+import io.github.hectorvent.floci.services.autoscaling.model.ScalingPolicy;
+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.List;
+
+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.anyInt;
+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.mock;
+import static org.mockito.Mockito.never;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/** The Auto Scaling policy CFN provisioner in isolation, against a mocked {@link AutoScalingService}. */
+class AutoScalingScalingPolicyCfnProvisionerTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String TYPE = "AWS::AutoScaling::ScalingPolicy";
+ private static final String ARN =
+ "arn:aws:autoscaling:us-east-1:000000000000:scalingPolicy:my-asg:my-stack-MyPolicy-abc";
+
+ private final AutoScalingService autoScaling = mock(AutoScalingService.class);
+ private final AutoScalingScalingPolicyCfnProvisioner provisioner =
+ new AutoScalingScalingPolicyCfnProvisioner(autoScaling);
+ private final ObjectMapper mapper = new ObjectMapper();
+
+ private ProvisionContext ctx() {
+ return ctx(null);
+ }
+
+ private ProvisionContext ctx(String priorPhysicalId) {
+ CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
+ when(engine.resolve(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ return node == null || node.isMissingNode() || node.isNull() ? null : node.asText();
+ });
+ when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
+ return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
+ }
+
+ private static StackResource resource(String priorPhysicalId, String priorPolicyName) {
+ return resource(priorPhysicalId, priorPolicyName, priorPolicyName == null ? null : "my-asg");
+ }
+
+ private static StackResource resource(String priorPhysicalId, String priorPolicyName, String priorAsgName) {
+ StackResource r = new StackResource();
+ r.setLogicalId("MyPolicy");
+ r.setResourceType(TYPE);
+ r.setPhysicalId(priorPhysicalId);
+ r.setAttributes(new HashMap<>());
+ if (priorPolicyName != null) {
+ r.getAttributes().put("PolicyName", priorPolicyName);
+ }
+ if (priorAsgName != null) {
+ r.getAttributes().put("AutoScalingGroupName", priorAsgName);
+ }
+ return r;
+ }
+
+ private static ScalingPolicy policy(String asgName, String name) {
+ ScalingPolicy policy = new ScalingPolicy();
+ policy.setAutoScalingGroupName(asgName);
+ policy.setPolicyName(name);
+ policy.setPolicyArn(ARN);
+ return policy;
+ }
+
+ @Test
+ void createSendsThePropertiesAndRecordsArnAndName() {
+ when(autoScaling.putScalingPolicy(eq(REGION), eq("my-asg"), anyString(), eq("SimpleScaling"),
+ eq("ChangeInCapacity"), eq(1), eq(60), eq(120), isNull()))
+ .thenReturn(policy("my-asg", "generated"));
+ ObjectNode props = mapper.createObjectNode()
+ .put("AutoScalingGroupName", "my-asg")
+ .put("PolicyType", "SimpleScaling")
+ .put("AdjustmentType", "ChangeInCapacity")
+ .put("ScalingAdjustment", 1)
+ .put("Cooldown", 60)
+ .put("EstimatedInstanceWarmup", 120);
+ StackResource r = resource(null, null);
+
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<String> name = ArgumentCaptor.forClass(String.class);
+ verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), name.capture(), eq("SimpleScaling"),
+ eq("ChangeInCapacity"), eq(1), eq(60), eq(120), isNull());
+ assertTrue(name.getValue().startsWith("my-stack-MyPolicy-"), name.getValue());
+ assertEquals(ARN, r.getPhysicalId());
+ assertEquals(ARN, r.getAttributes().get("Arn"));
+ assertEquals(name.getValue(), r.getAttributes().get("PolicyName"));
+ assertEquals("my-asg", r.getAttributes().get("AutoScalingGroupName"));
+ }
+
+ @Test
+ void omittedAdjustmentAndCooldownDefaultLikeTheQueryApi() {
+ when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
+ .thenReturn(policy("my-asg", "generated"));
+
+ provisioner.provision(resource(null, null), mapper.createObjectNode().put("AutoScalingGroupName", "my-asg"), ctx());
+
+ verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), anyString(), isNull(), isNull(),
+ eq(0), eq(300), isNull(), isNull());
+ }
+
+ @Test
+ void targetTrackingConfigurationIsParsed() {
+ when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
+ .thenReturn(policy("my-asg", "generated"));
+ ObjectNode props = mapper.createObjectNode()
+ .put("AutoScalingGroupName", "my-asg")
+ .put("PolicyType", "TargetTrackingScaling");
+ ObjectNode tracking = props.putObject("TargetTrackingConfiguration").put("TargetValue", 50.0);
+ tracking.putObject("PredefinedMetricSpecification").put("PredefinedMetricType", "ASGAverageCPUUtilization");
+
+ provisioner.provision(resource(null, null), props, ctx());
+
+ ArgumentCaptor<ScalingPolicy.TargetTrackingConfiguration> captor =
+ ArgumentCaptor.forClass(ScalingPolicy.TargetTrackingConfiguration.class);
+ verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), anyString(), eq("TargetTrackingScaling"),
+ isNull(), eq(0), eq(300), isNull(), captor.capture());
+ assertEquals(50.0, captor.getValue().getTargetValue());
+ assertEquals("ASGAverageCPUUtilization",
+ captor.getValue().getPredefinedMetricSpecification().getPredefinedMetricType());
+ }
+
+ @Test
+ void updateReusesTheRecordedNameOnTheSameGroup() {
+ when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
+ .thenReturn(policy("my-asg", "my-stack-MyPolicy-abc"));
+ StackResource r = resource(ARN, "my-stack-MyPolicy-abc");
+ ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "my-asg").put("Cooldown", 120);
+
+ provisioner.provision(r, props, ctx(ARN));
+
+ verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), eq("my-stack-MyPolicy-abc"), isNull(),
+ isNull(), eq(0), eq(120), isNull(), isNull());
+ // Identity comes from the recorded group, so no lookup is needed at all.
+ verify(autoScaling, never()).describePolicies(any(), any(), anyList());
+ assertEquals(ARN, r.getPhysicalId());
+ assertEquals("my-stack-MyPolicy-abc", r.getAttributes().get("PolicyName"));
+ }
+
+ @Test
+ void aMoveOntoAGroupThatAlreadyHasThatNameDoesNotOverwriteIt() {
+ // The destination group's own policy shares the name. Reading it as this resource would
+ // rewrite somebody else's policy and orphan the original.
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
+ resource(ARN, "my-stack-MyPolicy-abc", "my-asg"),
+ mapper.createObjectNode().put("AutoScalingGroupName", "other-asg"), ctx(ARN)));
+
+ assertTrue(e.getMessage().contains("AutoScalingGroupName"), e.getMessage());
+ verify(autoScaling, never()).putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any());
+ }
+
+ @Test
+ void anUpdateOfAResourceProvisionedBeforeTheGroupWasRecordedStillWorks() {
+ when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
+ .thenReturn(policy("my-asg", "my-stack-MyPolicy-abc"));
+
+ provisioner.provision(resource(ARN, "my-stack-MyPolicy-abc", null),
+ mapper.createObjectNode().put("AutoScalingGroupName", "my-asg"), ctx(ARN));
+
+ verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), eq("my-stack-MyPolicy-abc"), isNull(),
+ isNull(), eq(0), eq(300), isNull(), isNull());
+ }
+
+ @Test
+ void updateOfAPolicyGoneFromTheGroupRecreatesItUnderTheSameName() {
+ when(autoScaling.putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any()))
+ .thenReturn(policy("my-asg", "my-stack-MyPolicy-abc"));
+
+ provisioner.provision(resource(ARN, "my-stack-MyPolicy-abc"),
+ mapper.createObjectNode().put("AutoScalingGroupName", "my-asg"), ctx(ARN));
+
+ verify(autoScaling).putScalingPolicy(eq(REGION), eq("my-asg"), eq("my-stack-MyPolicy-abc"), isNull(),
+ isNull(), eq(0), eq(300), isNull(), isNull());
+ }
+
+ @Test
+ void movingThePolicyToAnotherGroupIsRefusedAsReplacementWorthy() {
+ AwsException e = assertThrows(AwsException.class, () -> provisioner.provision(
+ resource(ARN, "my-stack-MyPolicy-abc", "old-asg"),
+ mapper.createObjectNode().put("AutoScalingGroupName", "new-asg"), ctx(ARN)));
+
+ assertEquals("ValidationError", e.getErrorCode());
+ assertTrue(e.getMessage().contains("AutoScalingGroupName"), e.getMessage());
+ verify(autoScaling, never()).putScalingPolicy(any(), any(), any(), any(), any(), anyInt(), anyInt(), any(), any());
+ }
+
+ @Test
+ void deleteDelegatesByArn() {
+ provisioner.delete(TYPE, ARN, REGION);
+ verify(autoScaling).deletePolicy(REGION, null, ARN);
+ }
+
+ @Test
+ void deleteWithoutAPhysicalIdTouchesNothing() {
+ provisioner.delete(TYPE, null, REGION);
+ verify(autoScaling, never()).deletePolicy(any(), any(), any());
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 38e1d9f5aa..a50e733c9b 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -17,6 +17,7 @@ AWS::ApiGatewayV2::Stage LEGACY_SWITCH
AWS::AutoScaling::AutoScalingGroup LEGACY_SWITCH
AWS::AutoScaling::LaunchConfiguration LEGACY_SWITCH
AWS::AutoScaling::LifecycleHook AutoScalingLifecycleHookCfnProvisioner
+AWS::AutoScaling::ScalingPolicy AutoScalingScalingPolicyCfnProvisioner
AWS::Batch::ComputeEnvironment LEGACY_SWITCH
AWS::Batch::JobDefinition LEGACY_SWITCH
AWS::Batch::JobQueue LEGACY_SWITCH