Skip to content

armgit / floci

Public Imported from GitHub
0

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

refactor(cloudformation): move the AutoScaling types into a per-service provisioner (#3582)

Hector Ventura0f7df0fd1938
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
index 5ad75ac239..1e4659b23a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationResourceProvisioner.java
@@ -34,11 +34,6 @@ import io.github.hectorvent.floci.services.ecr.model.Repository;
import io.github.hectorvent.floci.services.cloudwatch.logs.CloudWatchLogsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.CloudWatchMetricsService;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.Dimension;
-import io.github.hectorvent.floci.services.autoscaling.AutoScalingService;
-import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields;
-import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
-import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
-import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;
import io.github.hectorvent.floci.services.cloudwatch.metrics.model.MetricAlarm;
import io.github.hectorvent.floci.services.ec2.model.IpPermission;
import io.github.hectorvent.floci.services.ec2.model.IpRange;
@@ -178,8 +173,6 @@ public class CloudFormationResourceProvisioner {
"AWS::ApiGatewayV2::Integration",
"AWS::ApiGatewayV2::Route",
"AWS::ApiGatewayV2::Stage",
- "AWS::AutoScaling::AutoScalingGroup",
- "AWS::AutoScaling::LaunchConfiguration",
"AWS::CloudFormation::CustomResource",
"AWS::CloudFront::Distribution",
"AWS::DynamoDB::GlobalTable",
@@ -221,7 +214,6 @@ public class CloudFormationResourceProvisioner {
private final StepFunctionsService stepFunctionsService;
private final Ec2Service ec2Service;
private final EksService eksService;
- private final AutoScalingService autoScalingService;
private final CloudFrontService cloudFrontService;
// Item 15 decomposition: extracted per-service provisioners are consulted before the switch
// below. As types migrate, their switch cases and provisionXxx methods are removed here; the
@@ -249,7 +241,6 @@ public class CloudFormationResourceProvisioner {
CloudWatchLogsService logsService,
KinesisService kinesisService,
CloudWatchMetricsService cloudWatchMetricsService,
- AutoScalingService autoScalingService,
FirehoseService firehoseService,
CloudFrontService cloudFrontService,
CloudFormationResourceRegistry resourceRegistry,
@@ -269,7 +260,6 @@ public class CloudFormationResourceProvisioner {
this.stepFunctionsService = stepFunctionsService;
this.ec2Service = ec2Service;
this.eksService = eksService;
- this.autoScalingService = autoScalingService;
this.cloudFrontService = cloudFrontService;
this.resourceRegistry = resourceRegistry;
this.dynamicReferences = dynamicReferences;
@@ -357,10 +347,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::EC2::Instance" -> provisionEc2Instance(resource, properties, engine, region);
case "AWS::EKS::Cluster" -> provisionEksCluster(resource, properties, engine, stackName);
case "AWS::EKS::Nodegroup" -> provisionEksNodegroup(resource, properties, engine, stackName);
- case "AWS::AutoScaling::LaunchConfiguration" ->
- provisionLaunchConfiguration(resource, properties, engine, region, stackName);
- case "AWS::AutoScaling::AutoScalingGroup" ->
- provisionAutoScalingGroup(resource, properties, engine, region, stackName);
case "AWS::CloudFront::Distribution" ->
provisionCloudFrontDistribution(resource, properties, engine);
default -> {
@@ -587,10 +573,6 @@ public class CloudFormationResourceProvisioner {
case "AWS::EC2::SecurityGroup" -> ec2Service.deleteSecurityGroup(region, physicalId);
case "AWS::EC2::Instance" -> ec2Service.terminateInstances(region, List.of(physicalId));
case "AWS::EKS::Cluster" -> eksService.deleteCluster(physicalId);
- case "AWS::AutoScaling::LaunchConfiguration" ->
- autoScalingService.deleteLaunchConfiguration(region, physicalId);
- case "AWS::AutoScaling::AutoScalingGroup" ->
- autoScalingService.deleteAutoScalingGroup(region, physicalId, true);
case "AWS::CloudFront::Distribution" -> cloudFrontService.removeDistribution(physicalId);
// Warn for the same reason the create path does: the delete reports success over a
// type nothing here removes, and at debug that is invisible at the default log level.
@@ -721,227 +703,11 @@ public class CloudFormationResourceProvisioner {
// ── Auto Scaling ────────────────────────────────────────────────────────────
- private void provisionLaunchConfiguration(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String explicitName = resolveOptional(props, "LaunchConfigurationName", engine);
- String priorPhysicalId = r.getPhysicalId();
- String name;
- if (explicitName != null && !explicitName.isBlank()) {
- name = explicitName;
- } else if (priorPhysicalId != null) {
- name = priorPhysicalId;
- } else {
- name = generatePhysicalName(stackName, r.getLogicalId(), 255, false);
- }
- // Launch configurations have no update API on real AWS at all (any property change replaces
- // the resource), so provision() being re-invoked on every UpdateStack means a same-named one
- // already on file must be left alone rather than re-created (createLaunchConfiguration throws
- // AlreadyExists).
- LaunchConfiguration lc = sameNameExistingResource(priorPhysicalId, name,
- n -> requireLaunchConfiguration(region, n));
- if (lc == null) {
- String associatePublicIp = resolveOptional(props, "AssociatePublicIpAddress", engine);
- lc = autoScalingService.createLaunchConfiguration(region, name,
- resolveOptional(props, "InstanceId", engine),
- resolveOptional(props, "ImageId", engine),
- resolveOptional(props, "InstanceType", engine),
- resolveOptional(props, "KeyName", engine),
- resolveStringList(props, "SecurityGroups", engine),
- resolveOptional(props, "UserData", engine),
- resolveOptional(props, "IamInstanceProfile", engine),
- // Absent in the template means the subnet default applies, so
- // it stays null rather than collapsing to false.
- associatePublicIp == null || associatePublicIp.isBlank()
- ? null
- : Boolean.parseBoolean(associatePublicIp));
- deleteRenamedResource(priorPhysicalId, name, n -> autoScalingService.deleteLaunchConfiguration(region, n),
- "launch configuration");
- }
- // Ref returns the launch configuration name.
- r.setPhysicalId(name);
- r.getAttributes().put("Arn", lc.getLaunchConfigurationArn());
- }
-
- private LaunchConfiguration requireLaunchConfiguration(String region, String name) {
- List<LaunchConfiguration> found = autoScalingService.describeLaunchConfigurations(region, List.of(name));
- if (found.isEmpty()) {
- throw new AwsException("ValidationError", "Launch configuration '" + name + "' not found.", 400);
- }
- return found.getFirst();
- }
-
- private void provisionAutoScalingGroup(StackResource r, JsonNode props, CloudFormationTemplateEngine engine,
- String region, String stackName) {
- String explicitName = resolveOptional(props, "AutoScalingGroupName", engine);
- String priorPhysicalId = r.getPhysicalId();
- String name;
- if (explicitName != null && !explicitName.isBlank()) {
- name = explicitName;
- } else if (priorPhysicalId != null) {
- name = priorPhysicalId;
- } else {
- name = generatePhysicalName(stackName, r.getLogicalId(), 255, false);
- }
- String launchConfigName = resolveOptional(props, "LaunchConfigurationName", engine);
- String launchTemplateId = null;
- String launchTemplateName = null;
- String launchTemplateVersion = null;
- if (props != null && props.has("LaunchTemplate")) {
- JsonNode lt = props.get("LaunchTemplate");
- // Id and name are distinct lookup keys in Auto Scaling: passing an lt- id in the name slot
- // never matches a stored template.
- launchTemplateId = engine.resolve(lt.path("LaunchTemplateId"));
- launchTemplateName = engine.resolve(lt.path("LaunchTemplateName"));
- launchTemplateVersion = engine.resolve(lt.path("Version"));
- }
- MixedInstancesPolicy mixedInstancesPolicy = resolveMixedInstancesPolicy(props, engine);
- int minSize = parseIntProp(props, "MinSize", engine, 0);
- int maxSize = parseIntProp(props, "MaxSize", engine, 0);
- int desiredCapacity = parseIntProp(props, "DesiredCapacity", engine, 0);
- int cooldown = parseIntProp(props, "Cooldown", engine, 0);
- List<String> availabilityZones = resolveStringList(props, "AvailabilityZones", engine);
- List<String> subnetIds = resolveStringList(props, "VPCZoneIdentifier", engine);
- String healthCheckType = resolveOptional(props, "HealthCheckType", engine);
- int healthCheckGracePeriod = parseIntProp(props, "HealthCheckGracePeriod", engine, 0);
- List<String> terminationPolicies = resolveStringList(props, "TerminationPolicies", engine);
-
- // provision() re-runs on every UpdateStack, so a same-named group already on file must be
- // reconciled via UpdateAutoScalingGroup instead of re-created (createAutoScalingGroup throws
- // AlreadyExists). TargetGroupARNs/LoadBalancerNames/Tags aren't reconciled here: they need
- // their own attach/detach and tagging APIs that updateAutoScalingGroup doesn't cover.
- AutoScalingGroup existing = sameNameExistingResource(priorPhysicalId, name,
- n -> requireAutoScalingGroup(region, n));
- AutoScalingGroup asg;
- if (existing != null) {
- autoScalingService.updateAutoScalingGroup(region, name,
- blankToNull(launchConfigName),
- blankToNull(launchTemplateId), blankToNull(launchTemplateName), blankToNull(launchTemplateVersion),
- mixedInstancesPolicy, minSize, maxSize, desiredCapacity, cooldown,
- availabilityZones, subnetIds, healthCheckType, healthCheckGracePeriod, terminationPolicies,
- AsgOptionalFields.none());
- asg = requireAutoScalingGroup(region, name);
- } else {
- asg = autoScalingService.createAutoScalingGroup(region, name,
- blankToNull(launchConfigName),
- blankToNull(launchTemplateId), blankToNull(launchTemplateName), blankToNull(launchTemplateVersion),
- mixedInstancesPolicy, minSize, maxSize, desiredCapacity, cooldown,
- availabilityZones, subnetIds,
- resolveStringList(props, "TargetGroupARNs", engine),
- resolveStringList(props, "LoadBalancerNames", engine),
- healthCheckType, healthCheckGracePeriod, terminationPolicies,
- resolveAsgTags(props, engine),
- resolveAsgTagPropagation(props, engine),
- AsgOptionalFields.none());
- deleteRenamedResource(priorPhysicalId, name, n -> autoScalingService.deleteAutoScalingGroup(region, n, true),
- "Auto Scaling group");
- }
- // Ref returns the Auto Scaling group name; Fn::GetAtt Arn returns the ASG ARN.
- r.setPhysicalId(name);
- r.getAttributes().put("Arn", asg.getAutoScalingGroupArn());
- }
- private AutoScalingGroup requireAutoScalingGroup(String region, String name) {
- List<AutoScalingGroup> found = autoScalingService.describeAutoScalingGroups(region, List.of(name));
- if (found.isEmpty()) {
- throw new AwsException("ValidationError", "Auto Scaling group '" + name + "' not found.", 400);
- }
- return found.getFirst();
- }
- /**
- * Builds the {@code MixedInstancesPolicy} of an Auto Scaling group from template properties, in the
- * same shape the Query API parser produces. Returns {@code null} when the property is absent, so
- * that the group falls back to its {@code LaunchTemplate} or {@code LaunchConfigurationName}.
- */
- private MixedInstancesPolicy resolveMixedInstancesPolicy(JsonNode props,
- CloudFormationTemplateEngine engine) {
- if (props == null || !props.has("MixedInstancesPolicy") || props.get("MixedInstancesPolicy").isNull()) {
- return null;
- }
- JsonNode policyNode = props.get("MixedInstancesPolicy");
- MixedInstancesPolicy policy = new MixedInstancesPolicy();
-
- JsonNode launchTemplateNode = policyNode.path("LaunchTemplate");
- if (launchTemplateNode.isObject()) {
- MixedInstancesPolicy.LaunchTemplate launchTemplate = new MixedInstancesPolicy.LaunchTemplate();
- JsonNode specNode = launchTemplateNode.path("LaunchTemplateSpecification");
- if (specNode.isObject()) {
- var specification = new MixedInstancesPolicy.LaunchTemplateSpecification();
- specification.setLaunchTemplateId(blankToNull(engine.resolve(specNode.path("LaunchTemplateId"))));
- specification.setLaunchTemplateName(blankToNull(engine.resolve(specNode.path("LaunchTemplateName"))));
- specification.setVersion(blankToNull(engine.resolve(specNode.path("Version"))));
- launchTemplate.setLaunchTemplateSpecification(specification);
- }
- for (JsonNode overrideNode : launchTemplateNode.path("Overrides")) {
- String instanceType = engine.resolve(overrideNode.path("InstanceType"));
- if (instanceType != null && !instanceType.isBlank()) {
- var override = new MixedInstancesPolicy.LaunchTemplateOverride();
- override.setInstanceType(instanceType);
- launchTemplate.getOverrides().add(override);
- }
- }
- policy.setLaunchTemplate(launchTemplate);
- }
- JsonNode distributionNode = policyNode.path("InstancesDistribution");
- if (distributionNode.isObject()) {
- var distribution = new MixedInstancesPolicy.InstancesDistribution();
- distribution.setOnDemandBaseCapacity(parseOptionalInt("OnDemandBaseCapacity",
- engine.resolve(distributionNode.path("OnDemandBaseCapacity"))));
- distribution.setOnDemandPercentageAboveBaseCapacity(
- parseOptionalInt("OnDemandPercentageAboveBaseCapacity",
- engine.resolve(distributionNode.path("OnDemandPercentageAboveBaseCapacity"))));
- distribution.setSpotAllocationStrategy(
- blankToNull(engine.resolve(distributionNode.path("SpotAllocationStrategy"))));
- policy.setInstancesDistribution(distribution);
- }
- return policy;
- }
- /**
- * Reads an optional integer property. A value that is present but not a number is a template
- * error, and AWS rejects it rather than treating it as absent.
- */
- private Integer parseOptionalInt(String field, String value) {
- if (value == null || value.isBlank()) {
- return null;
- }
- try {
- return Integer.valueOf(value.trim());
- } catch (NumberFormatException e) {
- throw new AwsException("ValidationError",
- "Value of property " + field + " must be an integer.", 400);
- }
- }
-
- private Map<String, String> resolveAsgTags(JsonNode props, CloudFormationTemplateEngine engine) {
- Map<String, String> tags = new LinkedHashMap<>();
- JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
- if (tagsNode != null && tagsNode.isArray()) {
- for (JsonNode tag : tagsNode) {
- String key = engine.resolve(tag.path("Key"));
- if (!key.isEmpty()) {
- tags.put(key, engine.resolve(tag.path("Value")));
- }
- }
- }
- return tags;
- }
-
- private Map<String, Boolean> resolveAsgTagPropagation(JsonNode props, CloudFormationTemplateEngine engine) {
- Map<String, Boolean> propagation = new LinkedHashMap<>();
- JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
- if (tagsNode != null && tagsNode.isArray()) {
- for (JsonNode tag : tagsNode) {
- String key = engine.resolve(tag.path("Key"));
- if (!key.isEmpty()) {
- propagation.put(key, Boolean.parseBoolean(engine.resolve(tag.path("PropagateAtLaunch"))));
- }
- }
- }
- return propagation;
- }
private List<String> resolveStringList(JsonNode props, String field, CloudFormationTemplateEngine engine) {
if (props == null || !props.has(field)) {
@@ -1161,58 +927,6 @@ public class CloudFormationResourceProvisioner {
}
}
- /**
- * Looks up {@code name} via {@code lookup} when this is an update re-invocation for the same
- * physical resource (i.e. {@code priorPhysicalId} is set and unchanged), returning {@code null}
- * either when this is a fresh create, a rename (handled as a replacement by the caller), or the
- * resource is missing on the backend despite the stack still remembering a physical id (e.g. it
- * was deleted out of band; the caller then falls back to creating it fresh).
- */
- private <T> T sameNameExistingResource(String priorPhysicalId, String name, java.util.function.Function<String, T> lookup) {
- if (priorPhysicalId == null || !priorPhysicalId.equals(name)) {
- return null;
- }
- try {
- return lookup.apply(name);
- } catch (AwsException notFound) {
- // Expected when the resource was deleted out of band since the prior update; the
- // caller falls back to creating it fresh under the same name.
- LOG.debugv(notFound, "No existing {0} found on file, falling back to create", name);
- return null;
- }
- }
-
- /**
- * Best-effort cleanup of the previous physical resource after a rename forced a fresh create
- * under the new name (mirrors provisionLogGroup's create-new-then-delete-old handling). Failures
- * are logged, not thrown: the new resource was already created successfully, so surfacing a
- * delete failure here would report the update as failed despite the stack now being in a usable
- * (if slightly leaky) state.
- */
- private void deleteRenamedResource(String priorPhysicalId, String newName, java.util.function.Consumer<String> delete,
- String resourceKind) {
- if (priorPhysicalId == null || priorPhysicalId.equals(newName)) {
- return;
- }
- try {
- delete.accept(priorPhysicalId);
- } catch (RuntimeException e) {
- LOG.warnv(e, "Failed to delete renamed {0} {1} after replacement by {2}",
- resourceKind, priorPhysicalId, newName);
- }
- }
-
- private int parseIntProp(JsonNode props, String name, CloudFormationTemplateEngine engine, int fallback) {
- String value = resolveOptional(props, name, engine);
- if (value == null || value.isBlank()) {
- return fallback;
- }
- try {
- return Integer.parseInt(value.trim());
- } catch (NumberFormatException e) {
- return fallback;
- }
- }
// ── EKS ─────────────────────────────────────────────────────────────────────
diff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java
new file mode 100644
index 0000000000..22ef0c0a15
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisioner.java
@@ -0,0 +1,366 @@
+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.AsgOptionalFields;
+import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
+import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
+import io.github.hectorvent.floci.services.autoscaling.model.MixedInstancesPolicy;
+import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
+import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Consumer;
+import java.util.function.Function;
+
+/**
+ * Provisions {@code AWS::AutoScaling::AutoScalingGroup} and
+ * {@code AWS::AutoScaling::LaunchConfiguration}.
+ *
+ * <p>Extracted from {@code CloudFormationResourceProvisioner}. The two types share a provisioner
+ * because they share {@code AutoScalingService} and because a group names a launch configuration:
+ * splitting them would put the same service behind two classes for no gain. The per-type
+ * siblings {@link AutoScalingLifecycleHookCfnProvisioner} and
+ * {@link AutoScalingScalingPolicyCfnProvisioner} stay separate: they attach to a group rather
+ * than being one.
+ *
+ * <p>Both types delete by physical id alone, so the id-only delete override serves them and
+ * neither is in the engine's {@code DELETE_NEEDS_STACK_RESOURCE} set.
+ */
+@ApplicationScoped
+public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
+
+ private static final String GROUP = "AWS::AutoScaling::AutoScalingGroup";
+
+ private static final String LAUNCH_CONFIGURATION = "AWS::AutoScaling::LaunchConfiguration";
+
+ private static final Logger LOG = Logger.getLogger(AutoScalingGroupCfnProvisioner.class);
+
+ private final AutoScalingService autoScalingService;
+
+ @Inject
+ public AutoScalingGroupCfnProvisioner(AutoScalingService autoScalingService) {
+ this.autoScalingService = autoScalingService;
+ }
+
+ @Override
+ public Set<String> resourceTypes() {
+ return Set.of(GROUP, LAUNCH_CONFIGURATION);
+ }
+
+ @Override
+ public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
+ switch (r.getResourceType()) {
+ case LAUNCH_CONFIGURATION -> provisionLaunchConfiguration(r, props, ctx);
+ case GROUP -> provisionAutoScalingGroup(r, props, ctx);
+ default -> throw unsupported(r.getResourceType());
+ }
+ }
+
+ @Override
+ public void delete(String resourceType, String physicalId, String region) {
+ switch (resourceType) {
+ case LAUNCH_CONFIGURATION -> autoScalingService.deleteLaunchConfiguration(region, physicalId);
+ case GROUP -> autoScalingService.deleteAutoScalingGroup(region, physicalId, true);
+ default -> throw unsupported(resourceType);
+ }
+ }
+
+ private static IllegalStateException unsupported(String resourceType) {
+ return new IllegalStateException(
+ "AutoScalingGroupCfnProvisioner received an unsupported type: " + resourceType);
+ }
+
+ private void provisionLaunchConfiguration(StackResource r, JsonNode props, ProvisionContext ctx) {
+ String region = ctx.region();
+ String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "LaunchConfigurationName"),
+ r.getLogicalId(), 255, false);
+
+ // Launch configurations have no update API on real AWS at all (any property change replaces
+ // the resource), so provision() being re-invoked on every UpdateStack means a same-named one
+ // already on file must be left alone rather than re-created (createLaunchConfiguration throws
+ // AlreadyExists).
+ LaunchConfiguration lc = existingEntity(ctx, name, n -> requireLaunchConfiguration(region, n));
+ if (lc == null) {
+ String associatePublicIp = ctx.resolveOptional(props, "AssociatePublicIpAddress");
+ lc = autoScalingService.createLaunchConfiguration(region, name,
+ ctx.resolveOptional(props, "InstanceId"),
+ ctx.resolveOptional(props, "ImageId"),
+ ctx.resolveOptional(props, "InstanceType"),
+ ctx.resolveOptional(props, "KeyName"),
+ ctx.resolveStringList(props, "SecurityGroups"),
+ ctx.resolveOptional(props, "UserData"),
+ ctx.resolveOptional(props, "IamInstanceProfile"),
+ // Absent in the template means the subnet default applies, so
+ // it stays null rather than collapsing to false.
+ associatePublicIp == null || associatePublicIp.isBlank()
+ ? null
+ : Boolean.parseBoolean(associatePublicIp));
+ deleteRenamedResource(ctx, name, n -> autoScalingService.deleteLaunchConfiguration(region, n),
+ "launch configuration");
+ }
+ // Ref returns the launch configuration name.
+ r.setPhysicalId(name);
+ r.getAttributes().put("Arn", lc.getLaunchConfigurationArn());
+ }
+
+ private LaunchConfiguration requireLaunchConfiguration(String region, String name) {
+ List<LaunchConfiguration> found = autoScalingService.describeLaunchConfigurations(region, List.of(name));
+ if (found.isEmpty()) {
+ throw new AwsException("ValidationError", "Launch configuration '" + name + "' not found.", 400);
+ }
+ return found.getFirst();
+ }
+
+ private void provisionAutoScalingGroup(StackResource r, JsonNode props, ProvisionContext ctx) {
+ CloudFormationTemplateEngine engine = ctx.engine();
+ String region = ctx.region();
+ String name = ctx.stablePhysicalName(ctx.resolveOptional(props, "AutoScalingGroupName"),
+ r.getLogicalId(), 255, false);
+ String launchConfigName = ctx.resolveOptional(props, "LaunchConfigurationName");
+ String launchTemplateId = null;
+ String launchTemplateName = null;
+ String launchTemplateVersion = null;
+ if (props != null && props.has("LaunchTemplate")) {
+ JsonNode lt = props.get("LaunchTemplate");
+ // Id and name are distinct lookup keys in Auto Scaling: passing an lt- id in the name slot
+ // never matches a stored template.
+ launchTemplateId = engine.resolve(lt.path("LaunchTemplateId"));
+ launchTemplateName = engine.resolve(lt.path("LaunchTemplateName"));
+ launchTemplateVersion = engine.resolve(lt.path("Version"));
+ }
+ MixedInstancesPolicy mixedInstancesPolicy = resolveMixedInstancesPolicy(props, engine);
+ int minSize = parseIntProp(props, "MinSize", ctx, 0);
+ int maxSize = parseIntProp(props, "MaxSize", ctx, 0);
+ int desiredCapacity = parseIntProp(props, "DesiredCapacity", ctx, 0);
+ int cooldown = parseIntProp(props, "Cooldown", ctx, 0);
+ List<String> availabilityZones = ctx.resolveStringList(props, "AvailabilityZones");
+ List<String> subnetIds = ctx.resolveStringList(props, "VPCZoneIdentifier");
+ String healthCheckType = ctx.resolveOptional(props, "HealthCheckType");
+ int healthCheckGracePeriod = parseIntProp(props, "HealthCheckGracePeriod", ctx, 0);
+ List<String> terminationPolicies = ctx.resolveStringList(props, "TerminationPolicies");
+ AsgOptionalFields optionalFields = resolveOptionalFields(props, ctx);
+
+ // provision() re-runs on every UpdateStack, so a same-named group already on file must be
+ // reconciled via UpdateAutoScalingGroup instead of re-created (createAutoScalingGroup throws
+ // AlreadyExists). TargetGroupARNs/LoadBalancerNames/Tags aren't reconciled here: they need
+ // their own attach/detach and tagging APIs that updateAutoScalingGroup doesn't cover.
+ AutoScalingGroup existing = existingEntity(ctx, name, n -> requireAutoScalingGroup(region, n));
+ AutoScalingGroup asg;
+ if (existing != null) {
+ autoScalingService.updateAutoScalingGroup(region, name,
+ blankToNull(launchConfigName),
+ blankToNull(launchTemplateId), blankToNull(launchTemplateName), blankToNull(launchTemplateVersion),
+ mixedInstancesPolicy, minSize, maxSize, desiredCapacity, cooldown,
+ availabilityZones, subnetIds, healthCheckType, healthCheckGracePeriod, terminationPolicies,
+ optionalFields);
+ asg = requireAutoScalingGroup(region, name);
+ } else {
+ asg = autoScalingService.createAutoScalingGroup(region, name,
+ blankToNull(launchConfigName),
+ blankToNull(launchTemplateId), blankToNull(launchTemplateName), blankToNull(launchTemplateVersion),
+ mixedInstancesPolicy, minSize, maxSize, desiredCapacity, cooldown,
+ availabilityZones, subnetIds,
+ ctx.resolveStringList(props, "TargetGroupARNs"),
+ ctx.resolveStringList(props, "LoadBalancerNames"),
+ healthCheckType, healthCheckGracePeriod, terminationPolicies,
+ resolveAsgTags(props, engine),
+ resolveAsgTagPropagation(props, engine),
+ optionalFields);
+ deleteRenamedResource(ctx, name, n -> autoScalingService.deleteAutoScalingGroup(region, n, true),
+ "Auto Scaling group");
+ }
+ // Ref returns the Auto Scaling group name.
+ r.setPhysicalId(name);
+ // AutoScalingGroupARN is the schema's only readOnlyProperty, so it is the attribute real
+ // CloudFormation resolves. Arn is kept beside it because templates and tests here already
+ // read that name, and dropping it would break them for no gain.
+ r.getAttributes().put("AutoScalingGroupARN", asg.getAutoScalingGroupArn());
+ r.getAttributes().put("Arn", asg.getAutoScalingGroupArn());
+ }
+
+ private AutoScalingGroup requireAutoScalingGroup(String region, String name) {
+ List<AutoScalingGroup> found = autoScalingService.describeAutoScalingGroups(region, List.of(name));
+ if (found.isEmpty()) {
+ throw new AwsException("ValidationError", "Auto Scaling group '" + name + "' not found.", 400);
+ }
+ return found.getFirst();
+ }
+
+ /**
+ * The four group properties the schema defines that the CloudFormation path used to drop,
+ * passing {@code AsgOptionalFields.none()} instead. Absent stays null so an update overwrites
+ * only what the template set, which is what {@code AsgOptionalFields.applyToExistingGroup} and
+ * the Query handler's {@code UpdateAutoScalingGroup} both do.
+ */
+ private AsgOptionalFields resolveOptionalFields(JsonNode props, ProvisionContext ctx) {
+ String capacityRebalance = ctx.resolveOptional(props, "CapacityRebalance");
+ return new AsgOptionalFields(
+ blankToNull(ctx.resolveOptional(props, "DesiredCapacityType")),
+ capacityRebalance == null || capacityRebalance.isBlank()
+ ? null
+ : Boolean.parseBoolean(capacityRebalance),
+ parseOptionalInt("MaxInstanceLifetime", ctx.resolveOptional(props, "MaxInstanceLifetime")),
+ parseOptionalInt("DefaultInstanceWarmup", ctx.resolveOptional(props, "DefaultInstanceWarmup")));
+ }
+
+ /**
+ * Builds the {@code MixedInstancesPolicy} of an Auto Scaling group from template properties, in the
+ * same shape the Query API parser produces. Returns {@code null} when the property is absent, so
+ * that the group falls back to its {@code LaunchTemplate} or {@code LaunchConfigurationName}.
+ */
+ private MixedInstancesPolicy resolveMixedInstancesPolicy(JsonNode props,
+ CloudFormationTemplateEngine engine) {
+ if (props == null || !props.has("MixedInstancesPolicy") || props.get("MixedInstancesPolicy").isNull()) {
+ return null;
+ }
+ JsonNode policyNode = props.get("MixedInstancesPolicy");
+ MixedInstancesPolicy policy = new MixedInstancesPolicy();
+
+ JsonNode launchTemplateNode = policyNode.path("LaunchTemplate");
+ if (launchTemplateNode.isObject()) {
+ MixedInstancesPolicy.LaunchTemplate launchTemplate = new MixedInstancesPolicy.LaunchTemplate();
+ JsonNode specNode = launchTemplateNode.path("LaunchTemplateSpecification");
+ if (specNode.isObject()) {
+ MixedInstancesPolicy.LaunchTemplateSpecification specification =
+ new MixedInstancesPolicy.LaunchTemplateSpecification();
+ specification.setLaunchTemplateId(blankToNull(engine.resolve(specNode.path("LaunchTemplateId"))));
+ specification.setLaunchTemplateName(blankToNull(engine.resolve(specNode.path("LaunchTemplateName"))));
+ specification.setVersion(blankToNull(engine.resolve(specNode.path("Version"))));
+ launchTemplate.setLaunchTemplateSpecification(specification);
+ }
+ for (JsonNode overrideNode : launchTemplateNode.path("Overrides")) {
+ String instanceType = engine.resolve(overrideNode.path("InstanceType"));
+ if (instanceType != null && !instanceType.isBlank()) {
+ MixedInstancesPolicy.LaunchTemplateOverride override =
+ new MixedInstancesPolicy.LaunchTemplateOverride();
+ override.setInstanceType(instanceType);
+ launchTemplate.getOverrides().add(override);
+ }
+ }
+ policy.setLaunchTemplate(launchTemplate);
+ }
+
+ JsonNode distributionNode = policyNode.path("InstancesDistribution");
+ if (distributionNode.isObject()) {
+ MixedInstancesPolicy.InstancesDistribution distribution =
+ new MixedInstancesPolicy.InstancesDistribution();
+ distribution.setOnDemandBaseCapacity(parseOptionalInt("OnDemandBaseCapacity",
+ engine.resolve(distributionNode.path("OnDemandBaseCapacity"))));
+ distribution.setOnDemandPercentageAboveBaseCapacity(
+ parseOptionalInt("OnDemandPercentageAboveBaseCapacity",
+ engine.resolve(distributionNode.path("OnDemandPercentageAboveBaseCapacity"))));
+ distribution.setSpotAllocationStrategy(
+ blankToNull(engine.resolve(distributionNode.path("SpotAllocationStrategy"))));
+ policy.setInstancesDistribution(distribution);
+ }
+ return policy;
+ }
+
+ /**
+ * Reads an optional integer property. A value that is present but not a number is a template
+ * error, and AWS rejects it rather than treating it as absent.
+ */
+ private Integer parseOptionalInt(String field, String value) {
+ if (value == null || value.isBlank()) {
+ return null;
+ }
+ try {
+ return Integer.valueOf(value.trim());
+ } catch (NumberFormatException e) {
+ throw new AwsException("ValidationError",
+ "Value of property " + field + " must be an integer.", 400);
+ }
+ }
+
+ private int parseIntProp(JsonNode props, String name, ProvisionContext ctx, int fallback) {
+ String value = ctx.resolveOptional(props, name);
+ if (value == null || value.isBlank()) {
+ return fallback;
+ }
+ try {
+ return Integer.parseInt(value.trim());
+ } catch (NumberFormatException e) {
+ return fallback;
+ }
+ }
+
+ private Map<String, String> resolveAsgTags(JsonNode props, CloudFormationTemplateEngine engine) {
+ Map<String, String> tags = new LinkedHashMap<>();
+ JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
+ if (tagsNode != null && tagsNode.isArray()) {
+ for (JsonNode tag : tagsNode) {
+ String key = engine.resolve(tag.path("Key"));
+ if (!key.isEmpty()) {
+ tags.put(key, engine.resolve(tag.path("Value")));
+ }
+ }
+ }
+ return tags;
+ }
+
+ private Map<String, Boolean> resolveAsgTagPropagation(JsonNode props, CloudFormationTemplateEngine engine) {
+ Map<String, Boolean> propagation = new LinkedHashMap<>();
+ JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
+ if (tagsNode != null && tagsNode.isArray()) {
+ for (JsonNode tag : tagsNode) {
+ String key = engine.resolve(tag.path("Key"));
+ if (!key.isEmpty()) {
+ propagation.put(key, Boolean.parseBoolean(engine.resolve(tag.path("PropagateAtLaunch"))));
+ }
+ }
+ }
+ return propagation;
+ }
+
+ /**
+ * Looks up {@code name} when this is an update re-invocation for the same physical entity,
+ * returning {@code null} on a fresh create, on a rename (which the caller handles as a
+ * replacement), or when the entity is missing on the backend despite the stack still
+ * remembering a physical id, for instance because it was deleted out of band.
+ */
+ private <T> T existingEntity(ProvisionContext ctx, String name, Function<String, T> lookup) {
+ if (!ctx.reusesPriorEntity(name)) {
+ return null;
+ }
+ try {
+ return lookup.apply(name);
+ } catch (AwsException notFound) {
+ // Expected when the resource was deleted out of band since the prior update; the
+ // caller falls back to creating it fresh under the same name.
+ LOG.debugv(notFound, "No existing {0} found on file, falling back to create", name);
+ return null;
+ }
+ }
+
+ /**
+ * Best-effort cleanup of the previous physical entity after a rename forced a fresh create under
+ * the new name. Failures are logged, not thrown: the new entity was already created, so
+ * surfacing a delete failure here would report the update as failed despite the stack now being
+ * in a usable, if slightly leaky, state.
+ */
+ private void deleteRenamedResource(ProvisionContext ctx, String newName, Consumer<String> delete,
+ String resourceKind) {
+ String priorPhysicalId = ctx.priorPhysicalId();
+ if (priorPhysicalId == null || priorPhysicalId.equals(newName)) {
+ return;
+ }
+ try {
+ delete.accept(priorPhysicalId);
+ } catch (RuntimeException e) {
+ LOG.warnv(e, "Failed to delete renamed {0} {1} after replacement by {2}",
+ resourceKind, priorPhysicalId, newName);
+ }
+ }
+
+ private String blankToNull(String value) {
+ return (value == null || value.isBlank()) ? null : value;
+ }
+}
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 4d81ab4c62..98e677042b 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
@@ -29,6 +29,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.ApiGatewayUsagePlanCfnProvisioner;
import io.github.hectorvent.floci.services.cloudformation.provisioners.ApiGatewayDomainCfnProvisioner;
+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;
import io.github.hectorvent.floci.services.cloudformation.provisioners.BackupVaultCfnProvisioner;
@@ -284,6 +285,7 @@ final class CfnProvisionerFixture {
discovered.add(new ApiGatewayDomainCfnProvisioner(apiGatewayService));
}
if (autoScalingService != null) {
+ discovered.add(new AutoScalingGroupCfnProvisioner(autoScalingService));
discovered.add(new AutoScalingLifecycleHookCfnProvisioner(autoScalingService));
discovered.add(new AutoScalingScalingPolicyCfnProvisioner(autoScalingService));
}
@@ -673,7 +675,6 @@ final class CfnProvisionerFixture {
logsService,
kinesisService,
cloudWatchMetricsService,
- autoScalingService,
firehoseService,
cloudFrontService,
resourceRegistry,
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAutoScalingIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAutoScalingIntegrationTest.java
index 3bb362b7b6..0668dabcee 100644
--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAutoScalingIntegrationTest.java
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationAutoScalingIntegrationTest.java
@@ -48,6 +48,10 @@ class CloudFormationAutoScalingIntegrationTest {
"MaxSize": 3,
"DesiredCapacity": 2,
"AvailabilityZones": ["us-east-1a"],
+ "DesiredCapacityType": "units",
+ "CapacityRebalance": true,
+ "MaxInstanceLifetime": 86400,
+ "DefaultInstanceWarmup": 300,
"Tags": [
{"Key": "cluster", "Value": "demo", "PropagateAtLaunch": true},
{"Key": "control-plane", "Value": "only", "PropagateAtLaunch": false}
@@ -56,7 +60,8 @@ class CloudFormationAutoScalingIntegrationTest {
}
},
"Outputs": {
- "AsgArn": {"Value": {"Fn::GetAtt": ["Asg", "Arn"]}}
+ "AsgArn": {"Value": {"Fn::GetAtt": ["Asg", "Arn"]}},
+ "AsgSchemaArn": {"Value": {"Fn::GetAtt": ["Asg", "AutoScalingGroupARN"]}}
}
}
""".formatted(lcName, asgName);
@@ -83,7 +88,12 @@ class CloudFormationAutoScalingIntegrationTest {
.then()
.statusCode(200)
.body(containsString("<StackStatus>CREATE_COMPLETE</StackStatus>"))
- .body(containsString(":autoScalingGroup:" + asgName));
+ .body(containsString(":autoScalingGroup:" + asgName))
+ // AutoScalingGroupARN is the name the registry schema defines, so it is the one real
+ // CloudFormation resolves. An unset attribute does not fail the stack: Fn::GetAtt falls
+ // back to the literal "Asg.AutoScalingGroupARN", which is what this rules out.
+ .body(containsString("<OutputKey>AsgSchemaArn</OutputKey>"))
+ .body(not(containsString("Asg.AutoScalingGroupARN")));
// The group really exists in Auto Scaling and references the launch configuration.
given()
@@ -102,7 +112,14 @@ class CloudFormationAutoScalingIntegrationTest {
.body(containsString("<PropagateAtLaunch>true</PropagateAtLaunch>"))
.body(containsString("<Key>control-plane</Key>"))
.body(containsString("<Value>only</Value>"))
- .body(containsString("<PropagateAtLaunch>false</PropagateAtLaunch>"));
+ .body(containsString("<PropagateAtLaunch>false</PropagateAtLaunch>"))
+ // The CloudFormation path used to pass AsgOptionalFields.none(), so a template setting
+ // these four had them dropped without any error. #3494 added them to the service and
+ // left the wiring to this provisioner.
+ .body(containsString("<DesiredCapacityType>units</DesiredCapacityType>"))
+ .body(containsString("<CapacityRebalance>true</CapacityRebalance>"))
+ .body(containsString("<MaxInstanceLifetime>86400</MaxInstanceLifetime>"))
+ .body(containsString("<DefaultInstanceWarmup>300</DefaultInstanceWarmup>"));
}
@Test
diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisionerTest.java
new file mode 100644
index 0000000000..54bb4af57d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/AutoScalingGroupCfnProvisionerTest.java
@@ -0,0 +1,253 @@
+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.services.autoscaling.AutoScalingService;
+import io.github.hectorvent.floci.services.autoscaling.model.AsgOptionalFields;
+import io.github.hectorvent.floci.services.autoscaling.model.AutoScalingGroup;
+import io.github.hectorvent.floci.services.autoscaling.model.LaunchConfiguration;
+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.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertNull;
+import static org.junit.jupiter.api.Assertions.assertThrows;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.ArgumentMatchers.anyBoolean;
+import static org.mockito.ArgumentMatchers.anyInt;
+import static org.mockito.ArgumentMatchers.anyList;
+import static org.mockito.ArgumentMatchers.anyMap;
+import static org.mockito.ArgumentMatchers.anyString;
+import static org.mockito.ArgumentMatchers.eq;
+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 group and launch configuration CFN provisioner in isolation, against a mocked
+ * {@link AutoScalingService}.
+ */
+class AutoScalingGroupCfnProvisionerTest {
+
+ private static final String REGION = "us-east-1";
+ private static final String GROUP = "AWS::AutoScaling::AutoScalingGroup";
+ private static final String LAUNCH_CONFIGURATION = "AWS::AutoScaling::LaunchConfiguration";
+ private static final String ASG_ARN =
+ "arn:aws:autoscaling:us-east-1:000000000000:autoScalingGroup:uuid:autoScalingGroupName/my-asg";
+
+ private final AutoScalingService autoScaling = mock(AutoScalingService.class);
+ private final AutoScalingGroupCfnProvisioner provisioner =
+ new AutoScalingGroupCfnProvisioner(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));
+ when(engine.resolveStringList(any())).thenAnswer(inv -> {
+ JsonNode node = inv.getArgument(0);
+ List<String> values = new ArrayList<>();
+ if (node != null && node.isArray()) {
+ node.forEach(element -> values.add(element.asText()));
+ }
+ return values;
+ });
+ return new ProvisionContext(engine, REGION, "000000000000", "my-stack", priorPhysicalId);
+ }
+
+ private static StackResource resource(String type, String logicalId, String priorPhysicalId) {
+ StackResource r = new StackResource();
+ r.setLogicalId(logicalId);
+ r.setResourceType(type);
+ r.setPhysicalId(priorPhysicalId);
+ r.setAttributes(new HashMap<>());
+ return r;
+ }
+
+ private static AutoScalingGroup group(String name) {
+ AutoScalingGroup asg = new AutoScalingGroup();
+ asg.setAutoScalingGroupName(name);
+ asg.setAutoScalingGroupArn(ASG_ARN);
+ return asg;
+ }
+
+ @Test
+ void groupCreateRecordsTheSchemaArnAttribute() {
+ // AutoScalingGroupARN is the schema's only readOnlyProperty, so it is the name real
+ // CloudFormation resolves. The monolith only ever wrote "Arn", which meant
+ // Fn::GetAtt [Asg, AutoScalingGroupARN] fell through to the literal "Asg.AutoScalingGroupARN".
+ when(autoScaling.createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
+ any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
+ any(), anyInt(), anyList(), anyMap(), anyMap(), any()))
+ .thenReturn(group("my-asg"));
+ StackResource r = resource(GROUP, "Asg", null);
+ ObjectNode props = mapper.createObjectNode()
+ .put("AutoScalingGroupName", "my-asg")
+ .put("MinSize", "1")
+ .put("MaxSize", "3");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("my-asg", r.getPhysicalId());
+ assertEquals(ASG_ARN, r.getAttributes().get("AutoScalingGroupARN"));
+ // Kept beside it: templates and the existing integration test read this name.
+ assertEquals(ASG_ARN, r.getAttributes().get("Arn"));
+ }
+
+ @Test
+ void groupCreateCarriesTheOptionalFieldsTheTemplateSet() {
+ // #3494 added these four to the service but left the CloudFormation path passing
+ // AsgOptionalFields.none(), so a template setting them was silently dropped.
+ when(autoScaling.createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
+ any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
+ any(), anyInt(), anyList(), anyMap(), anyMap(), any()))
+ .thenReturn(group("my-asg"));
+ StackResource r = resource(GROUP, "Asg", null);
+ ObjectNode props = mapper.createObjectNode()
+ .put("AutoScalingGroupName", "my-asg")
+ .put("MinSize", "1")
+ .put("MaxSize", "3")
+ .put("DesiredCapacityType", "vcpu")
+ .put("CapacityRebalance", "true")
+ .put("MaxInstanceLifetime", "86400")
+ .put("DefaultInstanceWarmup", "300");
+
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<AsgOptionalFields> captor = ArgumentCaptor.forClass(AsgOptionalFields.class);
+ verify(autoScaling).createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
+ any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
+ any(), anyInt(), anyList(), anyMap(), anyMap(), captor.capture());
+ AsgOptionalFields optional = captor.getValue();
+ assertEquals("vcpu", optional.desiredCapacityType());
+ assertEquals(Boolean.TRUE, optional.capacityRebalance());
+ assertEquals(86400, optional.maxInstanceLifetime());
+ assertEquals(300, optional.defaultInstanceWarmup());
+ }
+
+ @Test
+ void groupOptionalFieldsStayNullWhenTheTemplateOmitsThem() {
+ // Absent must stay null, not false or zero: applyToExistingGroup overwrites only the
+ // members that are set, matching what UpdateAutoScalingGroup does on the Query path.
+ when(autoScaling.createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
+ any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
+ any(), anyInt(), anyList(), anyMap(), anyMap(), any()))
+ .thenReturn(group("my-asg"));
+ StackResource r = resource(GROUP, "Asg", null);
+ ObjectNode props = mapper.createObjectNode().put("AutoScalingGroupName", "my-asg");
+
+ provisioner.provision(r, props, ctx());
+
+ ArgumentCaptor<AsgOptionalFields> captor = ArgumentCaptor.forClass(AsgOptionalFields.class);
+ verify(autoScaling).createAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
+ any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(), anyList(),
+ any(), anyInt(), anyList(), anyMap(), anyMap(), captor.capture());
+ AsgOptionalFields optional = captor.getValue();
+ assertNull(optional.desiredCapacityType());
+ assertNull(optional.capacityRebalance());
+ assertNull(optional.maxInstanceLifetime());
+ assertNull(optional.defaultInstanceWarmup());
+ }
+
+ @Test
+ void groupUpdateReconcilesTheSameNameInsteadOfCreatingItAgain() {
+ // provision() re-runs on every UpdateStack. createAutoScalingGroup throws AlreadyExists, so
+ // a same-named group already on file has to go through updateAutoScalingGroup.
+ when(autoScaling.describeAutoScalingGroups(REGION, List.of("my-asg")))
+ .thenReturn(List.of(group("my-asg")));
+ StackResource r = resource(GROUP, "Asg", "my-asg");
+ ObjectNode props = mapper.createObjectNode()
+ .put("AutoScalingGroupName", "my-asg")
+ .put("MinSize", "2")
+ .put("MaxSize", "6")
+ .put("DesiredCapacityType", "units");
+
+ provisioner.provision(r, props, ctx("my-asg"));
+
+ ArgumentCaptor<AsgOptionalFields> captor = ArgumentCaptor.forClass(AsgOptionalFields.class);
+ verify(autoScaling).updateAutoScalingGroup(eq(REGION), eq("my-asg"), any(), any(), any(), any(),
+ any(), eq(2), eq(6), anyInt(), anyInt(), anyList(), anyList(), any(), anyInt(), anyList(),
+ captor.capture());
+ assertEquals("units", captor.getValue().desiredCapacityType());
+ verify(autoScaling, never()).createAutoScalingGroup(anyString(), anyString(), any(), any(), any(),
+ any(), any(), anyInt(), anyInt(), anyInt(), anyInt(), anyList(), anyList(), anyList(),
+ anyList(), any(), anyInt(), anyList(), anyMap(), anyMap(), any());
+ }
+
+ @Test
+ void launchConfigurationCreateSetsTheNameAsPhysicalId() {
+ LaunchConfiguration lc = new LaunchConfiguration();
+ lc.setLaunchConfigurationName("my-lc");
+ lc.setLaunchConfigurationArn("arn:aws:autoscaling:us-east-1:000000000000:launchConfiguration:my-lc");
+ when(autoScaling.createLaunchConfiguration(eq(REGION), eq("my-lc"), any(), eq("ami-1"),
+ eq("t3.micro"), any(), anyList(), any(), any(), any()))
+ .thenReturn(lc);
+ StackResource r = resource(LAUNCH_CONFIGURATION, "Lc", null);
+ ObjectNode props = mapper.createObjectNode()
+ .put("LaunchConfigurationName", "my-lc")
+ .put("ImageId", "ami-1")
+ .put("InstanceType", "t3.micro");
+
+ provisioner.provision(r, props, ctx());
+
+ assertEquals("my-lc", r.getPhysicalId());
+ assertEquals("arn:aws:autoscaling:us-east-1:000000000000:launchConfiguration:my-lc",
+ r.getAttributes().get("Arn"));
+ }
+
+ @Test
+ void launchConfigurationUpdateLeavesTheExistingOneAlone() {
+ // Launch configurations have no update API on real AWS, so a same-named one already on file
+ // must not be re-created.
+ LaunchConfiguration lc = new LaunchConfiguration();
+ lc.setLaunchConfigurationName("my-lc");
+ lc.setLaunchConfigurationArn("arn:aws:autoscaling:us-east-1:000000000000:launchConfiguration:my-lc");
+ when(autoScaling.describeLaunchConfigurations(REGION, List.of("my-lc"))).thenReturn(List.of(lc));
+ StackResource r = resource(LAUNCH_CONFIGURATION, "Lc", "my-lc");
+ ObjectNode props = mapper.createObjectNode()
+ .put("LaunchConfigurationName", "my-lc")
+ .put("ImageId", "ami-2");
+
+ provisioner.provision(r, props, ctx("my-lc"));
+
+ verify(autoScaling, never()).createLaunchConfiguration(anyString(), anyString(), any(), any(),
+ any(), any(), anyList(), any(), any(), any());
+ assertEquals("my-lc", r.getPhysicalId());
+ }
+
+ @Test
+ void deleteRoutesEachTypeToItsOwnCall() {
+ provisioner.delete(LAUNCH_CONFIGURATION, "my-lc", REGION);
+ verify(autoScaling).deleteLaunchConfiguration(REGION, "my-lc");
+
+ provisioner.delete(GROUP, "my-asg", REGION);
+ verify(autoScaling).deleteAutoScalingGroup(REGION, "my-asg", true);
+ }
+
+ @Test
+ void anUnsupportedTypeIsRejectedRatherThanSilentlyIgnored() {
+ StackResource r = resource("AWS::AutoScaling::ScalingPolicy", "Policy", null);
+ ProvisionContext ctx = ctx();
+ ObjectNode props = mapper.createObjectNode();
+
+ assertThrows(IllegalStateException.class, () -> provisioner.provision(r, props, ctx));
+ assertThrows(IllegalStateException.class,
+ () -> provisioner.delete("AWS::AutoScaling::ScalingPolicy", "p", REGION));
+ verify(autoScaling, never()).deleteAutoScalingGroup(anyString(), anyString(), anyBoolean());
+ }
+}
diff --git a/src/test/resources/cloudformation/supported-resource-types.tsv b/src/test/resources/cloudformation/supported-resource-types.tsv
index 2ebb6cc65c..9b0c6f1ed7 100644
--- a/src/test/resources/cloudformation/supported-resource-types.tsv
+++ b/src/test/resources/cloudformation/supported-resource-types.tsv
@@ -22,8 +22,8 @@ AWS::AppSync::FunctionConfiguration AppSyncCfnProvisioner
AWS::AppSync::GraphQLApi AppSyncCfnProvisioner
AWS::AppSync::GraphQLSchema AppSyncCfnProvisioner
AWS::AppSync::Resolver AppSyncCfnProvisioner
-AWS::AutoScaling::AutoScalingGroup LEGACY_SWITCH
-AWS::AutoScaling::LaunchConfiguration LEGACY_SWITCH
+AWS::AutoScaling::AutoScalingGroup AutoScalingGroupCfnProvisioner
+AWS::AutoScaling::LaunchConfiguration AutoScalingGroupCfnProvisioner
AWS::AutoScaling::LifecycleHook AutoScalingLifecycleHookCfnProvisioner
AWS::AutoScaling::ScalingPolicy AutoScalingScalingPolicyCfnProvisioner
AWS::Backup::BackupVault BackupVaultCfnProvisioner