fix(cloudformation): replace changed launch configurations safely (#8599)

* fix(cloudformation): replace changed launch configurations safely
* fix(autoscaling): guard launch configuration replacement races
* fix(cloudformation): reuse replacement decisions and valid fixtures
This commit is contained in:
Jackson Price authored and GitHub committed 2026-11-16 14:29:15 -04:00
1 parent 43363c0f8d
commit 8ad3e2b419
9 files changed
+794 -136

No files matched your search

+19
View File
@@ -414,6 +414,25 @@ list-typed `Paths` holds a single entry; read it with `Fn::Select` as you would
Deleting the stack removes the resources in dependency order and finally the organization itself.
Deleting a resource that is already gone is tolerated.
## Auto Scaling Launch Configurations
CloudFormation preserves an unchanged launch configuration and replaces it when its resolved
properties change. An unnamed replacement receives a new name; replacing a custom-named
configuration requires a new `LaunchConfigurationName`. The old configuration remains available
until dependent groups switch and the stack update commits. A failed update restores the prior
configuration. `BlockDeviceMappings` and `MetadataOptions` are passed to Auto Scaling.
The shared CloudFormation change detector compares create-only properties using each stack
version's parameters and resource references. This also covers configurations created before
replacement support: unchanged references retain their identity, while added or changed values
or a removed `InstanceId` require replacement. No separate launch-configuration input snapshot
is needed.
Group creation and updates coordinate with launch-configuration deletion, so a concurrent
attachment cannot bypass the in-use check. A configuration already deleted cannot be attached.
Out-of-band deletion remains stack drift; this replacement behavior does not promise automatic
recreation under a missing configuration's former custom name.
## Auto Scaling Launch Template Resolution
`AWS::AutoScaling::AutoScalingGroup` resolves its launch template through any of the shapes AWS
@@ -370,9 +370,19 @@ public class AutoScalingService implements PassedRoleLookup {
}
public void deleteLaunchConfiguration(String region, String name) {
if (launchConfigs.remove(lcKey(region, name)) == null) {
throw new AwsException("ValidationError",
"Launch configuration '" + name + "' not found.", 400);
synchronized (lockFor(region)) {
String key = lcKey(region, name);
if (!launchConfigs.containsKey(key)) {
throw new AwsException("ValidationError",
"Launch configuration '" + name + "' not found.", 400);
}
boolean inUse = groups.values().stream().anyMatch(group -> region.equals(group.getRegion())
&& name.equals(group.getLaunchConfigurationName()));
if (inUse) {
throw new AwsException("ResourceInUse",
"Launch configuration '" + name + "' is in use by an Auto Scaling group.", 400);
}
launchConfigs.remove(key);
}
}
@@ -392,43 +402,45 @@ public class AutoScalingService implements PassedRoleLookup {
Map<String, String> tags,
Map<String, Boolean> tagPropagateAtLaunch,
AsgOptionalFields optionalFields) {
String key = asgKey(region, name);
if (groups.containsKey(key)) {
throw new AwsException("AlreadyExists",
"Auto Scaling group '" + name + "' already exists.", 400);
}
validateLaunchSource(launchConfigName, launchTemplateId, launchTemplateName, mixedInstancesPolicy);
if (launchConfigName == null && launchTemplateId == null && launchTemplateName == null
&& mixedInstancesPolicy == null) {
throw new AwsException("ValidationError",
"Valid requests must contain either LaunchTemplate, LaunchConfigurationName, "
+ "InstanceId or MixedInstancesPolicy parameter.", 400);
}
validateEffectiveLaunchImage(region, launchConfigName, launchTemplateId, launchTemplateName,
launchTemplateVersion, mixedInstancesPolicy);
validateOptionalFields(optionalFields);
validateDesiredCapacityType(
optionalFields != null ? optionalFields.desiredCapacityType() : null,
mixedInstancesPolicy);
synchronized (lockFor(region)) {
String key = asgKey(region, name);
if (groups.containsKey(key)) {
throw new AwsException("AlreadyExists",
"Auto Scaling group '" + name + "' already exists.", 400);
}
validateLaunchSource(launchConfigName, launchTemplateId, launchTemplateName, mixedInstancesPolicy);
if (launchConfigName == null && launchTemplateId == null && launchTemplateName == null
&& mixedInstancesPolicy == null) {
throw new AwsException("ValidationError",
"Valid requests must contain either LaunchTemplate, LaunchConfigurationName, "
+ "InstanceId or MixedInstancesPolicy parameter.", 400);
}
validateEffectiveLaunchImage(region, launchConfigName, launchTemplateId, launchTemplateName,
launchTemplateVersion, mixedInstancesPolicy);
validateOptionalFields(optionalFields);
validateDesiredCapacityType(
optionalFields != null ? optionalFields.desiredCapacityType() : null,
mixedInstancesPolicy);
AutoScalingGroup asg = newGroup(region, name, minSize, maxSize, desiredCapacity,
resolveAvailabilityZones(region, availabilityZones, subnetIds), subnetIds, terminationPolicies,
tags, tagPropagateAtLaunch);
asg.setLaunchConfigurationName(launchConfigName);
asg.setLaunchTemplateId(launchTemplateId);
asg.setLaunchTemplateName(launchTemplateName);
asg.setLaunchTemplateVersion(launchTemplateVersion);
asg.setMixedInstancesPolicy(mixedInstancesPolicy);
asg.setDefaultCooldown(defaultCooldown > 0 ? defaultCooldown : 300);
asg.setTargetGroupARNs(targetGroupArns != null ? new ArrayList<>(targetGroupArns) : new ArrayList<>());
asg.setLoadBalancerNames(lbNames != null ? new ArrayList<>(lbNames) : new ArrayList<>());
asg.setHealthCheckType(healthCheckType != null ? healthCheckType : "EC2");
asg.setHealthCheckGracePeriod(healthCheckGracePeriod);
if (optionalFields != null) {
optionalFields.applyToNewGroup(asg);
AutoScalingGroup asg = newGroup(region, name, minSize, maxSize, desiredCapacity,
resolveAvailabilityZones(region, availabilityZones, subnetIds), subnetIds, terminationPolicies,
tags, tagPropagateAtLaunch);
asg.setLaunchConfigurationName(launchConfigName);
asg.setLaunchTemplateId(launchTemplateId);
asg.setLaunchTemplateName(launchTemplateName);
asg.setLaunchTemplateVersion(launchTemplateVersion);
asg.setMixedInstancesPolicy(mixedInstancesPolicy);
asg.setDefaultCooldown(defaultCooldown > 0 ? defaultCooldown : 300);
asg.setTargetGroupARNs(targetGroupArns != null ? new ArrayList<>(targetGroupArns) : new ArrayList<>());
asg.setLoadBalancerNames(lbNames != null ? new ArrayList<>(lbNames) : new ArrayList<>());
asg.setHealthCheckType(healthCheckType != null ? healthCheckType : "EC2");
asg.setHealthCheckGracePeriod(healthCheckGracePeriod);
if (optionalFields != null) {
optionalFields.applyToNewGroup(asg);
}
groups.put(key, asg);
return asg;
}
groups.put(key, asg);
return asg;
}
/**
@@ -471,68 +483,70 @@ public class AutoScalingService implements PassedRoleLookup {
String healthCheckType, Integer healthCheckGracePeriod,
List<String> terminationPolicies,
AsgOptionalFields optionalFields) {
// Under the group's lock, which EnterStandby, ExitStandby and the reconciler hold while they read and
// change the group's capacity.
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
validateLaunchSource(launchConfigName, launchTemplateId, launchTemplateName, mixedInstancesPolicy);
if (launchTemplateVersion != null && launchTemplateId == null && launchTemplateName == null) {
throw new AwsException("ValidationError",
"LaunchTemplateVersion requires a LaunchTemplateId or LaunchTemplateName.", 400);
synchronized (lockFor(region)) {
// Under the group's lock, which EnterStandby, ExitStandby and the reconciler hold while they read and
// change the group's capacity.
String key = asgKey(region, name);
synchronized (lockFor(key)) {
AutoScalingGroup asg = requireGroup(region, name);
validateLaunchSource(launchConfigName, launchTemplateId, launchTemplateName, mixedInstancesPolicy);
if (launchTemplateVersion != null && launchTemplateId == null && launchTemplateName == null) {
throw new AwsException("ValidationError",
"LaunchTemplateVersion requires a LaunchTemplateId or LaunchTemplateName.", 400);
}
validateOptionalFields(optionalFields);
rejectDesiredConfigurationUpdateDuringActiveRefresh(region, name,
launchConfigName, launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy);
LaunchIdentity effectiveIdentity = effectiveLaunchIdentity(asg, launchConfigName,
launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy);
validateEffectiveLaunchImage(region,
effectiveIdentity.launchConfigurationName(),
effectiveIdentity.launchTemplateId(),
effectiveIdentity.launchTemplateName(),
effectiveIdentity.launchTemplateVersion(),
effectiveIdentity.mixedInstancesPolicy());
validateDesiredCapacityType(
effectiveDesiredCapacityType(asg, optionalFields),
effectiveIdentity.mixedInstancesPolicy());
List<String> updatedZones = availabilityZones;
if (subnetIds != null && !subnetIds.isEmpty()) {
updatedZones = resolveAvailabilityZones(region, availabilityZones, subnetIds);
}
if (launchConfigName != null) {
asg.setLaunchConfigurationName(launchConfigName);
asg.setLaunchTemplateId(null);
asg.setLaunchTemplateName(null);
asg.setLaunchTemplateVersion(null);
asg.setMixedInstancesPolicy(null);
}
if (launchTemplateId != null || launchTemplateName != null) {
asg.setLaunchConfigurationName(null);
asg.setLaunchTemplateId(launchTemplateId);
asg.setLaunchTemplateName(launchTemplateName);
asg.setLaunchTemplateVersion(launchTemplateVersion);
asg.setMixedInstancesPolicy(null);
}
if (mixedInstancesPolicy != null) {
asg.setLaunchConfigurationName(null);
asg.setLaunchTemplateId(null);
asg.setLaunchTemplateName(null);
asg.setLaunchTemplateVersion(null);
asg.setMixedInstancesPolicy(mixedInstancesPolicy);
}
if (minSize != null) { asg.setMinSize(minSize); }
if (maxSize != null) { asg.setMaxSize(maxSize); }
if (desiredCapacity != null) { asg.setDesiredCapacity(desiredCapacity); }
if (defaultCooldown != null) { asg.setDefaultCooldown(defaultCooldown); }
if (updatedZones != null) { asg.setAvailabilityZones(new ArrayList<>(updatedZones)); }
if (subnetIds != null) { asg.setSubnetIds(new ArrayList<>(subnetIds)); }
if (healthCheckType != null) { asg.setHealthCheckType(healthCheckType); }
if (healthCheckGracePeriod != null) { asg.setHealthCheckGracePeriod(healthCheckGracePeriod); }
if (terminationPolicies != null) { asg.setTerminationPolicies(new ArrayList<>(terminationPolicies)); }
if (optionalFields != null) {
optionalFields.applyToExistingGroup(asg);
}
groups.put(key, asg);
}
validateOptionalFields(optionalFields);
rejectDesiredConfigurationUpdateDuringActiveRefresh(region, name,
launchConfigName, launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy);
LaunchIdentity effectiveIdentity = effectiveLaunchIdentity(asg, launchConfigName,
launchTemplateId, launchTemplateName, launchTemplateVersion, mixedInstancesPolicy);
validateEffectiveLaunchImage(region,
effectiveIdentity.launchConfigurationName(),
effectiveIdentity.launchTemplateId(),
effectiveIdentity.launchTemplateName(),
effectiveIdentity.launchTemplateVersion(),
effectiveIdentity.mixedInstancesPolicy());
validateDesiredCapacityType(
effectiveDesiredCapacityType(asg, optionalFields),
effectiveIdentity.mixedInstancesPolicy());
List<String> updatedZones = availabilityZones;
if (subnetIds != null && !subnetIds.isEmpty()) {
updatedZones = resolveAvailabilityZones(region, availabilityZones, subnetIds);
}
if (launchConfigName != null) {
asg.setLaunchConfigurationName(launchConfigName);
asg.setLaunchTemplateId(null);
asg.setLaunchTemplateName(null);
asg.setLaunchTemplateVersion(null);
asg.setMixedInstancesPolicy(null);
}
if (launchTemplateId != null || launchTemplateName != null) {
asg.setLaunchConfigurationName(null);
asg.setLaunchTemplateId(launchTemplateId);
asg.setLaunchTemplateName(launchTemplateName);
asg.setLaunchTemplateVersion(launchTemplateVersion);
asg.setMixedInstancesPolicy(null);
}
if (mixedInstancesPolicy != null) {
asg.setLaunchConfigurationName(null);
asg.setLaunchTemplateId(null);
asg.setLaunchTemplateName(null);
asg.setLaunchTemplateVersion(null);
asg.setMixedInstancesPolicy(mixedInstancesPolicy);
}
if (minSize != null) { asg.setMinSize(minSize); }
if (maxSize != null) { asg.setMaxSize(maxSize); }
if (desiredCapacity != null) { asg.setDesiredCapacity(desiredCapacity); }
if (defaultCooldown != null) { asg.setDefaultCooldown(defaultCooldown); }
if (updatedZones != null) { asg.setAvailabilityZones(new ArrayList<>(updatedZones)); }
if (subnetIds != null) { asg.setSubnetIds(new ArrayList<>(subnetIds)); }
if (healthCheckType != null) { asg.setHealthCheckType(healthCheckType); }
if (healthCheckGracePeriod != null) { asg.setHealthCheckGracePeriod(healthCheckGracePeriod); }
if (terminationPolicies != null) { asg.setTerminationPolicies(new ArrayList<>(terminationPolicies)); }
if (optionalFields != null) {
optionalFields.applyToExistingGroup(asg);
}
groups.put(key, asg);
}
}
@@ -2448,6 +2462,10 @@ public class AutoScalingService implements PassedRoleLookup {
String launchTemplateVersion,
MixedInstancesPolicy mixedInstancesPolicy) {
if (launchConfigName != null) {
if (!launchConfigs.containsKey(lcKey(region, launchConfigName))) {
throw new AwsException("ValidationError",
"Launch configuration '" + launchConfigName + "' not found.", 400);
}
return;
}
if (launchTemplateId != null || launchTemplateName != null) {
@@ -11,6 +11,7 @@ import io.floci.aws.services.autoscaling.model.AvailabilityZoneDistribution;
import io.floci.aws.services.autoscaling.model.CapacityReservationSpecification;
import io.floci.aws.services.autoscaling.model.InstanceMaintenancePolicy;
import io.floci.aws.services.autoscaling.model.LaunchConfiguration;
import io.floci.aws.services.autoscaling.model.LaunchConfigurationBlockDeviceMapping;
import io.floci.aws.services.autoscaling.model.MixedInstancesPolicy;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import io.floci.aws.services.cloudformation.model.StackResource;
@@ -77,14 +78,29 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
@Override
public void delete(String resourceType, String physicalId, String region) {
switch (resourceType) {
case LAUNCH_CONFIGURATION -> autoScalingService.deleteLaunchConfiguration(region, physicalId);
case LAUNCH_CONFIGURATION -> deleteLaunchConfiguration(region, physicalId);
case GROUP -> autoScalingService.deleteAutoScalingGroup(region, physicalId, true);
default -> throw unsupported(resourceType);
}
}
private void deleteLaunchConfiguration(String region, String physicalId) {
try {
autoScalingService.deleteLaunchConfiguration(region, physicalId);
} catch (AwsException failure) {
if (!"ValidationError".equals(failure.getErrorCode())
|| !autoScalingService.describeLaunchConfigurations(region, List.of(physicalId)).isEmpty()) {
throw failure;
}
LOG.debugv("Launch configuration {0} is already absent", physicalId);
}
}
@Override
public boolean rollbackUpdate(StackResource resource) {
if (LAUNCH_CONFIGURATION.equals(resource.getResourceType())) {
return ReplacementCleanup.rollback(resource, this::delete);
}
if (GROUP.equals(resource.getResourceType())) {
String rawSnapshot = resource.getAttributes().remove(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR);
if (rawSnapshot != null) {
@@ -147,6 +163,9 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(CfnRollback.ASG_UPDATE_SNAPSHOT_ATTR);
if (LAUNCH_CONFIGURATION.equals(resource.getResourceType())) {
ReplacementCleanup.clear(resource);
}
}
public record AsgSnapshot(
@@ -184,35 +203,67 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
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), null, List.of(), metadataOptions(props, ctx));
deleteRenamedResource(ctx, name, n -> autoScalingService.deleteLaunchConfiguration(region, n),
"launch configuration");
String explicitName = ctx.resolveOptional(props, "LaunchConfigurationName");
String name = ctx.stablePhysicalName(explicitName, r.getLogicalId(), 255, false);
List<LaunchConfigurationBlockDeviceMapping> mappings = blockDeviceMappings(props, ctx);
LaunchTemplateData.MetadataOptions metadata = metadataOptions(props, ctx);
LaunchConfiguration prior = existingEntity(ctx, ctx.priorPhysicalId(),
n -> requireLaunchConfiguration(region, n));
if (ctx.isUpdate()) {
ReplacementCleanup.endRollbackRetry(r);
if (!launchConfigurationRequiresReplacement(props, ctx)
&& ctx.reusesPriorEntity(name) && prior != null) {
return;
}
if (explicitName != null && !explicitName.isBlank() && ctx.reusesPriorEntity(name)) {
throw CfnExceptions.customNamedReplacement(name);
}
if (explicitName == null || explicitName.isBlank()) {
name = ctx.generatePhysicalName(r.getLogicalId(), 255, false);
}
}
// Ref returns the launch configuration name.
Map<String, String> before = Map.copyOf(r.getAttributes());
String associatePublicIp = ctx.resolveOptional(props, "AssociatePublicIpAddress");
LaunchConfiguration 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"),
associatePublicIp == null || associatePublicIp.isBlank() ? null
: Boolean.parseBoolean(associatePublicIp), null, mappings, metadata);
r.setPhysicalId(name);
r.getAttributes().put("Arn", lc.getLaunchConfigurationArn());
ReplacementCleanup.record(r, ctx, before);
}
private static boolean launchConfigurationRequiresReplacement(JsonNode props, ProvisionContext ctx) {
PropertyChanges changes = ctx.changes(LAUNCH_CONFIGURATION, props);
if (changes.requiresReplacement()) {
return true;
}
if (ctx.priorProperties() == null) {
return false;
}
// The shared replacement flag currently omits newly added create-only properties.
return changes.byName().values().stream()
.anyMatch(change -> change.createOnly() && change.kind() == PropertyChanges.Kind.ADDED);
}
@Override
public boolean hasReplacementUpdate(StackResource resource) {
return LAUNCH_CONFIGURATION.equals(resource.getResourceType()) && ReplacementCleanup.hasReplacement(resource);
}
@Override
public String updateCleanupPhysicalId(StackResource resource) {
return LAUNCH_CONFIGURATION.equals(resource.getResourceType())
? ReplacementCleanup.cleanupPhysicalId(resource) : null;
}
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
return LAUNCH_CONFIGURATION.equals(resource.getResourceType())
? ReplacementCleanup.complete(resource, this::delete) : UpdateCleanupResult.notApplicable();
}
/**
@@ -241,6 +292,49 @@ public class AutoScalingGroupCfnProvisioner implements CfnResourceProvisioner {
return options;
}
private List<LaunchConfigurationBlockDeviceMapping> blockDeviceMappings(JsonNode props, ProvisionContext ctx) {
CfnPropertyTypes.Reader types = new CfnPropertyTypes.Reader(ctx.engine());
JsonNode mappings = types.read("BlockDeviceMappings", props.get("BlockDeviceMappings"),
CfnPropertyTypes.propertyShape(LAUNCH_CONFIGURATION, "BlockDeviceMappings"));
types.finish();
List<LaunchConfigurationBlockDeviceMapping> result = new ArrayList<>();
if (mappings == null) {
return result;
}
for (JsonNode mapping : mappings) {
LaunchConfigurationBlockDeviceMapping value = new LaunchConfigurationBlockDeviceMapping();
value.setDeviceName(mapping.path("DeviceName").asText(null));
value.setVirtualName(mapping.path("VirtualName").asText(null));
if (mapping.hasNonNull("NoDevice")) {
value.setNoDevice(mapping.get("NoDevice").booleanValue());
}
JsonNode ebs = mapping.get("Ebs");
if (ebs != null && !ebs.isNull()) {
LaunchConfigurationBlockDeviceMapping.Ebs disk = new LaunchConfigurationBlockDeviceMapping.Ebs();
disk.setSnapshotId(ebs.path("SnapshotId").asText(null));
disk.setVolumeType(ebs.path("VolumeType").asText(null));
if (ebs.hasNonNull("VolumeSize")) {
disk.setVolumeSize(ebs.get("VolumeSize").intValue());
}
if (ebs.hasNonNull("Iops")) {
disk.setIops(ebs.get("Iops").intValue());
}
if (ebs.hasNonNull("Throughput")) {
disk.setThroughput(ebs.get("Throughput").intValue());
}
if (ebs.hasNonNull("Encrypted")) {
disk.setEncrypted(ebs.get("Encrypted").booleanValue());
}
if (ebs.hasNonNull("DeleteOnTermination")) {
disk.setDeleteOnTermination(ebs.get("DeleteOnTermination").booleanValue());
}
value.setEbs(disk);
}
result.add(value);
}
return result;
}
private LaunchConfiguration requireLaunchConfiguration(String region, String name) {
List<LaunchConfiguration> found = autoScalingService.describeLaunchConfigurations(region, List.of(name));
if (found.isEmpty()) {
@@ -62,16 +62,27 @@ class AutoScalingCapacityAccountLockIntegrationTest {
workers.shutdownNow();
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
try {
RequestScopes.runAs(ACCOUNT, REGION, () -> service.deleteAutoScalingGroup(REGION, name, true));
RequestScopes.runAs(ACCOUNT, REGION, () -> delete(REGION, name));
} finally {
RequestScopes.runAs(otherAccount, otherRegion,
() -> service.deleteAutoScalingGroup(otherRegion, name, true));
() -> delete(otherRegion, name));
}
}
}
private void delete(String region, String name) {
if (!service.describeAutoScalingGroups(region, List.of(name)).isEmpty()) {
service.deleteAutoScalingGroup(region, name, true);
}
if (!service.describeLaunchConfigurations(region, List.of(name)).isEmpty()) {
service.deleteLaunchConfiguration(region, name);
}
}
private AutoScalingGroup create(String region, String name) {
service.createAutoScalingGroup(region, name, "unused-capacity-lock-source", null, null, null, null,
service.createLaunchConfiguration(region, name, null, "ami-12345678", "t3.micro",
null, List.of(), null, null, null);
service.createAutoScalingGroup(region, name, name, null, null, null, null,
0, 1, 0, 300, List.of(region + "a"), List.of(), List.of(), List.of(), "EC2", 0,
List.of("Default"), Map.of(), Map.of(), AsgOptionalFields.none());
return service.describeAutoScalingGroups(region, List.of(name)).getFirst();
@@ -0,0 +1,114 @@
package io.floci.aws.services.autoscaling;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.core.common.RegionResolver;
import io.floci.aws.services.autoscaling.model.AsgOptionalFields;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Subnet;
import io.floci.aws.testing.ThreadStates;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.Mockito.*;
class AutoScalingLaunchConfigurationAttachmentTest {
private static final String REGION = "us-east-1";
private AutoScalingService service;
private Ec2Service ec2;
@BeforeEach
void setUp() {
service = new AutoScalingService();
service.regionResolver = new RegionResolver(REGION, "000000000000");
service.createAutoScalingGroup(REGION, "existing", null, "lt-original", null, "1", null,
0, 0, 0, 300, List.of(), List.of(), List.of(), List.of(),
"EC2", 0, List.of(), Map.of(), Map.of(), AsgOptionalFields.none());
service.createLaunchConfiguration(REGION, "configuration", null, "ami-test", "t3.micro",
null, List.of(), null, null, null);
ec2 = mock(Ec2Service.class);
service.ec2Service = ec2;
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void deletionWaitsForAttachmentAlreadyPastValidation(boolean update) throws Exception {
CountDownLatch validated = new CountDownLatch(1);
CountDownLatch release = new CountDownLatch(1);
AtomicReference<Thread> deletingThread = new AtomicReference<>();
Subnet subnet = new Subnet();
subnet.setSubnetId("subnet-test");
subnet.setAvailabilityZone(REGION + "a");
when(ec2.describeSubnets(eq(REGION), eq(List.of("subnet-test")), isNull())).thenAnswer(invocation -> {
validated.countDown();
assertTrue(release.await(10, TimeUnit.SECONDS), "Attachment was not released");
return List.of(subnet);
});
ExecutorService workers = Executors.newFixedThreadPool(3);
try {
Future<?> attachment = workers.submit(() -> attachConfiguration(update));
assertTrue(validated.await(5, TimeUnit.SECONDS));
Future<AwsException> deletion = workers.submit(() -> {
deletingThread.set(Thread.currentThread());
return assertThrows(AwsException.class,
() -> service.deleteLaunchConfiguration(REGION, "configuration"));
});
ThreadStates.awaitBlockedOrDone(deletingThread, deletion);
assertEquals(Thread.State.BLOCKED, deletingThread.get().getState());
assertFalse(deletion.isDone(), "Deletion must wait for the attachment it raced");
workers.submit(() -> {
service.createLaunchConfiguration("us-west-2", "configuration", null, "ami-test", "t3.micro",
null, List.of(), null, null, null);
service.deleteLaunchConfiguration("us-west-2", "configuration");
}).get(5, TimeUnit.SECONDS);
release.countDown();
attachment.get(5, TimeUnit.SECONDS);
assertEquals("ResourceInUse", deletion.get(5, TimeUnit.SECONDS).getErrorCode());
assertEquals(1, service.describeLaunchConfigurations(REGION, List.of("configuration")).size());
String groupName = update ? "existing" : "created";
assertEquals("configuration", service.describeAutoScalingGroups(REGION, List.of(groupName))
.getFirst().getLaunchConfigurationName());
} finally {
release.countDown();
workers.shutdownNow();
assertTrue(workers.awaitTermination(5, TimeUnit.SECONDS));
}
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void attachmentRejectsAConfigurationDeletedBeforeValidation(boolean update) {
service.deleteLaunchConfiguration(REGION, "configuration");
AwsException failure = assertThrows(AwsException.class, () -> attachConfiguration(update));
assertEquals("ValidationError", failure.getErrorCode());
assertTrue(failure.getMessage().contains("configuration"));
assertTrue(service.describeAutoScalingGroups(REGION, List.of("created")).isEmpty());
assertNull(service.describeAutoScalingGroups(REGION, List.of("existing"))
.getFirst().getLaunchConfigurationName());
verifyNoInteractions(ec2);
}
private void attachConfiguration(boolean update) {
if (update) {
service.updateAutoScalingGroup(REGION, "existing", "configuration", null, null, null, null,
null, null, null, null, List.of(), List.of("subnet-test"),
null, null, null, AsgOptionalFields.none());
} else {
service.createAutoScalingGroup(REGION, "created", "configuration", null, null, null, null,
0, 0, 0, 300, List.of(), List.of("subnet-test"), List.of(), List.of(),
"EC2", 0, List.of(), Map.of(), Map.of(), AsgOptionalFields.none());
}
}
}
@@ -192,10 +192,12 @@ class AutoScalingTagPropagationIntegrationTest {
void sparseTagsRetainCreateDefaultsUpdateAndDeleteSemantics() {
String name = "sparse-tags-" + UUID.randomUUID();
try (AutoScalingClient client = AwsTestClients.create(AutoScalingClient.builder(), ACCOUNT, Region.of(REGION))) {
client.createLaunchConfiguration(request -> request.launchConfigurationName(name)
.imageId("ami-12345678").instanceType("t3.micro"));
try {
request(ACCOUNT, "autoscaling", "CreateAutoScalingGroup")
.formParam("AutoScalingGroupName", name)
.formParam("LaunchConfigurationName", "sparse-configuration")
.formParam("LaunchConfigurationName", name)
.formParam("MinSize", 0).formParam("MaxSize", 1).formParam("DesiredCapacity", 0)
.formParam("AvailabilityZones.member.1", REGION + "a")
.formParam("Tags.member.3.Key", "existing")
@@ -219,8 +221,13 @@ class AutoScalingTagPropagationIntegrationTest {
.post("/").then().statusCode(200);
assertTrue(describeGroupTags(client, name).isEmpty());
} finally {
if (!client.describeAutoScalingGroups(r -> r.autoScalingGroupNames(name)).autoScalingGroups().isEmpty()) {
client.deleteAutoScalingGroup(r -> r.autoScalingGroupName(name).forceDelete(true));
try {
if (!client.describeAutoScalingGroups(r -> r.autoScalingGroupNames(name))
.autoScalingGroups().isEmpty()) {
client.deleteAutoScalingGroup(r -> r.autoScalingGroupName(name).forceDelete(true));
}
} finally {
client.deleteLaunchConfiguration(r -> r.launchConfigurationName(name));
}
}
}
@@ -0,0 +1,234 @@
package io.floci.aws.services.cloudformation;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.RestAssured;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.auth.credentials.AwsBasicCredentials;
import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider;
import software.amazon.awssdk.http.urlconnection.UrlConnectionHttpClient;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.autoscaling.AutoScalingClient;
import software.amazon.awssdk.services.autoscaling.model.AutoScalingException;
import software.amazon.awssdk.services.autoscaling.model.LaunchConfiguration;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import java.net.URI;
import java.util.UUID;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@QuarkusTest
class CloudFormationLaunchConfigurationReplacementSdkIntegrationTest {
@Test
void changedConfigurationReplacesAndReattachesGroupWhileUnchangedConfigurationKeepsIdentity() {
try (Scenario scenario = new Scenario()) {
scenario.create(template(null, "t3.micro", 1));
String original = scenario.physical("Launch");
LaunchConfiguration launch = scenario.launch(original);
AutoScalingException inUse = assertThrows(AutoScalingException.class, () ->
scenario.scaling.deleteLaunchConfiguration(request -> request.launchConfigurationName(original)));
assertEquals("ResourceInUse", inUse.awsErrorDetails().errorCode());
assertEquals(original, scenario.launch(original).launchConfigurationName());
assertEquals("required", launch.metadataOptions().httpTokensAsString());
assertEquals("/dev/xvda", launch.blockDeviceMappings().getFirst().deviceName());
assertEquals(150, launch.blockDeviceMappings().getFirst().ebs().volumeSize());
assertEquals("gp3", launch.blockDeviceMappings().getFirst().ebs().volumeType());
assertTrue(launch.blockDeviceMappings().getFirst().ebs().encrypted());
assertTrue(launch.blockDeviceMappings().getFirst().ebs().deleteOnTermination());
scenario.update(template(null, "t3.micro", 2), "UPDATE_COMPLETE");
assertEquals(original, scenario.physical("Launch"));
scenario.update(template(null, "t3.small", 2), "UPDATE_COMPLETE");
String replacement = scenario.physical("Launch");
assertNotEquals(original, replacement);
assertEquals("t3.small", scenario.launch(replacement).instanceType());
assertFalse(scenario.scaling.describeLaunchConfigurations().launchConfigurations().stream()
.anyMatch(item -> original.equals(item.launchConfigurationName())));
assertEquals(replacement, scenario.scaling.describeAutoScalingGroups(request ->
request.autoScalingGroupNames(scenario.physical("Group")))
.autoScalingGroups().getFirst().launchConfigurationName());
}
}
@Test
void explicitNameReplacementRequiresNewNameAndPreservesOriginalOnRefusal() {
try (Scenario scenario = new Scenario()) {
String original = scenario.name + "-named";
scenario.create(template(original, "t3.micro", 1));
scenario.update(template(original, "t3.small", 1), "UPDATE_ROLLBACK_COMPLETE");
assertEquals(original, scenario.physical("Launch"));
assertEquals("t3.micro", scenario.launch(original).instanceType());
assertEquals(original, scenario.scaling.describeAutoScalingGroups(request ->
request.autoScalingGroupNames(scenario.physical("Group")))
.autoScalingGroups().getFirst().launchConfigurationName());
String replacement = original + "-next";
scenario.update(template(replacement, "t3.small", 1), "UPDATE_COMPLETE");
assertEquals(replacement, scenario.physical("Launch"));
assertEquals("t3.small", scenario.launch(replacement).instanceType());
assertFalse(scenario.scaling.describeLaunchConfigurations().launchConfigurations().stream()
.anyMatch(item -> original.equals(item.launchConfigurationName())));
}
}
@Test
void parameterChangesReplaceConfigurationsUsingThePreviousStackValues() {
try (Scenario scenario = new Scenario()) {
String initial = parameterTemplate(1);
scenario.create(initial);
String original = scenario.physical("Launch");
scenario.update(parameterTemplate(2), "UPDATE_COMPLETE");
assertEquals(original, scenario.physical("Launch"));
scenario.cfn.updateStack(request -> request.stackName(scenario.name).templateBody(parameterTemplate(2))
.parameters(parameter -> parameter.parameterKey("InstanceType").parameterValue("t3.small")));
CfnStackWaits.awaitStatus(scenario.cfn, scenario.name, "UPDATE_COMPLETE");
String replacement = scenario.physical("Launch");
assertNotEquals(original, replacement);
assertEquals("t3.small", scenario.launch(replacement).instanceType());
assertTrue(scenario.scaling.describeLaunchConfigurations(request ->
request.launchConfigurationNames(original)).launchConfigurations().isEmpty());
assertEquals(replacement, scenario.scaling.describeAutoScalingGroups(request ->
request.autoScalingGroupNames(scenario.physical("Group")))
.autoScalingGroups().getFirst().launchConfigurationName());
scenario.cfn.updateStack(request -> request.stackName(scenario.name).templateBody(parameterTemplate(3))
.parameters(parameter -> parameter.parameterKey("InstanceType").usePreviousValue(true)));
CfnStackWaits.awaitStatus(scenario.cfn, scenario.name, "UPDATE_COMPLETE");
assertEquals(replacement, scenario.physical("Launch"));
assertEquals("t3.small", scenario.launch(replacement).instanceType());
}
}
@Test
void addingUserDataReplacesAndReattachesTheGroup() {
try (Scenario scenario = new Scenario()) {
scenario.create(template(null, "t3.micro", 1));
String original = scenario.physical("Launch");
String userData = "IyEvYmluL3NoCmVjaG8gcmVhZHkK";
String updated = template(null, "t3.micro", 2)
.replace("\"ImageId\":", "\"UserData\": \"" + userData + "\",\n \"ImageId\":");
scenario.update(updated, "UPDATE_COMPLETE");
String replacement = scenario.physical("Launch");
assertNotEquals(original, replacement);
assertEquals(userData, scenario.launch(replacement).userData());
assertEquals(replacement, scenario.scaling.describeAutoScalingGroups(request ->
request.autoScalingGroupNames(scenario.physical("Group")))
.autoScalingGroups().getFirst().launchConfigurationName());
assertTrue(scenario.scaling.describeLaunchConfigurations(request ->
request.launchConfigurationNames(original)).launchConfigurations().isEmpty());
scenario.update(updated.replace("\"MaxSize\": \"2\"", "\"MaxSize\": \"3\""), "UPDATE_COMPLETE");
assertEquals(replacement, scenario.physical("Launch"));
assertEquals(userData, scenario.launch(replacement).userData());
}
}
private static String parameterTemplate(int max) {
return template(null, "t3.micro", max)
.replace("\"Resources\": {", """
"Parameters": {"InstanceType": {"Type": "String", "Default": "t3.micro"}},
"Resources": {""")
.replace("\"InstanceType\": \"t3.micro\"", "\"InstanceType\": {\"Ref\": \"InstanceType\"}");
}
private static String template(String name, String instanceType, int max) {
return """
{
"Resources": {
"Launch": {
"Type": "AWS::AutoScaling::LaunchConfiguration",
"Properties": {
%s
"ImageId": "ami-12345678",
"InstanceType": "%s",
"MetadataOptions": {
"HttpTokens": "required",
"HttpEndpoint": "enabled"
},
"BlockDeviceMappings": [
{
"DeviceName": "/dev/xvda",
"Ebs": {
"VolumeSize": 150,
"VolumeType": "gp3",
"Encrypted": true,
"DeleteOnTermination": true
}
}
]
}
},
"Group": {
"Type": "AWS::AutoScaling::AutoScalingGroup",
"Properties": {
"LaunchConfigurationName": {"Ref": "Launch"},
"MinSize": "0",
"MaxSize": "%s",
"DesiredCapacity": "0",
"AvailabilityZones": ["us-east-1a"]
}
}
}
}
""".formatted(name == null ? "" : "\"LaunchConfigurationName\": \"" + name + "\",", instanceType, max);
}
private static final class Scenario implements AutoCloseable {
private final String name = "lc-replacement-" + UUID.randomUUID().toString().substring(0, 8);
private final CloudFormationClient cfn;
private final AutoScalingClient scaling;
private boolean created;
private Scenario() {
URI endpoint = URI.create("http://127.0.0.1:" + RestAssured.port);
StaticCredentialsProvider credentials = StaticCredentialsProvider.create(
AwsBasicCredentials.create("846023460246", "test"));
cfn = CloudFormationClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).httpClientBuilder(UrlConnectionHttpClient.builder()).build();
scaling = AutoScalingClient.builder().endpointOverride(endpoint).region(Region.US_EAST_1)
.credentialsProvider(credentials).httpClientBuilder(UrlConnectionHttpClient.builder()).build();
}
private void create(String template) {
created = true;
CfnStackWaits.createStack(cfn, name, template, "CREATE_COMPLETE");
}
private void update(String template, String expected) {
CfnStackWaits.updateStack(cfn, name, template, expected);
}
private String physical(String logicalId) {
return cfn.describeStackResource(request -> request.stackName(name).logicalResourceId(logicalId))
.stackResourceDetail().physicalResourceId();
}
private LaunchConfiguration launch(String physicalId) {
return scaling.describeLaunchConfigurations(request -> request.launchConfigurationNames(physicalId))
.launchConfigurations().getFirst();
}
@Override
public void close() {
try {
if (created) {
CfnStackWaits.deleteStack(cfn, name);
assertTrue(scaling.describeAutoScalingGroups().autoScalingGroups().stream()
.noneMatch(group -> group.autoScalingGroupName().startsWith(name + "-")));
assertTrue(scaling.describeLaunchConfigurations().launchConfigurations().stream()
.noneMatch(launch -> launch.launchConfigurationName().startsWith(name + "-")));
}
} finally {
scaling.close();
cfn.close();
}
}
}
}
@@ -15,14 +15,18 @@ import io.floci.aws.services.autoscaling.model.MixedInstancesPolicy;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import io.floci.aws.services.cloudformation.model.StackResource;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;
import org.mockito.ArgumentCaptor;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -35,6 +39,8 @@ import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
@@ -345,11 +351,167 @@ class AutoScalingGroupCfnProvisionerTest {
}
@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.
void launchConfigurationPropertyChangeReplacesAndDefersOldDeletion() {
StackResource resource = launchConfigurationUpdate("old-lc", false);
String replacement = resource.getPhysicalId();
assertNotEquals("old-lc", replacement);
assertTrue(provisioner.hasReplacementUpdate(resource));
assertEquals("old-lc", provisioner.updateCleanupPhysicalId(resource));
verify(autoScaling, never()).deleteLaunchConfiguration(REGION, "old-lc");
provisioner.completeUpdate(resource);
verify(autoScaling).deleteLaunchConfiguration(REGION, "old-lc");
}
@Test
void launchConfigurationCleanupRetainsInUseFailureAndRetriesAfterRepair() {
StackResource resource = launchConfigurationUpdate("old-lc", false);
doThrow(new AwsException("ResourceInUse", "Launch configuration is attached", 400))
.when(autoScaling).deleteLaunchConfiguration(REGION, "old-lc");
UpdateCleanupResult failure = provisioner.completeUpdate(resource);
assertFalse(failure.complete());
assertEquals("old-lc", failure.previousPhysicalId());
assertEquals(1, failure.attempts());
doNothing().when(autoScaling).deleteLaunchConfiguration(REGION, "old-lc");
assertTrue(provisioner.completeUpdate(resource).complete());
}
@Test
void launchConfigurationDeleteDoesNotHideValidationErrorWhileResourceExists() {
LaunchConfiguration existing = new LaunchConfiguration();
when(autoScaling.describeLaunchConfigurations(REGION, List.of("existing"))).thenReturn(List.of(existing));
doThrow(new AwsException("ValidationError", "Cannot delete an attached launch configuration", 400))
.when(autoScaling).deleteLaunchConfiguration(REGION, "existing");
assertThrows(AwsException.class, () -> provisioner.delete(LAUNCH_CONFIGURATION, "existing", REGION));
}
@Test
void launchConfigurationReplacementRollbackRestoresPriorIdentity() {
StackResource resource = launchConfigurationUpdate("old-lc", false);
String replacement = resource.getPhysicalId();
assertTrue(provisioner.rollbackUpdate(resource));
assertEquals("old-lc", resource.getPhysicalId());
verify(autoScaling).deleteLaunchConfiguration(REGION, replacement);
verify(autoScaling, never()).deleteLaunchConfiguration(REGION, "old-lc");
}
@Test
void launchConfigurationReplacementRejectsUnchangedExplicitNameBeforeMutation() {
AwsException failure = assertThrows(AwsException.class, () -> launchConfigurationUpdate("old-lc", true));
assertEquals("ValidationError", failure.getErrorCode());
assertTrue(failure.getMessage().contains("Rename old-lc"));
verify(autoScaling, never()).createLaunchConfiguration(anyString(), anyString(), any(), any(),
any(), any(), anyList(), any(), any(), any(), any(), anyList(), any());
verify(autoScaling, never()).deleteLaunchConfiguration(anyString(), anyString());
}
private StackResource launchConfigurationUpdate(String oldName, boolean explicit) {
ObjectNode before = mapper.createObjectNode().put("ImageId", "ami-1").put("InstanceType", "t3.micro");
if (explicit) {
before.put("LaunchConfigurationName", oldName);
}
ObjectNode after = before.deepCopy().put("InstanceType", "t3.small");
StackResource resource = resource(LAUNCH_CONFIGURATION, "Lc", oldName);
LaunchConfiguration old = new LaunchConfiguration();
old.setLaunchConfigurationName(oldName);
when(autoScaling.describeLaunchConfigurations(REGION, List.of(oldName))).thenReturn(List.of(old));
when(autoScaling.createLaunchConfiguration(anyString(), anyString(), any(), any(), any(), any(),
anyList(), any(), any(), any(), any(), anyList(), any())).thenAnswer(invocation -> {
LaunchConfiguration created = new LaunchConfiguration();
created.setLaunchConfigurationName(invocation.getArgument(1));
created.setLaunchConfigurationArn("arn:aws:autoscaling:us-east-1:000000000000:launchConfiguration:new");
return created;
});
ProvisionContext original = ctx(oldName);
ProvisionContext update = new ProvisionContext(original.engine(), REGION, "000000000000",
"my-stack", oldName, event -> {}, before);
provisioner.provision(resource, after, update);
return resource;
}
@Test
void launchConfigurationReusesUnchangedInstanceTemplateWithoutExtraSnapshot() {
ObjectNode props = instanceProperties();
StackResource resource = provisionExistingInstance(props, props.deepCopy(), null, false);
assertEquals("my-lc", resource.getPhysicalId());
assertTrue(resource.getAttributes().isEmpty());
}
@Test
void launchConfigurationRejectsChangedInstanceBeforeMutation() {
ObjectNode previous = instanceProperties();
provisionExistingInstance(previous.deepCopy().put("InstanceId", "i-changed"), previous, null, true);
}
@Test
void launchConfigurationRejectsOtherChangedInputsBeforeMutation() {
ObjectNode previous = instanceProperties();
provisionExistingInstance(previous.deepCopy().put("InstanceType", "t3.small"), previous, null, true);
}
@Test
void launchConfigurationRejectsAddedCreateOnlyInputBeforeMutation() {
ObjectNode previous = instanceProperties();
ObjectNode current = previous.deepCopy().put("UserData", "IyEvYmluL3NoCmVjaG8gcmVhZHkK");
PropertyChanges changes = PropertyChanges.between(LAUNCH_CONFIGURATION, true, previous, current,
null, null, false);
provisionExistingInstance(current, previous, changes, true);
}
@ParameterizedTest
@ValueSource(booleans = {false, true})
void launchConfigurationUsesEngineDecisionForReferenceValues(boolean replacement) {
ObjectNode previous = instanceProperties();
previous.putObject("InstanceId").put("Ref", "SourceInstance");
previous.putObject("InstanceType").put("Ref", "InstanceType");
PropertyChanges changes = new PropertyChanges(Map.of(), replacement);
provisionExistingInstance(instanceProperties(), previous, changes, replacement);
}
@Test
void launchConfigurationRejectsRemovalOfTheInstanceSource() {
ObjectNode previous = instanceProperties().put("ImageId", "ami-original");
ObjectNode current = previous.deepCopy();
current.remove("InstanceId");
provisionExistingInstance(current, previous, null, true);
}
private ObjectNode instanceProperties() {
return mapper.createObjectNode().put("LaunchConfigurationName", "my-lc")
.put("InstanceId", "i-original").put("InstanceType", "t3.micro");
}
private StackResource provisionExistingInstance(ObjectNode current, JsonNode previous,
PropertyChanges changes, boolean rejected) {
LaunchConfiguration lc = new LaunchConfiguration();
lc.setLaunchConfigurationName("my-lc");
lc.setImageId("ami-original");
lc.setInstanceType("t3.micro");
when(autoScaling.describeLaunchConfigurations(REGION, List.of("my-lc"))).thenReturn(List.of(lc));
StackResource resource = resource(LAUNCH_CONFIGURATION, "Lc", "my-lc");
ProvisionContext original = ctx("my-lc");
ProvisionContext context = new ProvisionContext(original.engine(), REGION, "000000000000",
"my-stack", "my-lc", event -> {}, previous, changes);
if (rejected) {
AwsException failure = assertThrows(AwsException.class,
() -> provisioner.provision(resource, current, context));
assertEquals("ValidationError", failure.getErrorCode());
assertTrue(failure.getMessage().contains("Rename my-lc"));
assertTrue(resource.getAttributes().isEmpty());
} else {
provisioner.provision(resource, current, context);
}
verify(autoScaling, never()).createLaunchConfiguration(anyString(), anyString(), any(), any(),
any(), any(), anyList(), any(), any(), any(), any(), anyList(), any());
verify(autoScaling, never()).deleteLaunchConfiguration(anyString(), anyString());
return resource;
}
@Test
void launchConfigurationUpdateLeavesTheExistingOneAlone() {
// An unchanged legacy configuration keeps its physical identity.
LaunchConfiguration lc = new LaunchConfiguration();
lc.setLaunchConfigurationName("my-lc");
lc.setImageId("ami-2");
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");
@@ -84,7 +84,6 @@ AWS::AutoScaling::AutoScalingGroup NotificationConfigurations accepted and ignor
AWS::AutoScaling::AutoScalingGroup PlacementGroup accepted and ignored
AWS::AutoScaling::AutoScalingGroup SkipZonalShiftValidation accepted and ignored
AWS::AutoScaling::AutoScalingGroup TrafficSources accepted and ignored
AWS::AutoScaling::LaunchConfiguration BlockDeviceMappings accepted and ignored
AWS::AutoScaling::LaunchConfiguration ClassicLinkVPCId accepted and ignored
AWS::AutoScaling::LaunchConfiguration ClassicLinkVPCSecurityGroups accepted and ignored
AWS::AutoScaling::LaunchConfiguration EbsOptimized accepted and ignored
1 AWS::ApiGateway::ApiKey StageKeys accepted and ignored, as the ApiGatewayApiKeyCfnProvisioner javadoc records
84 AWS::AutoScaling::AutoScalingGroup PlacementGroup accepted and ignored
85 AWS::AutoScaling::AutoScalingGroup SkipZonalShiftValidation accepted and ignored
86 AWS::AutoScaling::AutoScalingGroup TrafficSources accepted and ignored
AWS::AutoScaling::LaunchConfiguration BlockDeviceMappings accepted and ignored
87 AWS::AutoScaling::LaunchConfiguration ClassicLinkVPCId accepted and ignored
88 AWS::AutoScaling::LaunchConfiguration ClassicLinkVPCSecurityGroups accepted and ignored
89 AWS::AutoScaling::LaunchConfiguration EbsOptimized accepted and ignored