mirror of
https://github.com/floci-io/floci.git
synced 2026-11-24 06:20:24 -05:00
feat(cloudformation): provision AWS::EC2::LaunchTemplate (#1973)
* feat(cloudformation): provision AWS::EC2::LaunchTemplate Create the launch template in Ec2Service from LaunchTemplateData (ImageId, InstanceType, KeyName, SecurityGroupIds, UserData, IamInstanceProfile). Ref resolves to the launch template id and Fn::GetAtt exposes LatestVersionNumber/DefaultVersionNumber, which CDK ASGs and instances reference. DeleteStack removes the template. Fixes #1971 * feat(cloudformation): resolve EC2 instance config from its LaunchTemplate reference An AWS::EC2::Instance that sets LaunchTemplate instead of direct properties now fills ImageId/InstanceType/KeyName from the referenced template's data (AWS resolution order), so instances launched from a launch template no longer fail with 'The request must contain the parameter ImageId'. * refactor(cloudformation): move AWS::EC2::LaunchTemplate into a per-service provisioner Follows the CfnResourceProvisioner pattern instead of growing the monolithic switch: Ec2LaunchTemplateCfnProvisioner injects only Ec2Service and is picked up by CloudFormationResourceRegistry via CDI. Provision and delete arms for AWS::EC2::LaunchTemplate are removed from CloudFormationResourceProvisioner along with the now-unused private provisionLaunchTemplate method. EC2 instance resolution against a referenced launch template stays put, since AWS::EC2::Instance is not extracted yet. An IamInstanceProfile given only by Name is now normalized to its instance-profile ARN, matching the EC2 query API path; previously the bare name was stored as if it were an ARN. Adds unit coverage for the new provisioner (attributes, generated name, profile ARN normalization, security groups, delete). * test(cloudformation): delete the launch-template instance stack so EC2 state stays clean The instance case left its stack standing, so a running instance (and its network interface) leaked into the shared emulator state for the rest of the suite. That pushed the total interface count past the MaxResults=5 boundary Ec2IntegrationTest's DescribeNetworkInterfaces pagination cases assert on, and they failed in full-suite runs while passing in isolation. Deleting the stack terminates the instance, which describeNetworkInterfaces skips. * fix(cloudformation): update a launch template in place instead of recreating it UpdateStack re-provisions every resource, and the provisioner called createLaunchTemplate unconditionally. An explicit LaunchTemplateName therefore hit InvalidLaunchTemplateName.AlreadyExistsException on every update, and an omitted one generated a fresh random name, creating a second template and orphaning the first. A template whose name has not changed is now updated by publishing a new version and keeping its physical id, which is how AWS::EC2::LaunchTemplate behaves when only its LaunchTemplateData changes. An unnamed template keeps the name generated at create time rather than minting a new one. A changed name is a replacement: the new template is created first and the previous one deleted only after that succeeds.
This commit is contained in:
1 parent
1a99721ae0
commit
4e0a815f20
4 files changed
+546
-1
No files matched your search
+25
-1
@@ -934,10 +934,34 @@ public class CloudFormationResourceProvisioner {
|
||||
String region) {
|
||||
String imageId = resolveOptional(props, "ImageId", engine);
|
||||
String instanceType = resolveOptional(props, "InstanceType", engine);
|
||||
String keyName = resolveOptional(props, "KeyName", engine);
|
||||
|
||||
// An instance may reference a LaunchTemplate for its config; fields the
|
||||
// properties don't set resolve from the template's data, as on AWS.
|
||||
if (props != null && props.has("LaunchTemplate")) {
|
||||
JsonNode ltRef = engine.resolveNode(props.get("LaunchTemplate"));
|
||||
try {
|
||||
var ltData = ec2Service.resolveLaunchTemplateData(region,
|
||||
ltRef.path("LaunchTemplateId").asText(null),
|
||||
ltRef.path("LaunchTemplateName").asText(null),
|
||||
ltRef.path("Version").asText(null));
|
||||
if (imageId == null || imageId.isBlank()) {
|
||||
imageId = ltData.getImageId();
|
||||
}
|
||||
if (instanceType == null || instanceType.isBlank()) {
|
||||
instanceType = ltData.getInstanceType();
|
||||
}
|
||||
if (keyName == null || keyName.isBlank()) {
|
||||
keyName = ltData.getKeyName();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
LOG.debugv("Could not resolve launch template for instance {0}: {1}",
|
||||
r.getLogicalId(), e.getMessage());
|
||||
}
|
||||
}
|
||||
if (instanceType == null || instanceType.isBlank()) {
|
||||
instanceType = "t3.micro";
|
||||
}
|
||||
String keyName = resolveOptional(props, "KeyName", engine);
|
||||
String subnetId = resolveOptional(props, "SubnetId", engine);
|
||||
String userData = resolveOptional(props, "UserData", engine);
|
||||
String iamInstanceProfile = resolveOptional(props, "IamInstanceProfile", engine);
|
||||
|
||||
+130
@@ -0,0 +1,130 @@
|
||||
package io.github.hectorvent.floci.services.cloudformation.provisioners;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import io.github.hectorvent.floci.core.common.AwsArnUtils;
|
||||
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
|
||||
import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* CloudFormation provisioning for {@code AWS::EC2::LaunchTemplate} (issue #1971).
|
||||
*/
|
||||
@ApplicationScoped
|
||||
public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private final Ec2Service ec2Service;
|
||||
|
||||
@Inject
|
||||
public Ec2LaunchTemplateCfnProvisioner(Ec2Service ec2Service) {
|
||||
this.ec2Service = ec2Service;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of("AWS::EC2::LaunchTemplate");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
String previousId = r.getPhysicalId();
|
||||
LaunchTemplate existing = previousId == null ? null : findExisting(ctx.region(), previousId);
|
||||
String declaredName = ctx.resolveOptional(props, "LaunchTemplateName");
|
||||
String name;
|
||||
if (declaredName != null && !declaredName.isBlank()) {
|
||||
name = declaredName;
|
||||
} else if (existing != null) {
|
||||
// Keep the name generated at create time; generating a fresh one on every update is
|
||||
// what made an unnamed template multiply.
|
||||
name = existing.getLaunchTemplateName();
|
||||
} else {
|
||||
name = ctx.generatePhysicalName(r.getLogicalId(), 128, false);
|
||||
}
|
||||
String imageId = null;
|
||||
String instanceType = null;
|
||||
String keyName = null;
|
||||
String encodedUserData = null;
|
||||
String iamInstanceProfileArn = null;
|
||||
List<String> securityGroupIds = null;
|
||||
if (props != null && props.has("LaunchTemplateData")) {
|
||||
JsonNode data = ctx.engine().resolveNode(props.get("LaunchTemplateData"));
|
||||
imageId = data.path("ImageId").asText(null);
|
||||
instanceType = data.path("InstanceType").asText(null);
|
||||
keyName = data.path("KeyName").asText(null);
|
||||
// CFN carries UserData already base64-encoded.
|
||||
encodedUserData = data.path("UserData").asText(null);
|
||||
iamInstanceProfileArn = resolveIamInstanceProfileArn(data.path("IamInstanceProfile"), ctx);
|
||||
if (data.has("SecurityGroupIds")) {
|
||||
securityGroupIds = new ArrayList<>();
|
||||
for (JsonNode sg : data.get("SecurityGroupIds")) {
|
||||
securityGroupIds.add(sg.asText());
|
||||
}
|
||||
}
|
||||
}
|
||||
// UpdateStack re-provisions every resource. Creating unconditionally meant an explicit
|
||||
// LaunchTemplateName hit InvalidLaunchTemplateName.AlreadyExistsException, while an
|
||||
// omitted one minted a second randomly named template and orphaned the first. A template
|
||||
// whose name has not changed is updated in place by publishing a new version, which is how
|
||||
// AWS::EC2::LaunchTemplate behaves when only its LaunchTemplateData changes.
|
||||
LaunchTemplate lt;
|
||||
if (existing != null && name.equals(existing.getLaunchTemplateName())) {
|
||||
lt = ec2Service.createLaunchTemplateVersion(ctx.region(), previousId, null, null,
|
||||
imageId, instanceType, keyName, securityGroupIds, null, encodedUserData,
|
||||
iamInstanceProfileArn, null);
|
||||
} else {
|
||||
lt = ec2Service.createLaunchTemplate(ctx.region(), name, imageId, instanceType, keyName,
|
||||
securityGroupIds, null, encodedUserData, iamInstanceProfileArn, null, null);
|
||||
// A changed name is a replacement: drop the template the previous execution created,
|
||||
// once the new one exists, so the old one is not left behind.
|
||||
if (existing != null) {
|
||||
try {
|
||||
ec2Service.deleteLaunchTemplate(ctx.region(), previousId, null);
|
||||
} catch (RuntimeException ignored) {
|
||||
// already gone — nothing to clean up
|
||||
}
|
||||
}
|
||||
}
|
||||
r.setPhysicalId(lt.getLaunchTemplateId());
|
||||
r.getAttributes().put("LaunchTemplateId", lt.getLaunchTemplateId());
|
||||
r.getAttributes().put("LatestVersionNumber", lt.getLatestVersionNumber());
|
||||
r.getAttributes().put("DefaultVersionNumber", lt.getDefaultVersionNumber());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
ec2Service.deleteLaunchTemplate(region, physicalId, null);
|
||||
}
|
||||
|
||||
/** The template a previous execution created, or null when it is gone. */
|
||||
private LaunchTemplate findExisting(String region, String launchTemplateId) {
|
||||
try {
|
||||
return ec2Service.describeLaunchTemplates(region, List.of(launchTemplateId), List.of(), Map.of())
|
||||
.stream().findFirst().orElse(null);
|
||||
} catch (RuntimeException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A profile given only by {@code Name} is normalized to its instance-profile ARN, matching
|
||||
* what the EC2 query API does for {@code IamInstanceProfile.Name} request parameters
|
||||
* (see {@code Ec2QueryHandler#resolveIamInstanceProfileArn}).
|
||||
*/
|
||||
private String resolveIamInstanceProfileArn(JsonNode profile, ProvisionContext ctx) {
|
||||
String arn = profile.path("Arn").asText(null);
|
||||
if (arn != null && !arn.isBlank()) {
|
||||
return arn;
|
||||
}
|
||||
String profileName = profile.path("Name").asText(null);
|
||||
if (profileName == null || profileName.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return AwsArnUtils.Arn.of("iam", "", ctx.accountId(), "instance-profile/" + profileName).toString();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user