mirror of
https://github.com/floci-io/floci.git
synced 2026-11-23 14:10:49 -05:00
fix(ec2): round-trip launch template data instead of discarding it (#2595)
* fix(ec2): round-trip launch template data instead of discarding it CreateLaunchTemplate returned 200 and kept only ImageId, InstanceType, KeyName, UserData, IamInstanceProfile, SecurityGroupIds and TagSpecifications. Every other member of RequestLaunchTemplateData was dropped without a word, so Terraform read back its own input missing and reported "Provider produced inconsistent result after apply", or diffed forever. MetadataOptions with HttpTokens=required (IMDSv2) and BlockDeviceMappings appear in most Gruntwork ASG and ECS modules. The AWS EC2 service model is the reference for what is stored and for the element names it is read back under: request parameter names are the ones botocore's EC2 serializer emits (note the singular BlockDeviceMapping.N and NetworkInterface.N list prefixes, taken from each list member's locationName), and response elements use ResponseLaunchTemplateData's locationNames. Stored and read back unchanged: ImageId, InstanceType, KeyName, UserData, KernelId, RamDiskId, SecurityGroupIds, IamInstanceProfile, BlockDeviceMappings, NetworkInterfaces, TagSpecifications, MetadataOptions, Monitoring, Placement, CpuOptions, CreditSpecification, EnclaveOptions, HibernationOptions, MaintenanceOptions, PrivateDnsNameOptions, CapacityReservationSpecification, EbsOptimized, DisableApiTermination, DisableApiStop, InstanceInitiatedShutdownBehavior. Two further contradictions in the same call, both fixed: - IamInstanceProfile keeps the form it was given. A profile submitted as Name reads back as Name rather than being rewritten to an Arn, so aws_launch_template.iam_instance_profile.name converges. The instance-profile ARN is derived at launch time instead. - NetworkInterfaces survives as a NetworkInterfaces block. Its Groups are no longer hoisted into top-level SecurityGroupIds; on AWS the two are mutually exclusive, and the promotion made the block vanish from state. A launch resolves security groups from whichever of the two is set. Deliberately out of scope, accepted and ignored rather than rejected: InstanceMarketOptions, InstanceRequirements, LicenseSpecifications, ElasticGpuSpecifications, ElasticInferenceAccelerators, NetworkPerformanceOptions, Operator, SecondaryInterfaces, and SecurityGroups (groups by name). Within NetworkInterfaces the IPv4/IPv6 address and prefix lists, EnaSrdSpecification, ConnectionTrackingSpecification, PrimaryIpv6 and EnaQueueCount are also ignored. A focused subset that round-trips beats a broad partial one. LaunchTemplate no longer mirrors launch data in flat fields alongside its version map; it holds one LaunchTemplateData, which removes the dataFrom/applyData sync and collapses two 11-argument service methods into a parameter object with explicit merge semantics for version creation. Fixes a compatibility defect this collapse introduced (flagged by review): a template persisted before this change stored the IAM instance profile as a bare iamInstanceProfileArn string and instance tags as a flat instanceTags list, both directly on LaunchTemplate and, separately, inside each entry of its versions map. Neither key exists on the new model, so ignoreUnknown silently dropped both on load - an upgrade would launch from an existing template with no IAM profile and no instance tags, with nothing in the logs to say so. Legacy @JsonSetters on LaunchTemplateData and LaunchTemplate map both old keys onto the new shape at load time, covering the versions-map entry (the path DescribeLaunchTemplateVersions and AutoScaling actually read) and the top-level fields (the path a template with no versions map falls back to). Deserialize-only, so a file saved by the current code never regains the old shape. Ec2ServicePersistenceTest#legacyIamProfileAndInstanceTagsSurviveRestart seeds a hand-built pre-migration ec2-launch-templates.json and asserts both paths survive a restart; reverting the two model changes alone fails it. * fix(ec2): correct SourceVersion inheritance and round-trip VersionDescription Addresses review feedback on the prior commit: - CreateLaunchTemplateVersion with SourceVersion omitted merged onto the latest version instead of following the AWS-documented "no source specified, no inheritance" behavior. A version created without SourceVersion now starts from an empty LaunchTemplateData, populated only by whatever fields the request itself supplies. - VersionDescription was accepted and silently dropped. It is a version-level field on LaunchTemplateVersion, not a member of RequestLaunchTemplateData, so it is tracked in a parallel per-version map on LaunchTemplate (alongside VersionNumber, CreateTime) rather than inside LaunchTemplateData, and round-trips through DescribeLaunchTemplateVersions. CreateLaunchTemplate accepts the same field for the initial version. - SecurityGroups (security groups by name) stays out of scope: resolving names to IDs would need lookup machinery - store scan, not-found handling, ambiguity across VPCs - that no other EC2 action here has either (RunInstances itself only accepts SecurityGroupId). Documented the reasoning in both the code and docs/services/ec2.md so the ignored list stays accurate now that SourceVersion and VersionDescription are handled correctly.
This commit is contained in:
1 parent
2963601f69
commit
f1ad306599
15 files changed
+1843
-313
No files matched your search
@@ -472,6 +472,52 @@ Route table ids follow the live API's own inconsistency: an id that does not exi
|
||||
|
||||
Launch templates store versioned launch data. New template versions can be created from an existing source version, and `ModifyLaunchTemplate` updates the default version used by later launches.
|
||||
|
||||
#### Launch template data members
|
||||
|
||||
These members of `RequestLaunchTemplateData` are stored and read back unchanged by
|
||||
`DescribeLaunchTemplateVersions`:
|
||||
|
||||
`ImageId`, `InstanceType`, `KeyName`, `UserData`, `KernelId`, `RamDiskId`, `SecurityGroupIds`,
|
||||
`IamInstanceProfile`, `BlockDeviceMappings`, `NetworkInterfaces`, `TagSpecifications`,
|
||||
`MetadataOptions`, `Monitoring`, `Placement`, `CpuOptions`, `CreditSpecification`,
|
||||
`EnclaveOptions`, `HibernationOptions`, `MaintenanceOptions`, `PrivateDnsNameOptions`,
|
||||
`CapacityReservationSpecification`, `EbsOptimized`, `DisableApiTermination`, `DisableApiStop`,
|
||||
`InstanceInitiatedShutdownBehavior`.
|
||||
|
||||
Two behaviours worth calling out, because they are what Terraform reads back:
|
||||
|
||||
- **`IamInstanceProfile` keeps the form it was given.** A profile submitted as `Name` reads back as
|
||||
`Name`, not rewritten to `Arn`. The instance-profile ARN is derived at launch time instead, so
|
||||
`aws_launch_template.iam_instance_profile.name` converges.
|
||||
- **`NetworkInterfaces` stays a `NetworkInterfaces` block.** Its `Groups` are not hoisted into
|
||||
top-level `SecurityGroupIds`; on AWS the two are mutually exclusive. A launch from the template
|
||||
resolves its security groups from whichever of the two is populated.
|
||||
|
||||
#### Launch template versions
|
||||
|
||||
`CreateLaunchTemplateVersion` accepts two members outside `LaunchTemplateData` itself:
|
||||
|
||||
- **`SourceVersion` controls inheritance, and omitting it means no inheritance.** A request that
|
||||
names a source version — including `$Latest` or `$Default` — layers its own fields onto that
|
||||
version's data, so only the fields it restates change. A request that omits `SourceVersion`
|
||||
entirely does **not** fall back to the latest version: the new version starts from an empty
|
||||
`LaunchTemplateData`, populated only by whatever fields the request itself supplies. This matches
|
||||
the AWS-documented behavior; it does not merge onto any prior version.
|
||||
- **`VersionDescription` is stored and read back by `DescribeLaunchTemplateVersions`.** It is a
|
||||
version-level field on `LaunchTemplateVersion`, not a member of `RequestLaunchTemplateData` /
|
||||
`ResponseLaunchTemplateData`, so it is tracked per version alongside `VersionNumber` and
|
||||
`CreateTime` rather than inside the launch template data payload. `CreateLaunchTemplate` accepts
|
||||
the same field for the initial version it creates.
|
||||
|
||||
Members the service model declares that are accepted and ignored rather than stored:
|
||||
`InstanceMarketOptions`, `InstanceRequirements`, `LicenseSpecifications`, `ElasticGpuSpecifications`,
|
||||
`ElasticInferenceAccelerators`, `NetworkPerformanceOptions`, `Operator`, `SecondaryInterfaces` and
|
||||
`SecurityGroups` (security groups by name — resolving names to IDs would need lookup machinery,
|
||||
including ambiguity handling across VPCs, that no other EC2 action here has either; `RunInstances`
|
||||
itself only accepts `SecurityGroupId`). Within `NetworkInterfaces`, the IPv4/IPv6 address and
|
||||
prefix lists, `EnaSrdSpecification`, `ConnectionTrackingSpecification`, `PrimaryIpv6` and
|
||||
`EnaQueueCount` are likewise ignored.
|
||||
|
||||
### IAM Instance Profiles
|
||||
|
||||
| Action | Description |
|
||||
|
||||
+14
-14
@@ -440,13 +440,13 @@ public class AutoScalingReconciler {
|
||||
: asg.getLaunchTemplateVersion();
|
||||
return new LaunchSource(
|
||||
null,
|
||||
version.getImageId(),
|
||||
version.getInstanceType(),
|
||||
version.getKeyName(),
|
||||
version.getSecurityGroupIds(),
|
||||
version.getInstanceTags(),
|
||||
version.getUserData(),
|
||||
version.getIamInstanceProfileArn(),
|
||||
version.getData().getImageId(),
|
||||
version.getData().getInstanceType(),
|
||||
version.getData().getKeyName(),
|
||||
version.getData().effectiveSecurityGroupIds(),
|
||||
version.getData().getInstanceTags(),
|
||||
version.getData().getUserData(),
|
||||
ec2Service.iamInstanceProfileArn(version.getData()),
|
||||
asg.getLaunchTemplateId(),
|
||||
asg.getLaunchTemplateName(),
|
||||
resolvedVersion,
|
||||
@@ -470,13 +470,13 @@ public class AutoScalingReconciler {
|
||||
String instanceType = mixedInstancesInstanceType(asg, version);
|
||||
return new LaunchSource(
|
||||
null,
|
||||
version.getImageId(),
|
||||
version.getData().getImageId(),
|
||||
instanceType,
|
||||
version.getKeyName(),
|
||||
version.getSecurityGroupIds(),
|
||||
version.getInstanceTags(),
|
||||
version.getUserData(),
|
||||
version.getIamInstanceProfileArn(),
|
||||
version.getData().getKeyName(),
|
||||
version.getData().effectiveSecurityGroupIds(),
|
||||
version.getData().getInstanceTags(),
|
||||
version.getData().getUserData(),
|
||||
ec2Service.iamInstanceProfileArn(version.getData()),
|
||||
specification.getLaunchTemplateId() == null
|
||||
? mixedLaunchTemplate.getLaunchTemplateId()
|
||||
: specification.getLaunchTemplateId(),
|
||||
@@ -557,7 +557,7 @@ public class AutoScalingReconciler {
|
||||
}
|
||||
}
|
||||
}
|
||||
return version.getInstanceType();
|
||||
return version.getData().getInstanceType();
|
||||
}
|
||||
|
||||
private record LaunchSource(
|
||||
|
||||
+1
-1
@@ -825,7 +825,7 @@ public class AutoScalingService {
|
||||
if (launchTemplateVersions.isEmpty()) {
|
||||
throw invalidLaunchTemplate();
|
||||
}
|
||||
if (isBlank(launchTemplateVersions.getFirst().getImageId())) {
|
||||
if (isBlank(launchTemplateVersions.getFirst().getData().getImageId())) {
|
||||
throw missingLaunchTemplateImageId();
|
||||
}
|
||||
}
|
||||
|
||||
+23
-31
@@ -1,10 +1,10 @@
|
||||
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 io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import jakarta.enterprise.context.ApplicationScoped;
|
||||
import jakarta.inject.Inject;
|
||||
|
||||
@@ -46,25 +46,21 @@ public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
|
||||
} 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;
|
||||
LaunchTemplateData data = new LaunchTemplateData();
|
||||
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);
|
||||
JsonNode node = ctx.engine().resolveNode(props.get("LaunchTemplateData"));
|
||||
data.setImageId(node.path("ImageId").asText(null));
|
||||
data.setInstanceType(node.path("InstanceType").asText(null));
|
||||
data.setKeyName(node.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());
|
||||
data.setEncodedUserData(node.path("UserData").asText(null));
|
||||
data.setIamInstanceProfile(iamInstanceProfile(node.path("IamInstanceProfile")));
|
||||
if (node.has("SecurityGroupIds")) {
|
||||
List<String> securityGroupIds = new ArrayList<>();
|
||||
for (JsonNode securityGroup : node.get("SecurityGroupIds")) {
|
||||
securityGroupIds.add(securityGroup.asText());
|
||||
}
|
||||
data.setSecurityGroupIds(securityGroupIds);
|
||||
}
|
||||
}
|
||||
// UpdateStack re-provisions every resource. Creating unconditionally meant an explicit
|
||||
@@ -74,12 +70,9 @@ public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
|
||||
// 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);
|
||||
lt = ec2Service.createLaunchTemplateVersion(ctx.region(), previousId, null, null, data);
|
||||
} else {
|
||||
lt = ec2Service.createLaunchTemplate(ctx.region(), name, imageId, instanceType, keyName,
|
||||
securityGroupIds, null, encodedUserData, iamInstanceProfileArn, null, null);
|
||||
lt = ec2Service.createLaunchTemplate(ctx.region(), name, data, 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) {
|
||||
@@ -112,19 +105,18 @@ public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}).
|
||||
* Keeps the form CloudFormation supplied. EC2 stores {@code Arn} and {@code Name} as given and
|
||||
* derives the ARN only at launch time, so normalizing {@code Name} into an ARN here would put
|
||||
* back the drift this provisioner's template data is read back through.
|
||||
*/
|
||||
private String resolveIamInstanceProfileArn(JsonNode profile, ProvisionContext ctx) {
|
||||
private LaunchTemplateData.IamInstanceProfile iamInstanceProfile(JsonNode profile) {
|
||||
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()) {
|
||||
boolean hasArn = arn != null && !arn.isBlank();
|
||||
boolean hasName = profileName != null && !profileName.isBlank();
|
||||
if (!hasArn && !hasName) {
|
||||
return null;
|
||||
}
|
||||
return AwsArnUtils.Arn.of("iam", "", ctx.accountId(), "instance-profile/" + profileName).toString();
|
||||
return new LaunchTemplateData.IamInstanceProfile(hasArn ? arn : null, hasName ? profileName : null);
|
||||
}
|
||||
}
|
||||
@@ -494,23 +494,6 @@ public class Ec2QueryHandler {
|
||||
return tags;
|
||||
}
|
||||
|
||||
private List<Tag> parseLaunchTemplateDataTagsForResource(MultivaluedMap<String, String> p, String resourceType) {
|
||||
List<Tag> tags = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String resType = p.getFirst("LaunchTemplateData.TagSpecification." + i + ".ResourceType");
|
||||
if (resType == null) break;
|
||||
if (resourceType.equals(resType)) {
|
||||
for (int j = 1; ; j++) {
|
||||
String key = p.getFirst("LaunchTemplateData.TagSpecification." + i + ".Tag." + j + ".Key");
|
||||
if (key == null) break;
|
||||
String value = p.getFirst("LaunchTemplateData.TagSpecification." + i + ".Tag." + j + ".Value");
|
||||
tags.add(new Tag(key, value));
|
||||
}
|
||||
}
|
||||
}
|
||||
return tags;
|
||||
}
|
||||
|
||||
// Apply tags supplied inline on a create call (TagSpecification) to the resource, so
|
||||
// they round-trip on the next Describe* — otherwise the provider sees phantom tag drift.
|
||||
private void applyResourceTags(MultivaluedMap<String, String> p, String region, String resourceType, String resourceId) {
|
||||
@@ -653,9 +636,10 @@ public class Ec2QueryHandler {
|
||||
instanceType = firstNonBlank(instanceType, launchTemplateData.getInstanceType());
|
||||
keyName = firstNonBlank(keyName, launchTemplateData.getKeyName());
|
||||
userData = firstNonBlank(userData, launchTemplateData.getUserData());
|
||||
iamInstanceProfileArn = firstNonBlank(iamInstanceProfileArn, launchTemplateData.getIamInstanceProfileArn());
|
||||
iamInstanceProfileArn = firstNonBlank(iamInstanceProfileArn,
|
||||
service.iamInstanceProfileArn(launchTemplateData));
|
||||
if (sgIds.isEmpty()) {
|
||||
sgIds = new ArrayList<>(launchTemplateData.getSecurityGroupIds());
|
||||
sgIds = new ArrayList<>(launchTemplateData.effectiveSecurityGroupIds());
|
||||
}
|
||||
if (!launchTemplateData.getInstanceTags().isEmpty()) {
|
||||
Map<String, Tag> mergedTags = new LinkedHashMap<>();
|
||||
@@ -3250,19 +3234,12 @@ public class Ec2QueryHandler {
|
||||
// ─── Launch Template handlers ─────────────────────────────────────────────
|
||||
|
||||
private Response handleCreateLaunchTemplate(MultivaluedMap<String, String> p, String region) {
|
||||
String encodedUserData = p.getFirst("LaunchTemplateData.UserData");
|
||||
LaunchTemplate launchTemplate = service.createLaunchTemplate(
|
||||
region,
|
||||
p.getFirst("LaunchTemplateName"),
|
||||
p.getFirst("LaunchTemplateData.ImageId"),
|
||||
p.getFirst("LaunchTemplateData.InstanceType"),
|
||||
p.getFirst("LaunchTemplateData.KeyName"),
|
||||
parseLaunchTemplateSecurityGroupIds(p),
|
||||
decodeUserData(encodedUserData),
|
||||
encodedUserData,
|
||||
resolveIamInstanceProfileArn(p, "LaunchTemplateData.IamInstanceProfile"),
|
||||
parseLaunchTemplateData(p),
|
||||
parseTagsForResource(p, "launch-template"),
|
||||
parseLaunchTemplateDataTagsForResource(p, "instance"));
|
||||
p.getFirst("VersionDescription"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateLaunchTemplateResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
@@ -3272,20 +3249,13 @@ public class Ec2QueryHandler {
|
||||
}
|
||||
|
||||
private Response handleCreateLaunchTemplateVersion(MultivaluedMap<String, String> p, String region) {
|
||||
String encodedUserData = p.getFirst("LaunchTemplateData.UserData");
|
||||
LaunchTemplate launchTemplate = service.createLaunchTemplateVersion(
|
||||
region,
|
||||
p.getFirst("LaunchTemplateId"),
|
||||
p.getFirst("LaunchTemplateName"),
|
||||
p.getFirst("SourceVersion"),
|
||||
p.getFirst("LaunchTemplateData.ImageId"),
|
||||
p.getFirst("LaunchTemplateData.InstanceType"),
|
||||
p.getFirst("LaunchTemplateData.KeyName"),
|
||||
parseLaunchTemplateSecurityGroupIds(p),
|
||||
decodeUserData(encodedUserData),
|
||||
encodedUserData,
|
||||
resolveIamInstanceProfileArn(p, "LaunchTemplateData.IamInstanceProfile"),
|
||||
parseLaunchTemplateDataTagsForResource(p, "instance"));
|
||||
parseLaunchTemplateData(p),
|
||||
p.getFirst("VersionDescription"));
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.start("CreateLaunchTemplateVersionResponse", AwsNamespaces.EC2)
|
||||
.elem("requestId", UUID.randomUUID().toString())
|
||||
@@ -3814,56 +3784,451 @@ public class Ec2QueryHandler {
|
||||
xml.elem("createTime", ISO_FMT.format(launchTemplate.getCreateTime()));
|
||||
}
|
||||
xml.elem("createdBy", launchTemplate.getCreatedBy())
|
||||
.elem("versionDescription", launchTemplate.getVersionDescription())
|
||||
.start("launchTemplateData")
|
||||
.elem("imageId", launchTemplate.getImageId())
|
||||
.elem("instanceType", launchTemplate.getInstanceType());
|
||||
if (launchTemplate.getKeyName() != null) {
|
||||
xml.elem("keyName", launchTemplate.getKeyName());
|
||||
}
|
||||
if (launchTemplate.getEncodedUserData() != null) {
|
||||
xml.elem("userData", launchTemplate.getEncodedUserData());
|
||||
}
|
||||
if (launchTemplate.getIamInstanceProfileArn() != null) {
|
||||
xml.start("iamInstanceProfile")
|
||||
.elem("arn", launchTemplate.getIamInstanceProfileArn())
|
||||
.end("iamInstanceProfile");
|
||||
}
|
||||
xml.start("securityGroupIdSet");
|
||||
for (String securityGroupId : launchTemplate.getSecurityGroupIds()) {
|
||||
xml.elem("item", securityGroupId);
|
||||
}
|
||||
xml.end("securityGroupIdSet");
|
||||
if (launchTemplate.getInstanceTags() != null && !launchTemplate.getInstanceTags().isEmpty()) {
|
||||
xml.start("tagSpecificationSet")
|
||||
.start("item")
|
||||
.elem("resourceType", "instance")
|
||||
.raw(tagSetXml(launchTemplate.getInstanceTags()))
|
||||
.end("item")
|
||||
.end("tagSpecificationSet");
|
||||
}
|
||||
xml.end("launchTemplateData");
|
||||
.raw(launchTemplateDataXml(launchTemplate.getData()))
|
||||
.end("launchTemplateData");
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
private List<String> parseLaunchTemplateSecurityGroupIds(MultivaluedMap<String, String> p) {
|
||||
LinkedHashSet<String> groups = new LinkedHashSet<>(getList(p, "LaunchTemplateData.SecurityGroupId"));
|
||||
for (int i = 1; ; i++) {
|
||||
boolean sawInterface = false;
|
||||
for (String prefix : List.of(
|
||||
"LaunchTemplateData.NetworkInterface." + i + ".Groups",
|
||||
"LaunchTemplateData.NetworkInterface." + i + ".GroupId",
|
||||
"LaunchTemplateData.NetworkInterface." + i + ".SecurityGroupId")) {
|
||||
List<String> values = getList(p, prefix);
|
||||
if (!values.isEmpty()) {
|
||||
sawInterface = true;
|
||||
groups.addAll(values);
|
||||
/**
|
||||
* Renders {@code ResponseLaunchTemplateData}. Element names are the {@code locationName}s the
|
||||
* EC2 service model declares, so what the provider reads back matches what it submitted.
|
||||
*/
|
||||
private String launchTemplateDataXml(LaunchTemplateData data) {
|
||||
XmlBuilder xml = new XmlBuilder()
|
||||
.elem("imageId", data.getImageId())
|
||||
.elem("instanceType", data.getInstanceType())
|
||||
.elem("kernelId", data.getKernelId())
|
||||
.elem("ramDiskId", data.getRamDiskId())
|
||||
.elem("keyName", data.getKeyName())
|
||||
.elem("userData", data.getEncodedUserData())
|
||||
.elem("ebsOptimized", str(data.getEbsOptimized()))
|
||||
.elem("disableApiTermination", str(data.getDisableApiTermination()))
|
||||
.elem("disableApiStop", str(data.getDisableApiStop()))
|
||||
.elem("instanceInitiatedShutdownBehavior", data.getInstanceInitiatedShutdownBehavior());
|
||||
|
||||
LaunchTemplateData.IamInstanceProfile profile = data.getIamInstanceProfile();
|
||||
if (profile != null && (profile.getArn() != null || profile.getName() != null)) {
|
||||
xml.start("iamInstanceProfile")
|
||||
.elem("arn", profile.getArn())
|
||||
.elem("name", profile.getName())
|
||||
.end("iamInstanceProfile");
|
||||
}
|
||||
|
||||
if (!data.getBlockDeviceMappings().isEmpty()) {
|
||||
xml.start("blockDeviceMappingSet");
|
||||
for (LaunchTemplateData.BlockDeviceMapping mapping : data.getBlockDeviceMappings()) {
|
||||
xml.start("item")
|
||||
.elem("deviceName", mapping.getDeviceName())
|
||||
.elem("virtualName", mapping.getVirtualName())
|
||||
.elem("noDevice", mapping.getNoDevice());
|
||||
LaunchTemplateData.Ebs ebs = mapping.getEbs();
|
||||
if (ebs != null) {
|
||||
xml.start("ebs")
|
||||
.elem("encrypted", str(ebs.getEncrypted()))
|
||||
.elem("deleteOnTermination", str(ebs.getDeleteOnTermination()))
|
||||
.elem("iops", str(ebs.getIops()))
|
||||
.elem("kmsKeyId", ebs.getKmsKeyId())
|
||||
.elem("snapshotId", ebs.getSnapshotId())
|
||||
.elem("volumeSize", str(ebs.getVolumeSize()))
|
||||
.elem("volumeType", ebs.getVolumeType())
|
||||
.elem("throughput", str(ebs.getThroughput()))
|
||||
.end("ebs");
|
||||
}
|
||||
xml.end("item");
|
||||
}
|
||||
if (!sawInterface && p.getFirst("LaunchTemplateData.NetworkInterface." + i + ".DeviceIndex") == null) {
|
||||
xml.end("blockDeviceMappingSet");
|
||||
}
|
||||
|
||||
if (!data.getNetworkInterfaces().isEmpty()) {
|
||||
xml.start("networkInterfaceSet");
|
||||
for (LaunchTemplateData.NetworkInterface networkInterface : data.getNetworkInterfaces()) {
|
||||
xml.start("item")
|
||||
.elem("associatePublicIpAddress", str(networkInterface.getAssociatePublicIpAddress()))
|
||||
.elem("associateCarrierIpAddress", str(networkInterface.getAssociateCarrierIpAddress()))
|
||||
.elem("deleteOnTermination", str(networkInterface.getDeleteOnTermination()))
|
||||
.elem("description", networkInterface.getDescription())
|
||||
.elem("deviceIndex", str(networkInterface.getDeviceIndex()))
|
||||
.elem("interfaceType", networkInterface.getInterfaceType())
|
||||
.elem("ipv6AddressCount", str(networkInterface.getIpv6AddressCount()))
|
||||
.elem("networkInterfaceId", networkInterface.getNetworkInterfaceId())
|
||||
.elem("privateIpAddress", networkInterface.getPrivateIpAddress())
|
||||
.elem("secondaryPrivateIpAddressCount", str(networkInterface.getSecondaryPrivateIpAddressCount()))
|
||||
.elem("subnetId", networkInterface.getSubnetId())
|
||||
.elem("networkCardIndex", str(networkInterface.getNetworkCardIndex()));
|
||||
if (!networkInterface.getGroups().isEmpty()) {
|
||||
xml.start("groupSet");
|
||||
for (String group : networkInterface.getGroups()) {
|
||||
xml.elem("item", group);
|
||||
}
|
||||
xml.end("groupSet");
|
||||
}
|
||||
xml.end("item");
|
||||
}
|
||||
xml.end("networkInterfaceSet");
|
||||
}
|
||||
|
||||
LaunchTemplateData.MetadataOptions metadataOptions = data.getMetadataOptions();
|
||||
if (metadataOptions != null) {
|
||||
xml.start("metadataOptions")
|
||||
.elem("state", metadataOptions.getState() != null ? metadataOptions.getState() : "applied")
|
||||
.elem("httpTokens", metadataOptions.getHttpTokens())
|
||||
.elem("httpPutResponseHopLimit", str(metadataOptions.getHttpPutResponseHopLimit()))
|
||||
.elem("httpEndpoint", metadataOptions.getHttpEndpoint())
|
||||
.elem("httpProtocolIpv6", metadataOptions.getHttpProtocolIpv6())
|
||||
.elem("instanceMetadataTags", metadataOptions.getInstanceMetadataTags())
|
||||
.end("metadataOptions");
|
||||
}
|
||||
|
||||
LaunchTemplateData.Monitoring monitoring = data.getMonitoring();
|
||||
if (monitoring != null) {
|
||||
xml.start("monitoring").elem("enabled", str(monitoring.getEnabled())).end("monitoring");
|
||||
}
|
||||
|
||||
LaunchTemplateData.Placement placement = data.getPlacement();
|
||||
if (placement != null) {
|
||||
xml.start("placement")
|
||||
.elem("availabilityZone", placement.getAvailabilityZone())
|
||||
.elem("availabilityZoneId", placement.getAvailabilityZoneId())
|
||||
.elem("affinity", placement.getAffinity())
|
||||
.elem("groupName", placement.getGroupName())
|
||||
.elem("groupId", placement.getGroupId())
|
||||
.elem("hostId", placement.getHostId())
|
||||
.elem("tenancy", placement.getTenancy())
|
||||
.elem("spreadDomain", placement.getSpreadDomain())
|
||||
.elem("hostResourceGroupArn", placement.getHostResourceGroupArn())
|
||||
.elem("partitionNumber", str(placement.getPartitionNumber()))
|
||||
.end("placement");
|
||||
}
|
||||
|
||||
LaunchTemplateData.CpuOptions cpuOptions = data.getCpuOptions();
|
||||
if (cpuOptions != null) {
|
||||
xml.start("cpuOptions")
|
||||
.elem("coreCount", str(cpuOptions.getCoreCount()))
|
||||
.elem("threadsPerCore", str(cpuOptions.getThreadsPerCore()))
|
||||
.elem("amdSevSnp", cpuOptions.getAmdSevSnp())
|
||||
.end("cpuOptions");
|
||||
}
|
||||
|
||||
LaunchTemplateData.CreditSpecification creditSpecification = data.getCreditSpecification();
|
||||
if (creditSpecification != null) {
|
||||
xml.start("creditSpecification")
|
||||
.elem("cpuCredits", creditSpecification.getCpuCredits())
|
||||
.end("creditSpecification");
|
||||
}
|
||||
|
||||
LaunchTemplateData.EnclaveOptions enclaveOptions = data.getEnclaveOptions();
|
||||
if (enclaveOptions != null) {
|
||||
xml.start("enclaveOptions").elem("enabled", str(enclaveOptions.getEnabled())).end("enclaveOptions");
|
||||
}
|
||||
|
||||
LaunchTemplateData.HibernationOptions hibernationOptions = data.getHibernationOptions();
|
||||
if (hibernationOptions != null) {
|
||||
xml.start("hibernationOptions")
|
||||
.elem("configured", str(hibernationOptions.getConfigured()))
|
||||
.end("hibernationOptions");
|
||||
}
|
||||
|
||||
LaunchTemplateData.MaintenanceOptions maintenanceOptions = data.getMaintenanceOptions();
|
||||
if (maintenanceOptions != null) {
|
||||
xml.start("maintenanceOptions")
|
||||
.elem("autoRecovery", maintenanceOptions.getAutoRecovery())
|
||||
.end("maintenanceOptions");
|
||||
}
|
||||
|
||||
LaunchTemplateData.PrivateDnsNameOptions privateDnsNameOptions = data.getPrivateDnsNameOptions();
|
||||
if (privateDnsNameOptions != null) {
|
||||
xml.start("privateDnsNameOptions")
|
||||
.elem("hostnameType", privateDnsNameOptions.getHostnameType())
|
||||
.elem("enableResourceNameDnsARecord", str(privateDnsNameOptions.getEnableResourceNameDnsARecord()))
|
||||
.elem("enableResourceNameDnsAAAARecord", str(privateDnsNameOptions.getEnableResourceNameDnsAAAARecord()))
|
||||
.end("privateDnsNameOptions");
|
||||
}
|
||||
|
||||
LaunchTemplateData.CapacityReservationSpecification capacityReservation =
|
||||
data.getCapacityReservationSpecification();
|
||||
if (capacityReservation != null) {
|
||||
xml.start("capacityReservationSpecification")
|
||||
.elem("capacityReservationPreference", capacityReservation.getCapacityReservationPreference());
|
||||
LaunchTemplateData.CapacityReservationTarget target = capacityReservation.getCapacityReservationTarget();
|
||||
if (target != null) {
|
||||
xml.start("capacityReservationTarget")
|
||||
.elem("capacityReservationId", target.getCapacityReservationId())
|
||||
.elem("capacityReservationResourceGroupArn", target.getCapacityReservationResourceGroupArn())
|
||||
.end("capacityReservationTarget");
|
||||
}
|
||||
xml.end("capacityReservationSpecification");
|
||||
}
|
||||
|
||||
if (!data.getSecurityGroupIds().isEmpty()) {
|
||||
xml.start("securityGroupIdSet");
|
||||
for (String securityGroupId : data.getSecurityGroupIds()) {
|
||||
xml.elem("item", securityGroupId);
|
||||
}
|
||||
xml.end("securityGroupIdSet");
|
||||
}
|
||||
|
||||
if (!data.getTagSpecifications().isEmpty()) {
|
||||
xml.start("tagSpecificationSet");
|
||||
for (LaunchTemplateData.TagSpecification spec : data.getTagSpecifications()) {
|
||||
xml.start("item")
|
||||
.elem("resourceType", spec.getResourceType())
|
||||
.raw(tagSetXml(spec.getTags()))
|
||||
.end("item");
|
||||
}
|
||||
xml.end("tagSpecificationSet");
|
||||
}
|
||||
return xml.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses {@code RequestLaunchTemplateData} from the EC2 query wire format. Parameter names are
|
||||
* the ones botocore's EC2 serializer emits — list members carry the model's singular
|
||||
* {@code locationName}, which is why the prefixes are {@code BlockDeviceMapping.N} rather than
|
||||
* {@code BlockDeviceMappings.N}.
|
||||
*/
|
||||
private LaunchTemplateData parseLaunchTemplateData(MultivaluedMap<String, String> p) {
|
||||
String prefix = "LaunchTemplateData";
|
||||
LaunchTemplateData data = new LaunchTemplateData();
|
||||
data.setImageId(p.getFirst(prefix + ".ImageId"));
|
||||
data.setInstanceType(p.getFirst(prefix + ".InstanceType"));
|
||||
data.setKeyName(p.getFirst(prefix + ".KeyName"));
|
||||
data.setKernelId(p.getFirst(prefix + ".KernelId"));
|
||||
data.setRamDiskId(p.getFirst(prefix + ".RamDiskId"));
|
||||
data.setInstanceInitiatedShutdownBehavior(p.getFirst(prefix + ".InstanceInitiatedShutdownBehavior"));
|
||||
data.setEbsOptimized(boolParam(p, prefix + ".EbsOptimized"));
|
||||
data.setDisableApiTermination(boolParam(p, prefix + ".DisableApiTermination"));
|
||||
data.setDisableApiStop(boolParam(p, prefix + ".DisableApiStop"));
|
||||
|
||||
String encodedUserData = p.getFirst(prefix + ".UserData");
|
||||
data.setEncodedUserData(encodedUserData);
|
||||
data.setUserData(decodeUserData(encodedUserData));
|
||||
|
||||
String profileArn = p.getFirst(prefix + ".IamInstanceProfile.Arn");
|
||||
String profileName = p.getFirst(prefix + ".IamInstanceProfile.Name");
|
||||
if (isSet(profileArn) || isSet(profileName)) {
|
||||
data.setIamInstanceProfile(new LaunchTemplateData.IamInstanceProfile(
|
||||
isSet(profileArn) ? profileArn : null,
|
||||
isSet(profileName) ? profileName : null));
|
||||
}
|
||||
|
||||
// SecurityGroups (the by-name form, as opposed to SecurityGroupId) is deliberately not
|
||||
// parsed here. Resolving names to IDs would need real lookup machinery — scanning the
|
||||
// security-group store, handling "not found", and handling ambiguity across VPCs — that
|
||||
// RunInstances itself doesn't have today (it only accepts SecurityGroupId); see
|
||||
// docs/services/ec2.md's launch-template section.
|
||||
data.setSecurityGroupIds(getList(p, prefix + ".SecurityGroupId"));
|
||||
data.setBlockDeviceMappings(parseLaunchTemplateBlockDeviceMappings(p, prefix));
|
||||
data.setNetworkInterfaces(parseLaunchTemplateNetworkInterfaces(p, prefix));
|
||||
data.setTagSpecifications(parseLaunchTemplateTagSpecifications(p, prefix));
|
||||
|
||||
if (anyParamStartsWith(p, prefix + ".MetadataOptions.")) {
|
||||
LaunchTemplateData.MetadataOptions options = new LaunchTemplateData.MetadataOptions();
|
||||
options.setHttpTokens(p.getFirst(prefix + ".MetadataOptions.HttpTokens"));
|
||||
options.setHttpPutResponseHopLimit(intParam(p, prefix + ".MetadataOptions.HttpPutResponseHopLimit"));
|
||||
options.setHttpEndpoint(p.getFirst(prefix + ".MetadataOptions.HttpEndpoint"));
|
||||
options.setHttpProtocolIpv6(p.getFirst(prefix + ".MetadataOptions.HttpProtocolIpv6"));
|
||||
options.setInstanceMetadataTags(p.getFirst(prefix + ".MetadataOptions.InstanceMetadataTags"));
|
||||
data.setMetadataOptions(options);
|
||||
}
|
||||
|
||||
Boolean monitoringEnabled = boolParam(p, prefix + ".Monitoring.Enabled");
|
||||
if (monitoringEnabled != null) {
|
||||
LaunchTemplateData.Monitoring monitoring = new LaunchTemplateData.Monitoring();
|
||||
monitoring.setEnabled(monitoringEnabled);
|
||||
data.setMonitoring(monitoring);
|
||||
}
|
||||
|
||||
if (anyParamStartsWith(p, prefix + ".Placement.")) {
|
||||
LaunchTemplateData.Placement placement = new LaunchTemplateData.Placement();
|
||||
placement.setAvailabilityZone(p.getFirst(prefix + ".Placement.AvailabilityZone"));
|
||||
placement.setAvailabilityZoneId(p.getFirst(prefix + ".Placement.AvailabilityZoneId"));
|
||||
placement.setAffinity(p.getFirst(prefix + ".Placement.Affinity"));
|
||||
placement.setGroupName(p.getFirst(prefix + ".Placement.GroupName"));
|
||||
placement.setGroupId(p.getFirst(prefix + ".Placement.GroupId"));
|
||||
placement.setHostId(p.getFirst(prefix + ".Placement.HostId"));
|
||||
placement.setTenancy(p.getFirst(prefix + ".Placement.Tenancy"));
|
||||
placement.setSpreadDomain(p.getFirst(prefix + ".Placement.SpreadDomain"));
|
||||
placement.setHostResourceGroupArn(p.getFirst(prefix + ".Placement.HostResourceGroupArn"));
|
||||
placement.setPartitionNumber(intParam(p, prefix + ".Placement.PartitionNumber"));
|
||||
data.setPlacement(placement);
|
||||
}
|
||||
|
||||
if (anyParamStartsWith(p, prefix + ".CpuOptions.")) {
|
||||
LaunchTemplateData.CpuOptions cpuOptions = new LaunchTemplateData.CpuOptions();
|
||||
cpuOptions.setCoreCount(intParam(p, prefix + ".CpuOptions.CoreCount"));
|
||||
cpuOptions.setThreadsPerCore(intParam(p, prefix + ".CpuOptions.ThreadsPerCore"));
|
||||
cpuOptions.setAmdSevSnp(p.getFirst(prefix + ".CpuOptions.AmdSevSnp"));
|
||||
data.setCpuOptions(cpuOptions);
|
||||
}
|
||||
|
||||
String cpuCredits = p.getFirst(prefix + ".CreditSpecification.CpuCredits");
|
||||
if (isSet(cpuCredits)) {
|
||||
LaunchTemplateData.CreditSpecification creditSpecification = new LaunchTemplateData.CreditSpecification();
|
||||
creditSpecification.setCpuCredits(cpuCredits);
|
||||
data.setCreditSpecification(creditSpecification);
|
||||
}
|
||||
|
||||
Boolean enclaveEnabled = boolParam(p, prefix + ".EnclaveOptions.Enabled");
|
||||
if (enclaveEnabled != null) {
|
||||
LaunchTemplateData.EnclaveOptions enclaveOptions = new LaunchTemplateData.EnclaveOptions();
|
||||
enclaveOptions.setEnabled(enclaveEnabled);
|
||||
data.setEnclaveOptions(enclaveOptions);
|
||||
}
|
||||
|
||||
Boolean hibernationConfigured = boolParam(p, prefix + ".HibernationOptions.Configured");
|
||||
if (hibernationConfigured != null) {
|
||||
LaunchTemplateData.HibernationOptions hibernationOptions = new LaunchTemplateData.HibernationOptions();
|
||||
hibernationOptions.setConfigured(hibernationConfigured);
|
||||
data.setHibernationOptions(hibernationOptions);
|
||||
}
|
||||
|
||||
String autoRecovery = p.getFirst(prefix + ".MaintenanceOptions.AutoRecovery");
|
||||
if (isSet(autoRecovery)) {
|
||||
LaunchTemplateData.MaintenanceOptions maintenanceOptions = new LaunchTemplateData.MaintenanceOptions();
|
||||
maintenanceOptions.setAutoRecovery(autoRecovery);
|
||||
data.setMaintenanceOptions(maintenanceOptions);
|
||||
}
|
||||
|
||||
if (anyParamStartsWith(p, prefix + ".PrivateDnsNameOptions.")) {
|
||||
LaunchTemplateData.PrivateDnsNameOptions options = new LaunchTemplateData.PrivateDnsNameOptions();
|
||||
options.setHostnameType(p.getFirst(prefix + ".PrivateDnsNameOptions.HostnameType"));
|
||||
options.setEnableResourceNameDnsARecord(
|
||||
boolParam(p, prefix + ".PrivateDnsNameOptions.EnableResourceNameDnsARecord"));
|
||||
options.setEnableResourceNameDnsAAAARecord(
|
||||
boolParam(p, prefix + ".PrivateDnsNameOptions.EnableResourceNameDnsAAAARecord"));
|
||||
data.setPrivateDnsNameOptions(options);
|
||||
}
|
||||
|
||||
if (anyParamStartsWith(p, prefix + ".CapacityReservationSpecification.")) {
|
||||
LaunchTemplateData.CapacityReservationSpecification spec =
|
||||
new LaunchTemplateData.CapacityReservationSpecification();
|
||||
spec.setCapacityReservationPreference(
|
||||
p.getFirst(prefix + ".CapacityReservationSpecification.CapacityReservationPreference"));
|
||||
String targetPrefix = prefix + ".CapacityReservationSpecification.CapacityReservationTarget.";
|
||||
if (anyParamStartsWith(p, targetPrefix)) {
|
||||
LaunchTemplateData.CapacityReservationTarget target = new LaunchTemplateData.CapacityReservationTarget();
|
||||
target.setCapacityReservationId(p.getFirst(targetPrefix + "CapacityReservationId"));
|
||||
target.setCapacityReservationResourceGroupArn(
|
||||
p.getFirst(targetPrefix + "CapacityReservationResourceGroupArn"));
|
||||
spec.setCapacityReservationTarget(target);
|
||||
}
|
||||
data.setCapacityReservationSpecification(spec);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
private List<LaunchTemplateData.BlockDeviceMapping> parseLaunchTemplateBlockDeviceMappings(
|
||||
MultivaluedMap<String, String> p, String prefix) {
|
||||
List<LaunchTemplateData.BlockDeviceMapping> mappings = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String base = prefix + ".BlockDeviceMapping." + i;
|
||||
if (!anyParamStartsWith(p, base + ".")) {
|
||||
break;
|
||||
}
|
||||
LaunchTemplateData.BlockDeviceMapping mapping = new LaunchTemplateData.BlockDeviceMapping();
|
||||
mapping.setDeviceName(p.getFirst(base + ".DeviceName"));
|
||||
mapping.setVirtualName(p.getFirst(base + ".VirtualName"));
|
||||
mapping.setNoDevice(p.getFirst(base + ".NoDevice"));
|
||||
if (anyParamStartsWith(p, base + ".Ebs.")) {
|
||||
LaunchTemplateData.Ebs ebs = new LaunchTemplateData.Ebs();
|
||||
ebs.setEncrypted(boolParam(p, base + ".Ebs.Encrypted"));
|
||||
ebs.setDeleteOnTermination(boolParam(p, base + ".Ebs.DeleteOnTermination"));
|
||||
ebs.setIops(intParam(p, base + ".Ebs.Iops"));
|
||||
ebs.setKmsKeyId(p.getFirst(base + ".Ebs.KmsKeyId"));
|
||||
ebs.setSnapshotId(p.getFirst(base + ".Ebs.SnapshotId"));
|
||||
ebs.setVolumeSize(intParam(p, base + ".Ebs.VolumeSize"));
|
||||
ebs.setVolumeType(p.getFirst(base + ".Ebs.VolumeType"));
|
||||
ebs.setThroughput(intParam(p, base + ".Ebs.Throughput"));
|
||||
mapping.setEbs(ebs);
|
||||
}
|
||||
mappings.add(mapping);
|
||||
}
|
||||
return new ArrayList<>(groups);
|
||||
return mappings;
|
||||
}
|
||||
|
||||
private List<LaunchTemplateData.NetworkInterface> parseLaunchTemplateNetworkInterfaces(
|
||||
MultivaluedMap<String, String> p, String prefix) {
|
||||
List<LaunchTemplateData.NetworkInterface> interfaces = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String base = prefix + ".NetworkInterface." + i;
|
||||
if (!anyParamStartsWith(p, base + ".")) {
|
||||
break;
|
||||
}
|
||||
LaunchTemplateData.NetworkInterface networkInterface = new LaunchTemplateData.NetworkInterface();
|
||||
networkInterface.setAssociatePublicIpAddress(boolParam(p, base + ".AssociatePublicIpAddress"));
|
||||
networkInterface.setAssociateCarrierIpAddress(boolParam(p, base + ".AssociateCarrierIpAddress"));
|
||||
networkInterface.setDeleteOnTermination(boolParam(p, base + ".DeleteOnTermination"));
|
||||
networkInterface.setDescription(p.getFirst(base + ".Description"));
|
||||
networkInterface.setDeviceIndex(intParam(p, base + ".DeviceIndex"));
|
||||
networkInterface.setInterfaceType(p.getFirst(base + ".InterfaceType"));
|
||||
networkInterface.setIpv6AddressCount(intParam(p, base + ".Ipv6AddressCount"));
|
||||
networkInterface.setNetworkInterfaceId(p.getFirst(base + ".NetworkInterfaceId"));
|
||||
networkInterface.setPrivateIpAddress(p.getFirst(base + ".PrivateIpAddress"));
|
||||
networkInterface.setSecondaryPrivateIpAddressCount(intParam(p, base + ".SecondaryPrivateIpAddressCount"));
|
||||
networkInterface.setSubnetId(p.getFirst(base + ".SubnetId"));
|
||||
networkInterface.setNetworkCardIndex(intParam(p, base + ".NetworkCardIndex"));
|
||||
networkInterface.setGroups(getList(p, base + ".SecurityGroupId", base + ".Groups", base + ".GroupId"));
|
||||
interfaces.add(networkInterface);
|
||||
}
|
||||
return interfaces;
|
||||
}
|
||||
|
||||
private List<LaunchTemplateData.TagSpecification> parseLaunchTemplateTagSpecifications(
|
||||
MultivaluedMap<String, String> p, String prefix) {
|
||||
List<LaunchTemplateData.TagSpecification> specs = new ArrayList<>();
|
||||
for (int i = 1; ; i++) {
|
||||
String base = prefix + ".TagSpecification." + i;
|
||||
String resourceType = p.getFirst(base + ".ResourceType");
|
||||
if (resourceType == null) {
|
||||
break;
|
||||
}
|
||||
List<Tag> tagList = new ArrayList<>();
|
||||
for (int j = 1; ; j++) {
|
||||
String key = p.getFirst(base + ".Tag." + j + ".Key");
|
||||
if (key == null) {
|
||||
break;
|
||||
}
|
||||
tagList.add(new Tag(key, p.getFirst(base + ".Tag." + j + ".Value")));
|
||||
}
|
||||
specs.add(new LaunchTemplateData.TagSpecification(resourceType, tagList));
|
||||
}
|
||||
return specs;
|
||||
}
|
||||
|
||||
private boolean anyParamStartsWith(MultivaluedMap<String, String> p, String prefix) {
|
||||
for (String name : p.keySet()) {
|
||||
if (name.startsWith(prefix)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private static boolean isSet(String value) {
|
||||
return value != null && !value.isBlank();
|
||||
}
|
||||
|
||||
private Boolean boolParam(MultivaluedMap<String, String> p, String name) {
|
||||
String value = p.getFirst(name);
|
||||
return isSet(value) ? Boolean.valueOf(Boolean.parseBoolean(value)) : null;
|
||||
}
|
||||
|
||||
private Integer intParam(MultivaluedMap<String, String> p, String name) {
|
||||
String value = p.getFirst(name);
|
||||
if (!isSet(value)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return Integer.valueOf(value);
|
||||
} catch (NumberFormatException e) {
|
||||
throw new AwsException("InvalidParameterValue", name + " is not a valid integer.", 400);
|
||||
}
|
||||
}
|
||||
|
||||
private static String str(Object value) {
|
||||
return value != null ? String.valueOf(value) : null;
|
||||
}
|
||||
|
||||
private String decodeUserData(String userDataEncoded) {
|
||||
|
||||
@@ -3830,12 +3830,13 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
|
||||
// ─── Launch Templates ─────────────────────────────────────────────────────
|
||||
|
||||
public LaunchTemplate createLaunchTemplate(String region, String name, String imageId,
|
||||
String instanceType, String keyName,
|
||||
List<String> securityGroupIds, String userData,
|
||||
String encodedUserData,
|
||||
String iamInstanceProfileArn,
|
||||
List<Tag> launchTemplateTags, List<Tag> instanceTags) {
|
||||
public LaunchTemplate createLaunchTemplate(String region, String name, LaunchTemplateData data,
|
||||
List<Tag> launchTemplateTags) {
|
||||
return createLaunchTemplate(region, name, data, launchTemplateTags, null);
|
||||
}
|
||||
|
||||
public LaunchTemplate createLaunchTemplate(String region, String name, LaunchTemplateData data,
|
||||
List<Tag> launchTemplateTags, String versionDescription) {
|
||||
ensureDefaultResources(region);
|
||||
if (name == null || name.isBlank()) {
|
||||
throw new AwsException("MissingParameter", "The request must contain the parameter LaunchTemplateName", 400);
|
||||
@@ -3853,65 +3854,54 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
launchTemplate.setCreateTime(Instant.now());
|
||||
launchTemplate.setCreatedBy(AwsArnUtils.Arn.of("iam", "", accountId, "root").toString());
|
||||
launchTemplate.setRegion(region);
|
||||
launchTemplate.setImageId(imageId);
|
||||
launchTemplate.setInstanceType(instanceType);
|
||||
launchTemplate.setKeyName(keyName);
|
||||
launchTemplate.setUserData(userData);
|
||||
launchTemplate.setEncodedUserData(encodedUserData);
|
||||
launchTemplate.setIamInstanceProfileArn(iamInstanceProfileArn);
|
||||
if (securityGroupIds != null) {
|
||||
launchTemplate.setSecurityGroupIds(new ArrayList<>(securityGroupIds));
|
||||
}
|
||||
launchTemplate.setData(new LaunchTemplateData(data != null ? data : new LaunchTemplateData()));
|
||||
if (launchTemplateTags != null && !launchTemplateTags.isEmpty()) {
|
||||
launchTemplate.setTags(new ArrayList<>(launchTemplateTags));
|
||||
tags.put(launchTemplate.getLaunchTemplateId(), new ArrayList<>(launchTemplateTags));
|
||||
}
|
||||
if (instanceTags != null && !instanceTags.isEmpty()) {
|
||||
launchTemplate.setInstanceTags(new ArrayList<>(instanceTags));
|
||||
launchTemplate.getVersions().put("1", new LaunchTemplateData(launchTemplate.getData()));
|
||||
if (versionDescription != null && !versionDescription.isBlank()) {
|
||||
launchTemplate.getVersionDescriptions().put("1", versionDescription);
|
||||
launchTemplate.setVersionDescription(versionDescription);
|
||||
}
|
||||
launchTemplate.getVersions().put("1", dataFrom(launchTemplate));
|
||||
launchTemplates.put(key(region, launchTemplate.getLaunchTemplateId()), launchTemplate);
|
||||
return launchTemplate;
|
||||
}
|
||||
|
||||
public LaunchTemplate createLaunchTemplateVersion(String region, String id, String name,
|
||||
String sourceVersion,
|
||||
String imageId, String instanceType, String keyName,
|
||||
List<String> securityGroupIds, String userData,
|
||||
String encodedUserData,
|
||||
String iamInstanceProfileArn,
|
||||
List<Tag> instanceTags) {
|
||||
String sourceVersion, LaunchTemplateData data) {
|
||||
return createLaunchTemplateVersion(region, id, name, sourceVersion, data, null);
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@code SourceVersion} that is null or absent does not fall back to the latest version —
|
||||
* per the EC2 API, "no source specified" means the new version starts from an empty
|
||||
* {@link LaunchTemplateData}, populated only by whatever fields this request itself supplies.
|
||||
* Only an explicit {@code SourceVersion} (including {@code $Latest} / {@code $Default}) causes
|
||||
* inheritance.
|
||||
*/
|
||||
public LaunchTemplate createLaunchTemplateVersion(String region, String id, String name,
|
||||
String sourceVersion, LaunchTemplateData data,
|
||||
String versionDescription) {
|
||||
ensureDefaultResources(region);
|
||||
LaunchTemplate launchTemplate = findLaunchTemplate(region, id, name);
|
||||
ensureLaunchTemplateVersions(launchTemplate);
|
||||
int latestVersion = parseLaunchTemplateVersion(launchTemplate.getLatestVersionNumber()) + 1;
|
||||
LaunchTemplateData data = new LaunchTemplateData(versionData(launchTemplate,
|
||||
resolveLaunchTemplateVersion(launchTemplate, sourceVersion, launchTemplate.getLatestVersionNumber())));
|
||||
LaunchTemplateData source;
|
||||
if (sourceVersion == null || sourceVersion.isBlank()) {
|
||||
source = new LaunchTemplateData();
|
||||
} else {
|
||||
source = versionData(launchTemplate,
|
||||
resolveLaunchTemplateVersion(launchTemplate, sourceVersion, launchTemplate.getLatestVersionNumber()));
|
||||
}
|
||||
LaunchTemplateData merged = source.mergedWith(data != null ? data : new LaunchTemplateData());
|
||||
launchTemplate.setLatestVersionNumber(String.valueOf(latestVersion));
|
||||
if (imageId != null && !imageId.isBlank()) {
|
||||
data.setImageId(imageId);
|
||||
launchTemplate.getVersions().put(String.valueOf(latestVersion), merged);
|
||||
launchTemplate.setData(new LaunchTemplateData(merged));
|
||||
if (versionDescription != null && !versionDescription.isBlank()) {
|
||||
launchTemplate.getVersionDescriptions().put(String.valueOf(latestVersion), versionDescription);
|
||||
}
|
||||
if (instanceType != null && !instanceType.isBlank()) {
|
||||
data.setInstanceType(instanceType);
|
||||
}
|
||||
if (keyName != null && !keyName.isBlank()) {
|
||||
data.setKeyName(keyName);
|
||||
}
|
||||
if (userData != null && !userData.isBlank()) {
|
||||
data.setUserData(userData);
|
||||
data.setEncodedUserData(encodedUserData);
|
||||
}
|
||||
if (iamInstanceProfileArn != null && !iamInstanceProfileArn.isBlank()) {
|
||||
data.setIamInstanceProfileArn(iamInstanceProfileArn);
|
||||
}
|
||||
if (securityGroupIds != null && !securityGroupIds.isEmpty()) {
|
||||
data.setSecurityGroupIds(securityGroupIds);
|
||||
}
|
||||
if (instanceTags != null && !instanceTags.isEmpty()) {
|
||||
data.setInstanceTags(instanceTags);
|
||||
}
|
||||
launchTemplate.getVersions().put(String.valueOf(latestVersion), data);
|
||||
applyData(launchTemplate, data);
|
||||
launchTemplate.setVersionDescription(launchTemplate.getVersionDescriptions().get(String.valueOf(latestVersion)));
|
||||
launchTemplates.put(key(region, launchTemplate.getLaunchTemplateId()), launchTemplate);
|
||||
return launchTemplate;
|
||||
}
|
||||
@@ -3971,6 +3961,25 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
/**
|
||||
* The instance-profile ARN a launch from {@code data} should use. A template given only a
|
||||
* {@code Name} keeps that form as stored; the ARN is derived here, at launch time, instead of
|
||||
* being written back into the template.
|
||||
*/
|
||||
public String iamInstanceProfileArn(LaunchTemplateData data) {
|
||||
if (data == null || data.getIamInstanceProfile() == null) {
|
||||
return null;
|
||||
}
|
||||
LaunchTemplateData.IamInstanceProfile profile = data.getIamInstanceProfile();
|
||||
if (profile.getArn() != null && !profile.getArn().isBlank()) {
|
||||
return profile.getArn();
|
||||
}
|
||||
if (profile.getName() == null || profile.getName().isBlank()) {
|
||||
return null;
|
||||
}
|
||||
return AwsArnUtils.Arn.of("iam", "", accountId, "instance-profile/" + profile.getName()).toString();
|
||||
}
|
||||
|
||||
public LaunchTemplateData resolveLaunchTemplateData(String region, String id, String name, String version) {
|
||||
ensureDefaultResources(region);
|
||||
LaunchTemplate launchTemplate = findLaunchTemplate(region, id, name);
|
||||
@@ -4019,7 +4028,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
if (!launchTemplate.getVersions().isEmpty()) {
|
||||
return;
|
||||
}
|
||||
launchTemplate.getVersions().put(launchTemplate.getLatestVersionNumber(), dataFrom(launchTemplate));
|
||||
launchTemplate.getVersions().put(launchTemplate.getLatestVersionNumber(),
|
||||
new LaunchTemplateData(launchTemplate.getData()));
|
||||
launchTemplates.put(key(launchTemplate.getRegion(), launchTemplate.getLaunchTemplateId()), launchTemplate);
|
||||
}
|
||||
|
||||
@@ -4045,30 +4055,6 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
return launchTemplate.getVersions().get(version);
|
||||
}
|
||||
|
||||
private LaunchTemplateData dataFrom(LaunchTemplate launchTemplate) {
|
||||
LaunchTemplateData data = new LaunchTemplateData();
|
||||
data.setImageId(launchTemplate.getImageId());
|
||||
data.setInstanceType(launchTemplate.getInstanceType());
|
||||
data.setKeyName(launchTemplate.getKeyName());
|
||||
data.setUserData(launchTemplate.getUserData());
|
||||
data.setEncodedUserData(launchTemplate.getEncodedUserData());
|
||||
data.setIamInstanceProfileArn(launchTemplate.getIamInstanceProfileArn());
|
||||
data.setSecurityGroupIds(launchTemplate.getSecurityGroupIds());
|
||||
data.setInstanceTags(launchTemplate.getInstanceTags());
|
||||
return data;
|
||||
}
|
||||
|
||||
private void applyData(LaunchTemplate launchTemplate, LaunchTemplateData data) {
|
||||
launchTemplate.setImageId(data.getImageId());
|
||||
launchTemplate.setInstanceType(data.getInstanceType());
|
||||
launchTemplate.setKeyName(data.getKeyName());
|
||||
launchTemplate.setUserData(data.getUserData());
|
||||
launchTemplate.setEncodedUserData(data.getEncodedUserData());
|
||||
launchTemplate.setIamInstanceProfileArn(data.getIamInstanceProfileArn());
|
||||
launchTemplate.setSecurityGroupIds(new ArrayList<>(data.getSecurityGroupIds()));
|
||||
launchTemplate.setInstanceTags(data.getInstanceTags());
|
||||
}
|
||||
|
||||
private LaunchTemplate copyForVersion(LaunchTemplate source, String versionNumber) {
|
||||
LaunchTemplate copy = new LaunchTemplate();
|
||||
copy.setLaunchTemplateId(source.getLaunchTemplateId());
|
||||
@@ -4079,7 +4065,8 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
|
||||
copy.setCreatedBy(source.getCreatedBy());
|
||||
copy.setRegion(source.getRegion());
|
||||
copy.setTags(source.getTags());
|
||||
applyData(copy, versionData(source, versionNumber));
|
||||
copy.setData(new LaunchTemplateData(versionData(source, versionNumber)));
|
||||
copy.setVersionDescription(source.getVersionDescriptions().get(versionNumber));
|
||||
return copy;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package io.github.hectorvent.floci.services.ec2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonSetter;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.time.Instant;
|
||||
@@ -9,6 +10,13 @@ import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* A template persisted before this class collapsed onto a single {@link LaunchTemplateData} also
|
||||
* carried the current version's {@code iamInstanceProfileArn} and {@code instanceTags} as flat
|
||||
* fields directly on this class, alongside the equivalent per-version fields inside
|
||||
* {@link LaunchTemplateData} (see the legacy setters there for the {@code versions} map side).
|
||||
* The setters below map that top-level shape onto {@link #data} at load time.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class LaunchTemplate {
|
||||
@@ -20,16 +28,11 @@ public class LaunchTemplate {
|
||||
private Instant createTime;
|
||||
private String createdBy;
|
||||
private String region;
|
||||
private String imageId;
|
||||
private String instanceType;
|
||||
private String keyName;
|
||||
private String userData;
|
||||
private String encodedUserData;
|
||||
private String iamInstanceProfileArn;
|
||||
private List<String> securityGroupIds = new ArrayList<>();
|
||||
private List<Tag> tags = new ArrayList<>();
|
||||
private List<Tag> instanceTags = new ArrayList<>();
|
||||
private LaunchTemplateData data = new LaunchTemplateData();
|
||||
private Map<String, LaunchTemplateData> versions = new LinkedHashMap<>();
|
||||
private String versionDescription;
|
||||
private Map<String, String> versionDescriptions = new LinkedHashMap<>();
|
||||
|
||||
public LaunchTemplate() {}
|
||||
|
||||
@@ -54,37 +57,55 @@ public class LaunchTemplate {
|
||||
public String getRegion() { return region; }
|
||||
public void setRegion(String region) { this.region = region; }
|
||||
|
||||
public String getImageId() { return imageId; }
|
||||
public void setImageId(String imageId) { this.imageId = imageId; }
|
||||
|
||||
public String getInstanceType() { return instanceType; }
|
||||
public void setInstanceType(String instanceType) { this.instanceType = instanceType; }
|
||||
|
||||
public String getKeyName() { return keyName; }
|
||||
public void setKeyName(String keyName) { this.keyName = keyName; }
|
||||
|
||||
public String getUserData() { return userData; }
|
||||
public void setUserData(String userData) { this.userData = userData; }
|
||||
|
||||
public String getEncodedUserData() { return encodedUserData; }
|
||||
public void setEncodedUserData(String encodedUserData) { this.encodedUserData = encodedUserData; }
|
||||
|
||||
public String getIamInstanceProfileArn() { return iamInstanceProfileArn; }
|
||||
public void setIamInstanceProfileArn(String iamInstanceProfileArn) { this.iamInstanceProfileArn = iamInstanceProfileArn; }
|
||||
|
||||
public List<String> getSecurityGroupIds() { return securityGroupIds; }
|
||||
public void setSecurityGroupIds(List<String> securityGroupIds) { this.securityGroupIds = securityGroupIds; }
|
||||
|
||||
public List<Tag> getTags() { return tags; }
|
||||
public void setTags(List<Tag> tags) { this.tags = tags; }
|
||||
public void setTags(List<Tag> tags) {
|
||||
this.tags = tags != null ? new ArrayList<>(tags) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public List<Tag> getInstanceTags() { return instanceTags; }
|
||||
public void setInstanceTags(List<Tag> instanceTags) {
|
||||
this.instanceTags = instanceTags != null ? new ArrayList<>(instanceTags) : new ArrayList<>();
|
||||
/** The data of the version this instance represents — the latest one unless copied for another. */
|
||||
public LaunchTemplateData getData() { return data; }
|
||||
public void setData(LaunchTemplateData data) {
|
||||
this.data = data != null ? data : new LaunchTemplateData();
|
||||
}
|
||||
|
||||
public Map<String, LaunchTemplateData> getVersions() { return versions; }
|
||||
public void setVersions(Map<String, LaunchTemplateData> versions) {
|
||||
this.versions = versions != null ? new LinkedHashMap<>(versions) : new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
/** The {@code VersionDescription} of the version this instance represents — see {@link #getData()}. */
|
||||
public String getVersionDescription() { return versionDescription; }
|
||||
public void setVersionDescription(String versionDescription) { this.versionDescription = versionDescription; }
|
||||
|
||||
/**
|
||||
* {@code VersionDescription} is a version-level field on {@code LaunchTemplateVersion}, not a
|
||||
* member of {@code RequestLaunchTemplateData} / {@code ResponseLaunchTemplateData}, so it is
|
||||
* tracked in this parallel map — keyed by version number, the same way {@link #versions} is —
|
||||
* rather than inside {@link LaunchTemplateData} itself.
|
||||
*/
|
||||
public Map<String, String> getVersionDescriptions() { return versionDescriptions; }
|
||||
public void setVersionDescriptions(Map<String, String> versionDescriptions) {
|
||||
this.versionDescriptions = versionDescriptions != null ? new LinkedHashMap<>(versionDescriptions) : new LinkedHashMap<>();
|
||||
}
|
||||
|
||||
// ── Pre-unified-data schema migration ────────────────────────────────────────────────
|
||||
//
|
||||
// See the class-level note above. Deserialize-only — there is no getter for either legacy
|
||||
// key, so a file saved today never writes this shape back out. Guarded the same way as
|
||||
// LaunchTemplateData's equivalent setters: a current-schema record never carries these keys,
|
||||
// so this only ever fires for a pre-migration file, whichever order the keys load in.
|
||||
|
||||
@JsonSetter("iamInstanceProfileArn")
|
||||
public void setLegacyIamInstanceProfileArn(String arn) {
|
||||
if (arn != null && !arn.isBlank() && data.getIamInstanceProfile() == null) {
|
||||
data.setIamInstanceProfile(new LaunchTemplateData.IamInstanceProfile(arn, null));
|
||||
}
|
||||
}
|
||||
|
||||
@JsonSetter("instanceTags")
|
||||
public void setLegacyInstanceTags(List<Tag> instanceTags) {
|
||||
if (instanceTags != null && !instanceTags.isEmpty() && data.getTagSpecifications().isEmpty()) {
|
||||
data.getTagSpecifications().add(new LaunchTemplateData.TagSpecification("instance", instanceTags));
|
||||
}
|
||||
}
|
||||
}
|
||||
+635
-9
@@ -1,11 +1,24 @@
|
||||
package io.github.hectorvent.floci.services.ec2.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonSetter;
|
||||
import io.quarkus.runtime.annotations.RegisterForReflection;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The subset of EC2 {@code RequestLaunchTemplateData} / {@code ResponseLaunchTemplateData} that
|
||||
* Floci round-trips. Members the service model declares but this class omits are listed in
|
||||
* {@code docs/services/ec2.md}; they are accepted and ignored rather than rejected.
|
||||
*
|
||||
* <p>A version persisted before this class existed in its current shape stored the instance
|
||||
* profile as a bare {@code iamInstanceProfileArn} string and instance tags as a flat
|
||||
* {@code instanceTags} list, rather than the {@link IamInstanceProfile} / {@link TagSpecification}
|
||||
* shapes below. Both old keys are mapped onto the new fields at load time (see the legacy setters
|
||||
* near the bottom of this class), so ignoreUnknown never has to silently drop them.
|
||||
*/
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class LaunchTemplateData {
|
||||
@@ -15,9 +28,27 @@ public class LaunchTemplateData {
|
||||
private String keyName;
|
||||
private String userData;
|
||||
private String encodedUserData;
|
||||
private String iamInstanceProfileArn;
|
||||
private String kernelId;
|
||||
private String ramDiskId;
|
||||
private String instanceInitiatedShutdownBehavior;
|
||||
private Boolean ebsOptimized;
|
||||
private Boolean disableApiTermination;
|
||||
private Boolean disableApiStop;
|
||||
private IamInstanceProfile iamInstanceProfile;
|
||||
private MetadataOptions metadataOptions;
|
||||
private Monitoring monitoring;
|
||||
private Placement placement;
|
||||
private CpuOptions cpuOptions;
|
||||
private CreditSpecification creditSpecification;
|
||||
private EnclaveOptions enclaveOptions;
|
||||
private HibernationOptions hibernationOptions;
|
||||
private MaintenanceOptions maintenanceOptions;
|
||||
private PrivateDnsNameOptions privateDnsNameOptions;
|
||||
private CapacityReservationSpecification capacityReservationSpecification;
|
||||
private List<String> securityGroupIds = new ArrayList<>();
|
||||
private List<Tag> instanceTags = new ArrayList<>();
|
||||
private List<BlockDeviceMapping> blockDeviceMappings = new ArrayList<>();
|
||||
private List<NetworkInterface> networkInterfaces = new ArrayList<>();
|
||||
private List<TagSpecification> tagSpecifications = new ArrayList<>();
|
||||
|
||||
public LaunchTemplateData() {}
|
||||
|
||||
@@ -27,9 +58,116 @@ public class LaunchTemplateData {
|
||||
this.keyName = source.keyName;
|
||||
this.userData = source.userData;
|
||||
this.encodedUserData = source.encodedUserData;
|
||||
this.iamInstanceProfileArn = source.iamInstanceProfileArn;
|
||||
this.kernelId = source.kernelId;
|
||||
this.ramDiskId = source.ramDiskId;
|
||||
this.instanceInitiatedShutdownBehavior = source.instanceInitiatedShutdownBehavior;
|
||||
this.ebsOptimized = source.ebsOptimized;
|
||||
this.disableApiTermination = source.disableApiTermination;
|
||||
this.disableApiStop = source.disableApiStop;
|
||||
this.iamInstanceProfile = source.iamInstanceProfile;
|
||||
this.metadataOptions = source.metadataOptions;
|
||||
this.monitoring = source.monitoring;
|
||||
this.placement = source.placement;
|
||||
this.cpuOptions = source.cpuOptions;
|
||||
this.creditSpecification = source.creditSpecification;
|
||||
this.enclaveOptions = source.enclaveOptions;
|
||||
this.hibernationOptions = source.hibernationOptions;
|
||||
this.maintenanceOptions = source.maintenanceOptions;
|
||||
this.privateDnsNameOptions = source.privateDnsNameOptions;
|
||||
this.capacityReservationSpecification = source.capacityReservationSpecification;
|
||||
this.securityGroupIds = new ArrayList<>(source.securityGroupIds);
|
||||
this.instanceTags = new ArrayList<>(source.instanceTags);
|
||||
this.blockDeviceMappings = new ArrayList<>(source.blockDeviceMappings);
|
||||
this.networkInterfaces = new ArrayList<>(source.networkInterfaces);
|
||||
this.tagSpecifications = new ArrayList<>(source.tagSpecifications);
|
||||
}
|
||||
|
||||
/**
|
||||
* Members present on {@code override} replace those inherited from this instance, which is how
|
||||
* {@code CreateLaunchTemplateVersion} layers a new version onto its source version.
|
||||
*/
|
||||
public LaunchTemplateData mergedWith(LaunchTemplateData override) {
|
||||
LaunchTemplateData merged = new LaunchTemplateData(this);
|
||||
if (isPresent(override.imageId)) {
|
||||
merged.imageId = override.imageId;
|
||||
}
|
||||
if (isPresent(override.instanceType)) {
|
||||
merged.instanceType = override.instanceType;
|
||||
}
|
||||
if (isPresent(override.keyName)) {
|
||||
merged.keyName = override.keyName;
|
||||
}
|
||||
if (isPresent(override.userData) || isPresent(override.encodedUserData)) {
|
||||
merged.userData = override.userData;
|
||||
merged.encodedUserData = override.encodedUserData;
|
||||
}
|
||||
if (isPresent(override.kernelId)) {
|
||||
merged.kernelId = override.kernelId;
|
||||
}
|
||||
if (isPresent(override.ramDiskId)) {
|
||||
merged.ramDiskId = override.ramDiskId;
|
||||
}
|
||||
if (isPresent(override.instanceInitiatedShutdownBehavior)) {
|
||||
merged.instanceInitiatedShutdownBehavior = override.instanceInitiatedShutdownBehavior;
|
||||
}
|
||||
if (override.ebsOptimized != null) {
|
||||
merged.ebsOptimized = override.ebsOptimized;
|
||||
}
|
||||
if (override.disableApiTermination != null) {
|
||||
merged.disableApiTermination = override.disableApiTermination;
|
||||
}
|
||||
if (override.disableApiStop != null) {
|
||||
merged.disableApiStop = override.disableApiStop;
|
||||
}
|
||||
if (override.iamInstanceProfile != null) {
|
||||
merged.iamInstanceProfile = override.iamInstanceProfile;
|
||||
}
|
||||
if (override.metadataOptions != null) {
|
||||
merged.metadataOptions = override.metadataOptions;
|
||||
}
|
||||
if (override.monitoring != null) {
|
||||
merged.monitoring = override.monitoring;
|
||||
}
|
||||
if (override.placement != null) {
|
||||
merged.placement = override.placement;
|
||||
}
|
||||
if (override.cpuOptions != null) {
|
||||
merged.cpuOptions = override.cpuOptions;
|
||||
}
|
||||
if (override.creditSpecification != null) {
|
||||
merged.creditSpecification = override.creditSpecification;
|
||||
}
|
||||
if (override.enclaveOptions != null) {
|
||||
merged.enclaveOptions = override.enclaveOptions;
|
||||
}
|
||||
if (override.hibernationOptions != null) {
|
||||
merged.hibernationOptions = override.hibernationOptions;
|
||||
}
|
||||
if (override.maintenanceOptions != null) {
|
||||
merged.maintenanceOptions = override.maintenanceOptions;
|
||||
}
|
||||
if (override.privateDnsNameOptions != null) {
|
||||
merged.privateDnsNameOptions = override.privateDnsNameOptions;
|
||||
}
|
||||
if (override.capacityReservationSpecification != null) {
|
||||
merged.capacityReservationSpecification = override.capacityReservationSpecification;
|
||||
}
|
||||
if (!override.securityGroupIds.isEmpty()) {
|
||||
merged.securityGroupIds = new ArrayList<>(override.securityGroupIds);
|
||||
}
|
||||
if (!override.blockDeviceMappings.isEmpty()) {
|
||||
merged.blockDeviceMappings = new ArrayList<>(override.blockDeviceMappings);
|
||||
}
|
||||
if (!override.networkInterfaces.isEmpty()) {
|
||||
merged.networkInterfaces = new ArrayList<>(override.networkInterfaces);
|
||||
}
|
||||
if (!override.tagSpecifications.isEmpty()) {
|
||||
merged.tagSpecifications = new ArrayList<>(override.tagSpecifications);
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
private static boolean isPresent(String value) {
|
||||
return value != null && !value.isBlank();
|
||||
}
|
||||
|
||||
public String getImageId() { return imageId; }
|
||||
@@ -47,16 +185,504 @@ public class LaunchTemplateData {
|
||||
public String getEncodedUserData() { return encodedUserData; }
|
||||
public void setEncodedUserData(String encodedUserData) { this.encodedUserData = encodedUserData; }
|
||||
|
||||
public String getIamInstanceProfileArn() { return iamInstanceProfileArn; }
|
||||
public void setIamInstanceProfileArn(String iamInstanceProfileArn) { this.iamInstanceProfileArn = iamInstanceProfileArn; }
|
||||
public String getKernelId() { return kernelId; }
|
||||
public void setKernelId(String kernelId) { this.kernelId = kernelId; }
|
||||
|
||||
public String getRamDiskId() { return ramDiskId; }
|
||||
public void setRamDiskId(String ramDiskId) { this.ramDiskId = ramDiskId; }
|
||||
|
||||
public String getInstanceInitiatedShutdownBehavior() { return instanceInitiatedShutdownBehavior; }
|
||||
public void setInstanceInitiatedShutdownBehavior(String instanceInitiatedShutdownBehavior) {
|
||||
this.instanceInitiatedShutdownBehavior = instanceInitiatedShutdownBehavior;
|
||||
}
|
||||
|
||||
public Boolean getEbsOptimized() { return ebsOptimized; }
|
||||
public void setEbsOptimized(Boolean ebsOptimized) { this.ebsOptimized = ebsOptimized; }
|
||||
|
||||
public Boolean getDisableApiTermination() { return disableApiTermination; }
|
||||
public void setDisableApiTermination(Boolean disableApiTermination) { this.disableApiTermination = disableApiTermination; }
|
||||
|
||||
public Boolean getDisableApiStop() { return disableApiStop; }
|
||||
public void setDisableApiStop(Boolean disableApiStop) { this.disableApiStop = disableApiStop; }
|
||||
|
||||
public IamInstanceProfile getIamInstanceProfile() { return iamInstanceProfile; }
|
||||
public void setIamInstanceProfile(IamInstanceProfile iamInstanceProfile) { this.iamInstanceProfile = iamInstanceProfile; }
|
||||
|
||||
public MetadataOptions getMetadataOptions() { return metadataOptions; }
|
||||
public void setMetadataOptions(MetadataOptions metadataOptions) { this.metadataOptions = metadataOptions; }
|
||||
|
||||
public Monitoring getMonitoring() { return monitoring; }
|
||||
public void setMonitoring(Monitoring monitoring) { this.monitoring = monitoring; }
|
||||
|
||||
public Placement getPlacement() { return placement; }
|
||||
public void setPlacement(Placement placement) { this.placement = placement; }
|
||||
|
||||
public CpuOptions getCpuOptions() { return cpuOptions; }
|
||||
public void setCpuOptions(CpuOptions cpuOptions) { this.cpuOptions = cpuOptions; }
|
||||
|
||||
public CreditSpecification getCreditSpecification() { return creditSpecification; }
|
||||
public void setCreditSpecification(CreditSpecification creditSpecification) { this.creditSpecification = creditSpecification; }
|
||||
|
||||
public EnclaveOptions getEnclaveOptions() { return enclaveOptions; }
|
||||
public void setEnclaveOptions(EnclaveOptions enclaveOptions) { this.enclaveOptions = enclaveOptions; }
|
||||
|
||||
public HibernationOptions getHibernationOptions() { return hibernationOptions; }
|
||||
public void setHibernationOptions(HibernationOptions hibernationOptions) { this.hibernationOptions = hibernationOptions; }
|
||||
|
||||
public MaintenanceOptions getMaintenanceOptions() { return maintenanceOptions; }
|
||||
public void setMaintenanceOptions(MaintenanceOptions maintenanceOptions) { this.maintenanceOptions = maintenanceOptions; }
|
||||
|
||||
public PrivateDnsNameOptions getPrivateDnsNameOptions() { return privateDnsNameOptions; }
|
||||
public void setPrivateDnsNameOptions(PrivateDnsNameOptions privateDnsNameOptions) {
|
||||
this.privateDnsNameOptions = privateDnsNameOptions;
|
||||
}
|
||||
|
||||
public CapacityReservationSpecification getCapacityReservationSpecification() {
|
||||
return capacityReservationSpecification;
|
||||
}
|
||||
public void setCapacityReservationSpecification(CapacityReservationSpecification capacityReservationSpecification) {
|
||||
this.capacityReservationSpecification = capacityReservationSpecification;
|
||||
}
|
||||
|
||||
public List<String> getSecurityGroupIds() { return securityGroupIds; }
|
||||
public void setSecurityGroupIds(List<String> securityGroupIds) {
|
||||
this.securityGroupIds = securityGroupIds != null ? new ArrayList<>(securityGroupIds) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public List<Tag> getInstanceTags() { return instanceTags; }
|
||||
public void setInstanceTags(List<Tag> instanceTags) {
|
||||
this.instanceTags = instanceTags != null ? new ArrayList<>(instanceTags) : new ArrayList<>();
|
||||
public List<BlockDeviceMapping> getBlockDeviceMappings() { return blockDeviceMappings; }
|
||||
public void setBlockDeviceMappings(List<BlockDeviceMapping> blockDeviceMappings) {
|
||||
this.blockDeviceMappings = blockDeviceMappings != null ? new ArrayList<>(blockDeviceMappings) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public List<NetworkInterface> getNetworkInterfaces() { return networkInterfaces; }
|
||||
public void setNetworkInterfaces(List<NetworkInterface> networkInterfaces) {
|
||||
this.networkInterfaces = networkInterfaces != null ? new ArrayList<>(networkInterfaces) : new ArrayList<>();
|
||||
}
|
||||
|
||||
public List<TagSpecification> getTagSpecifications() { return tagSpecifications; }
|
||||
public void setTagSpecifications(List<TagSpecification> tagSpecifications) {
|
||||
this.tagSpecifications = tagSpecifications != null ? new ArrayList<>(tagSpecifications) : new ArrayList<>();
|
||||
}
|
||||
|
||||
/** The tags a launch from this template applies to the instance it creates. */
|
||||
@JsonIgnore
|
||||
public List<Tag> getInstanceTags() {
|
||||
return tagsForResource("instance");
|
||||
}
|
||||
|
||||
// ── Pre-unified-data schema migration ────────────────────────────────────────────────
|
||||
//
|
||||
// A version persisted before this PR stored the instance profile and instance tags under
|
||||
// these two keys directly on this class, rather than nested inside iamInstanceProfile /
|
||||
// tagSpecifications. Without the setters below, ignoreUnknown silently drops both keys and
|
||||
// an upgraded Floci launches from that version with no IAM profile and no instance tags.
|
||||
// Deserialize-only: there is no getter for either key, so a file saved today never writes
|
||||
// this shape back out. Guarded so a current-schema record — which never carries these keys —
|
||||
// can't have a stray legacy key fight the real field, whichever order they load in.
|
||||
|
||||
@JsonSetter("iamInstanceProfileArn")
|
||||
public void setLegacyIamInstanceProfileArn(String arn) {
|
||||
if (arn != null && !arn.isBlank() && iamInstanceProfile == null) {
|
||||
iamInstanceProfile = new IamInstanceProfile(arn, null);
|
||||
}
|
||||
}
|
||||
|
||||
@JsonSetter("instanceTags")
|
||||
public void setLegacyInstanceTags(List<Tag> tags) {
|
||||
if (tags != null && !tags.isEmpty() && tagSpecifications.isEmpty()) {
|
||||
tagSpecifications.add(new TagSpecification("instance", tags));
|
||||
}
|
||||
}
|
||||
|
||||
@JsonIgnore
|
||||
public List<Tag> tagsForResource(String resourceType) {
|
||||
List<Tag> result = new ArrayList<>();
|
||||
for (TagSpecification spec : tagSpecifications) {
|
||||
if (resourceType.equals(spec.getResourceType())) {
|
||||
result.addAll(spec.getTags());
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* The security groups a launch from this template applies. On AWS, top-level
|
||||
* {@code SecurityGroupIds} and {@code NetworkInterfaces[].Groups} are mutually exclusive, so at
|
||||
* most one of the two is populated. Resolving them here — rather than folding the interface
|
||||
* groups into the stored top-level list — is what keeps a NetworkInterfaces block readable back
|
||||
* as a NetworkInterfaces block.
|
||||
*/
|
||||
@JsonIgnore
|
||||
public List<String> effectiveSecurityGroupIds() {
|
||||
if (!securityGroupIds.isEmpty()) {
|
||||
return List.copyOf(securityGroupIds);
|
||||
}
|
||||
List<String> fromInterfaces = new ArrayList<>();
|
||||
for (NetworkInterface networkInterface : networkInterfaces) {
|
||||
for (String group : networkInterface.getGroups()) {
|
||||
if (!fromInterfaces.contains(group)) {
|
||||
fromInterfaces.add(group);
|
||||
}
|
||||
}
|
||||
}
|
||||
return fromInterfaces;
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class IamInstanceProfile {
|
||||
private String arn;
|
||||
private String name;
|
||||
|
||||
public IamInstanceProfile() {}
|
||||
|
||||
public IamInstanceProfile(String arn, String name) {
|
||||
this.arn = arn;
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getArn() { return arn; }
|
||||
public void setArn(String arn) { this.arn = arn; }
|
||||
|
||||
public String getName() { return name; }
|
||||
public void setName(String name) { this.name = name; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class BlockDeviceMapping {
|
||||
private String deviceName;
|
||||
private String virtualName;
|
||||
private String noDevice;
|
||||
private Ebs ebs;
|
||||
|
||||
public String getDeviceName() { return deviceName; }
|
||||
public void setDeviceName(String deviceName) { this.deviceName = deviceName; }
|
||||
|
||||
public String getVirtualName() { return virtualName; }
|
||||
public void setVirtualName(String virtualName) { this.virtualName = virtualName; }
|
||||
|
||||
public String getNoDevice() { return noDevice; }
|
||||
public void setNoDevice(String noDevice) { this.noDevice = noDevice; }
|
||||
|
||||
public Ebs getEbs() { return ebs; }
|
||||
public void setEbs(Ebs ebs) { this.ebs = ebs; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Ebs {
|
||||
private Boolean encrypted;
|
||||
private Boolean deleteOnTermination;
|
||||
private Integer iops;
|
||||
private String kmsKeyId;
|
||||
private String snapshotId;
|
||||
private Integer volumeSize;
|
||||
private String volumeType;
|
||||
private Integer throughput;
|
||||
|
||||
public Boolean getEncrypted() { return encrypted; }
|
||||
public void setEncrypted(Boolean encrypted) { this.encrypted = encrypted; }
|
||||
|
||||
public Boolean getDeleteOnTermination() { return deleteOnTermination; }
|
||||
public void setDeleteOnTermination(Boolean deleteOnTermination) { this.deleteOnTermination = deleteOnTermination; }
|
||||
|
||||
public Integer getIops() { return iops; }
|
||||
public void setIops(Integer iops) { this.iops = iops; }
|
||||
|
||||
public String getKmsKeyId() { return kmsKeyId; }
|
||||
public void setKmsKeyId(String kmsKeyId) { this.kmsKeyId = kmsKeyId; }
|
||||
|
||||
public String getSnapshotId() { return snapshotId; }
|
||||
public void setSnapshotId(String snapshotId) { this.snapshotId = snapshotId; }
|
||||
|
||||
public Integer getVolumeSize() { return volumeSize; }
|
||||
public void setVolumeSize(Integer volumeSize) { this.volumeSize = volumeSize; }
|
||||
|
||||
public String getVolumeType() { return volumeType; }
|
||||
public void setVolumeType(String volumeType) { this.volumeType = volumeType; }
|
||||
|
||||
public Integer getThroughput() { return throughput; }
|
||||
public void setThroughput(Integer throughput) { this.throughput = throughput; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class MetadataOptions {
|
||||
private String state;
|
||||
private String httpTokens;
|
||||
private Integer httpPutResponseHopLimit;
|
||||
private String httpEndpoint;
|
||||
private String httpProtocolIpv6;
|
||||
private String instanceMetadataTags;
|
||||
|
||||
public String getState() { return state; }
|
||||
public void setState(String state) { this.state = state; }
|
||||
|
||||
public String getHttpTokens() { return httpTokens; }
|
||||
public void setHttpTokens(String httpTokens) { this.httpTokens = httpTokens; }
|
||||
|
||||
public Integer getHttpPutResponseHopLimit() { return httpPutResponseHopLimit; }
|
||||
public void setHttpPutResponseHopLimit(Integer httpPutResponseHopLimit) {
|
||||
this.httpPutResponseHopLimit = httpPutResponseHopLimit;
|
||||
}
|
||||
|
||||
public String getHttpEndpoint() { return httpEndpoint; }
|
||||
public void setHttpEndpoint(String httpEndpoint) { this.httpEndpoint = httpEndpoint; }
|
||||
|
||||
public String getHttpProtocolIpv6() { return httpProtocolIpv6; }
|
||||
public void setHttpProtocolIpv6(String httpProtocolIpv6) { this.httpProtocolIpv6 = httpProtocolIpv6; }
|
||||
|
||||
public String getInstanceMetadataTags() { return instanceMetadataTags; }
|
||||
public void setInstanceMetadataTags(String instanceMetadataTags) { this.instanceMetadataTags = instanceMetadataTags; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class NetworkInterface {
|
||||
private Boolean associatePublicIpAddress;
|
||||
private Boolean associateCarrierIpAddress;
|
||||
private Boolean deleteOnTermination;
|
||||
private String description;
|
||||
private Integer deviceIndex;
|
||||
private String interfaceType;
|
||||
private Integer ipv6AddressCount;
|
||||
private String networkInterfaceId;
|
||||
private String privateIpAddress;
|
||||
private Integer secondaryPrivateIpAddressCount;
|
||||
private String subnetId;
|
||||
private Integer networkCardIndex;
|
||||
private List<String> groups = new ArrayList<>();
|
||||
|
||||
public Boolean getAssociatePublicIpAddress() { return associatePublicIpAddress; }
|
||||
public void setAssociatePublicIpAddress(Boolean associatePublicIpAddress) {
|
||||
this.associatePublicIpAddress = associatePublicIpAddress;
|
||||
}
|
||||
|
||||
public Boolean getAssociateCarrierIpAddress() { return associateCarrierIpAddress; }
|
||||
public void setAssociateCarrierIpAddress(Boolean associateCarrierIpAddress) {
|
||||
this.associateCarrierIpAddress = associateCarrierIpAddress;
|
||||
}
|
||||
|
||||
public Boolean getDeleteOnTermination() { return deleteOnTermination; }
|
||||
public void setDeleteOnTermination(Boolean deleteOnTermination) { this.deleteOnTermination = deleteOnTermination; }
|
||||
|
||||
public String getDescription() { return description; }
|
||||
public void setDescription(String description) { this.description = description; }
|
||||
|
||||
public Integer getDeviceIndex() { return deviceIndex; }
|
||||
public void setDeviceIndex(Integer deviceIndex) { this.deviceIndex = deviceIndex; }
|
||||
|
||||
public String getInterfaceType() { return interfaceType; }
|
||||
public void setInterfaceType(String interfaceType) { this.interfaceType = interfaceType; }
|
||||
|
||||
public Integer getIpv6AddressCount() { return ipv6AddressCount; }
|
||||
public void setIpv6AddressCount(Integer ipv6AddressCount) { this.ipv6AddressCount = ipv6AddressCount; }
|
||||
|
||||
public String getNetworkInterfaceId() { return networkInterfaceId; }
|
||||
public void setNetworkInterfaceId(String networkInterfaceId) { this.networkInterfaceId = networkInterfaceId; }
|
||||
|
||||
public String getPrivateIpAddress() { return privateIpAddress; }
|
||||
public void setPrivateIpAddress(String privateIpAddress) { this.privateIpAddress = privateIpAddress; }
|
||||
|
||||
public Integer getSecondaryPrivateIpAddressCount() { return secondaryPrivateIpAddressCount; }
|
||||
public void setSecondaryPrivateIpAddressCount(Integer secondaryPrivateIpAddressCount) {
|
||||
this.secondaryPrivateIpAddressCount = secondaryPrivateIpAddressCount;
|
||||
}
|
||||
|
||||
public String getSubnetId() { return subnetId; }
|
||||
public void setSubnetId(String subnetId) { this.subnetId = subnetId; }
|
||||
|
||||
public Integer getNetworkCardIndex() { return networkCardIndex; }
|
||||
public void setNetworkCardIndex(Integer networkCardIndex) { this.networkCardIndex = networkCardIndex; }
|
||||
|
||||
public List<String> getGroups() { return groups; }
|
||||
public void setGroups(List<String> groups) {
|
||||
this.groups = groups != null ? new ArrayList<>(groups) : new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class TagSpecification {
|
||||
private String resourceType;
|
||||
private List<Tag> tags = new ArrayList<>();
|
||||
|
||||
public TagSpecification() {}
|
||||
|
||||
public TagSpecification(String resourceType, List<Tag> tags) {
|
||||
this.resourceType = resourceType;
|
||||
setTags(tags);
|
||||
}
|
||||
|
||||
public String getResourceType() { return resourceType; }
|
||||
public void setResourceType(String resourceType) { this.resourceType = resourceType; }
|
||||
|
||||
public List<Tag> getTags() { return tags; }
|
||||
public void setTags(List<Tag> tags) {
|
||||
this.tags = tags != null ? new ArrayList<>(tags) : new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Monitoring {
|
||||
private Boolean enabled;
|
||||
|
||||
public Boolean getEnabled() { return enabled; }
|
||||
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class EnclaveOptions {
|
||||
private Boolean enabled;
|
||||
|
||||
public Boolean getEnabled() { return enabled; }
|
||||
public void setEnabled(Boolean enabled) { this.enabled = enabled; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class HibernationOptions {
|
||||
private Boolean configured;
|
||||
|
||||
public Boolean getConfigured() { return configured; }
|
||||
public void setConfigured(Boolean configured) { this.configured = configured; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class MaintenanceOptions {
|
||||
private String autoRecovery;
|
||||
|
||||
public String getAutoRecovery() { return autoRecovery; }
|
||||
public void setAutoRecovery(String autoRecovery) { this.autoRecovery = autoRecovery; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CreditSpecification {
|
||||
private String cpuCredits;
|
||||
|
||||
public String getCpuCredits() { return cpuCredits; }
|
||||
public void setCpuCredits(String cpuCredits) { this.cpuCredits = cpuCredits; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CpuOptions {
|
||||
private Integer coreCount;
|
||||
private Integer threadsPerCore;
|
||||
private String amdSevSnp;
|
||||
|
||||
public Integer getCoreCount() { return coreCount; }
|
||||
public void setCoreCount(Integer coreCount) { this.coreCount = coreCount; }
|
||||
|
||||
public Integer getThreadsPerCore() { return threadsPerCore; }
|
||||
public void setThreadsPerCore(Integer threadsPerCore) { this.threadsPerCore = threadsPerCore; }
|
||||
|
||||
public String getAmdSevSnp() { return amdSevSnp; }
|
||||
public void setAmdSevSnp(String amdSevSnp) { this.amdSevSnp = amdSevSnp; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class Placement {
|
||||
private String availabilityZone;
|
||||
private String availabilityZoneId;
|
||||
private String affinity;
|
||||
private String groupName;
|
||||
private String groupId;
|
||||
private String hostId;
|
||||
private String tenancy;
|
||||
private String spreadDomain;
|
||||
private String hostResourceGroupArn;
|
||||
private Integer partitionNumber;
|
||||
|
||||
public String getAvailabilityZone() { return availabilityZone; }
|
||||
public void setAvailabilityZone(String availabilityZone) { this.availabilityZone = availabilityZone; }
|
||||
|
||||
public String getAvailabilityZoneId() { return availabilityZoneId; }
|
||||
public void setAvailabilityZoneId(String availabilityZoneId) { this.availabilityZoneId = availabilityZoneId; }
|
||||
|
||||
public String getAffinity() { return affinity; }
|
||||
public void setAffinity(String affinity) { this.affinity = affinity; }
|
||||
|
||||
public String getGroupName() { return groupName; }
|
||||
public void setGroupName(String groupName) { this.groupName = groupName; }
|
||||
|
||||
public String getGroupId() { return groupId; }
|
||||
public void setGroupId(String groupId) { this.groupId = groupId; }
|
||||
|
||||
public String getHostId() { return hostId; }
|
||||
public void setHostId(String hostId) { this.hostId = hostId; }
|
||||
|
||||
public String getTenancy() { return tenancy; }
|
||||
public void setTenancy(String tenancy) { this.tenancy = tenancy; }
|
||||
|
||||
public String getSpreadDomain() { return spreadDomain; }
|
||||
public void setSpreadDomain(String spreadDomain) { this.spreadDomain = spreadDomain; }
|
||||
|
||||
public String getHostResourceGroupArn() { return hostResourceGroupArn; }
|
||||
public void setHostResourceGroupArn(String hostResourceGroupArn) { this.hostResourceGroupArn = hostResourceGroupArn; }
|
||||
|
||||
public Integer getPartitionNumber() { return partitionNumber; }
|
||||
public void setPartitionNumber(Integer partitionNumber) { this.partitionNumber = partitionNumber; }
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class PrivateDnsNameOptions {
|
||||
private String hostnameType;
|
||||
private Boolean enableResourceNameDnsARecord;
|
||||
private Boolean enableResourceNameDnsAAAARecord;
|
||||
|
||||
public String getHostnameType() { return hostnameType; }
|
||||
public void setHostnameType(String hostnameType) { this.hostnameType = hostnameType; }
|
||||
|
||||
public Boolean getEnableResourceNameDnsARecord() { return enableResourceNameDnsARecord; }
|
||||
public void setEnableResourceNameDnsARecord(Boolean enableResourceNameDnsARecord) {
|
||||
this.enableResourceNameDnsARecord = enableResourceNameDnsARecord;
|
||||
}
|
||||
|
||||
public Boolean getEnableResourceNameDnsAAAARecord() { return enableResourceNameDnsAAAARecord; }
|
||||
public void setEnableResourceNameDnsAAAARecord(Boolean enableResourceNameDnsAAAARecord) {
|
||||
this.enableResourceNameDnsAAAARecord = enableResourceNameDnsAAAARecord;
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CapacityReservationSpecification {
|
||||
private String capacityReservationPreference;
|
||||
private CapacityReservationTarget capacityReservationTarget;
|
||||
|
||||
public String getCapacityReservationPreference() { return capacityReservationPreference; }
|
||||
public void setCapacityReservationPreference(String capacityReservationPreference) {
|
||||
this.capacityReservationPreference = capacityReservationPreference;
|
||||
}
|
||||
|
||||
public CapacityReservationTarget getCapacityReservationTarget() { return capacityReservationTarget; }
|
||||
public void setCapacityReservationTarget(CapacityReservationTarget capacityReservationTarget) {
|
||||
this.capacityReservationTarget = capacityReservationTarget;
|
||||
}
|
||||
}
|
||||
|
||||
@RegisterForReflection
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CapacityReservationTarget {
|
||||
private String capacityReservationId;
|
||||
private String capacityReservationResourceGroupArn;
|
||||
|
||||
public String getCapacityReservationId() { return capacityReservationId; }
|
||||
public void setCapacityReservationId(String capacityReservationId) {
|
||||
this.capacityReservationId = capacityReservationId;
|
||||
}
|
||||
|
||||
public String getCapacityReservationResourceGroupArn() { return capacityReservationResourceGroupArn; }
|
||||
public void setCapacityReservationResourceGroupArn(String capacityReservationResourceGroupArn) {
|
||||
this.capacityReservationResourceGroupArn = capacityReservationResourceGroupArn;
|
||||
}
|
||||
}
|
||||
}
|
||||
+13
-8
@@ -8,6 +8,7 @@ import io.github.hectorvent.floci.services.ec2.Ec2Service;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Instance;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Reservation;
|
||||
import io.github.hectorvent.floci.services.ec2.model.Tag;
|
||||
import io.github.hectorvent.floci.services.elbv2.ElbV2Service;
|
||||
@@ -101,12 +102,16 @@ class AutoScalingReconcilerTest {
|
||||
launchTemplate.setLaunchTemplateId("lt-123");
|
||||
LaunchTemplate version = new LaunchTemplate();
|
||||
version.setLatestVersionNumber("1");
|
||||
version.setImageId("ami-version-1");
|
||||
version.setInstanceType("t3.micro");
|
||||
version.setIamInstanceProfileArn("arn:aws:iam::000000000000:instance-profile/app-profile");
|
||||
version.getData().setImageId("ami-version-1");
|
||||
version.getData().setInstanceType("t3.micro");
|
||||
version.getData().setIamInstanceProfile(new LaunchTemplateData.IamInstanceProfile(
|
||||
"arn:aws:iam::000000000000:instance-profile/app-profile", null));
|
||||
when(ec2Service.iamInstanceProfileArn(version.getData()))
|
||||
.thenReturn("arn:aws:iam::000000000000:instance-profile/app-profile");
|
||||
List<Tag> instanceTags = List.of(new Tag("app.ClusterId", "development"));
|
||||
List<Tag> propagatedTags = List.of(new Tag("app.ClusterId", "development"), new Tag("job-id", "2001"));
|
||||
version.setInstanceTags(instanceTags);
|
||||
version.getData().setTagSpecifications(List.of(
|
||||
new LaunchTemplateData.TagSpecification("instance", instanceTags)));
|
||||
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
|
||||
.thenReturn(List.of(launchTemplate));
|
||||
when(ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("1")))
|
||||
@@ -198,8 +203,8 @@ class AutoScalingReconcilerTest {
|
||||
launchTemplate.setLaunchTemplateId("lt-123");
|
||||
LaunchTemplate version = new LaunchTemplate();
|
||||
version.setLatestVersionNumber("7");
|
||||
version.setImageId("ami-version-7");
|
||||
version.setInstanceType("t3.micro");
|
||||
version.getData().setImageId("ami-version-7");
|
||||
version.getData().setInstanceType("t3.micro");
|
||||
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
|
||||
.thenReturn(List.of(launchTemplate));
|
||||
when(ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("$Latest")))
|
||||
@@ -247,8 +252,8 @@ class AutoScalingReconcilerTest {
|
||||
launchTemplate.setLaunchTemplateId("lt-123");
|
||||
LaunchTemplate version = new LaunchTemplate();
|
||||
version.setLatestVersionNumber("3");
|
||||
version.setImageId("ami-version-3");
|
||||
version.setInstanceType("t3.micro");
|
||||
version.getData().setImageId("ami-version-3");
|
||||
version.getData().setInstanceType("t3.micro");
|
||||
when(ec2Service.describeLaunchTemplates("us-east-1", List.of("lt-123"), List.of(), Map.of()))
|
||||
.thenReturn(List.of(launchTemplate));
|
||||
when(ec2Service.describeLaunchTemplateVersions("us-east-1", "lt-123", null, List.of("3")))
|
||||
|
||||
+2
-2
@@ -98,7 +98,7 @@ class AutoScalingServiceTest {
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
service.ec2Service = ec2Service;
|
||||
LaunchTemplate version = new LaunchTemplate();
|
||||
version.setImageId(null);
|
||||
version.getData().setImageId(null);
|
||||
when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-no-image", null, List.of("1")))
|
||||
.thenReturn(List.of(version));
|
||||
|
||||
@@ -242,7 +242,7 @@ class AutoScalingServiceTest {
|
||||
Ec2Service ec2Service = mock(Ec2Service.class);
|
||||
service.ec2Service = ec2Service;
|
||||
LaunchTemplate version = new LaunchTemplate();
|
||||
version.setImageId("");
|
||||
version.getData().setImageId("");
|
||||
when(ec2Service.describeLaunchTemplateVersions(REGION, "lt-no-image", null, List.of("2")))
|
||||
.thenReturn(List.of(version));
|
||||
|
||||
|
||||
+29
-41
@@ -7,6 +7,8 @@ import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplate
|
||||
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 io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
@@ -15,7 +17,9 @@ import java.util.List;
|
||||
import java.util.Set;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.anyString;
|
||||
@@ -61,8 +65,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
|
||||
@Test
|
||||
void setsPhysicalIdAndGetAttAttributes() {
|
||||
when(ec2.createLaunchTemplate(eq("us-east-1"), eq("my-lt"), eq("ami-12345678"),
|
||||
eq("t3.small"), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull()))
|
||||
when(ec2.createLaunchTemplate(eq("us-east-1"), eq("my-lt"), any(), any()))
|
||||
.thenReturn(template("lt-abc123"));
|
||||
ObjectNode data = mapper.createObjectNode()
|
||||
.put("ImageId", "ami-12345678")
|
||||
@@ -81,16 +84,14 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
|
||||
@Test
|
||||
void withoutNameGeneratesPhysicalName() {
|
||||
when(ec2.createLaunchTemplate(eq("us-east-1"), anyString(), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), any()))
|
||||
when(ec2.createLaunchTemplate(eq("us-east-1"), anyString(), any(), any()))
|
||||
.thenReturn(template("lt-gen"));
|
||||
StackResource r = resource("Lt");
|
||||
|
||||
provisioner.provision(r, mapper.createObjectNode(), ctx());
|
||||
|
||||
verify(ec2).createLaunchTemplate(eq("us-east-1"),
|
||||
org.mockito.ArgumentMatchers.matches("my-stack-Lt-[0-9a-f]{12}"),
|
||||
isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull(), isNull());
|
||||
org.mockito.ArgumentMatchers.matches("my-stack-Lt-[0-9a-f]{12}"), any(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -102,7 +103,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
when(ec2.describeLaunchTemplates(eq("us-east-1"), eq(List.of("lt-abc123")), eq(List.of()), any()))
|
||||
.thenReturn(List.of(existing));
|
||||
when(ec2.createLaunchTemplateVersion(eq("us-east-1"), eq("lt-abc123"), isNull(), isNull(),
|
||||
eq("ami-updated"), any(), any(), any(), any(), any(), any(), any()))
|
||||
argThat(d -> d != null && "ami-updated".equals(d.getImageId()))))
|
||||
.thenReturn(template("lt-abc123"));
|
||||
|
||||
ObjectNode props = mapper.createObjectNode().put("LaunchTemplateName", "my-lt");
|
||||
@@ -113,8 +114,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
provisioner.provision(r, props, ctx());
|
||||
|
||||
assertEquals("lt-abc123", r.getPhysicalId());
|
||||
verify(ec2, never()).createLaunchTemplate(any(), any(), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), any());
|
||||
verify(ec2, never()).createLaunchTemplate(any(), any(), any(), any());
|
||||
verify(ec2, never()).deleteLaunchTemplate(any(), any(), any());
|
||||
}
|
||||
|
||||
@@ -125,8 +125,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
existing.setLaunchTemplateName("my-stack-Lt-0123456789ab");
|
||||
when(ec2.describeLaunchTemplates(eq("us-east-1"), eq(List.of("lt-gen")), eq(List.of()), any()))
|
||||
.thenReturn(List.of(existing));
|
||||
when(ec2.createLaunchTemplateVersion(eq("us-east-1"), eq("lt-gen"), isNull(), isNull(),
|
||||
any(), any(), any(), any(), any(), any(), any(), any()))
|
||||
when(ec2.createLaunchTemplateVersion(eq("us-east-1"), eq("lt-gen"), isNull(), isNull(), any()))
|
||||
.thenReturn(template("lt-gen"));
|
||||
|
||||
StackResource r = resource("Lt");
|
||||
@@ -135,8 +134,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
provisioner.provision(r, mapper.createObjectNode(), ctx());
|
||||
|
||||
assertEquals("lt-gen", r.getPhysicalId());
|
||||
verify(ec2, never()).createLaunchTemplate(any(), any(), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), any());
|
||||
verify(ec2, never()).createLaunchTemplate(any(), any(), any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
@@ -145,8 +143,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
existing.setLaunchTemplateName("old-name");
|
||||
when(ec2.describeLaunchTemplates(eq("us-east-1"), eq(List.of("lt-old")), eq(List.of()), any()))
|
||||
.thenReturn(List.of(existing));
|
||||
when(ec2.createLaunchTemplate(eq("us-east-1"), eq("new-name"), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), any()))
|
||||
when(ec2.createLaunchTemplate(eq("us-east-1"), eq("new-name"), any(), any()))
|
||||
.thenReturn(template("lt-new"));
|
||||
|
||||
StackResource r = resource("Lt");
|
||||
@@ -157,16 +154,16 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
assertEquals("lt-new", r.getPhysicalId());
|
||||
// Created before the old one is dropped, so a failed create leaves the original intact.
|
||||
InOrder order = inOrder(ec2);
|
||||
order.verify(ec2).createLaunchTemplate(eq("us-east-1"), eq("new-name"), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), any());
|
||||
order.verify(ec2).createLaunchTemplate(eq("us-east-1"), eq("new-name"), any(), any());
|
||||
order.verify(ec2).deleteLaunchTemplate("us-east-1", "lt-old", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void profileNameIsNormalizedToInstanceProfileArn() {
|
||||
when(ec2.createLaunchTemplate(any(), any(), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(template("lt-prof"));
|
||||
void profileGivenOnlyByNameKeepsThatForm() {
|
||||
// Normalizing Name into an Arn here is what made
|
||||
// aws_launch_template.iam_instance_profile.name never converge: Terraform sets .name and
|
||||
// read back .arn. EC2 derives the ARN at launch time instead.
|
||||
when(ec2.createLaunchTemplate(any(), any(), any(), any())).thenReturn(template("lt-prof"));
|
||||
ObjectNode data = mapper.createObjectNode();
|
||||
data.putObject("IamInstanceProfile").put("Name", "my-profile");
|
||||
ObjectNode props = mapper.createObjectNode();
|
||||
@@ -174,16 +171,15 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
|
||||
provisioner.provision(resource("Lt"), props, ctx());
|
||||
|
||||
verify(ec2).createLaunchTemplate(eq("us-east-1"), anyString(), isNull(), isNull(), isNull(),
|
||||
isNull(), isNull(), isNull(),
|
||||
eq("arn:aws:iam::000000000000:instance-profile/my-profile"), isNull(), isNull());
|
||||
ArgumentCaptor<LaunchTemplateData> captor = ArgumentCaptor.forClass(LaunchTemplateData.class);
|
||||
verify(ec2).createLaunchTemplate(eq("us-east-1"), anyString(), captor.capture(), isNull());
|
||||
assertEquals("my-profile", captor.getValue().getIamInstanceProfile().getName());
|
||||
assertNull(captor.getValue().getIamInstanceProfile().getArn());
|
||||
}
|
||||
|
||||
@Test
|
||||
void profileArnIsPassedThrough() {
|
||||
when(ec2.createLaunchTemplate(any(), any(), any(), any(), any(),
|
||||
any(), any(), any(), any(), any(), any()))
|
||||
.thenReturn(template("lt-prof"));
|
||||
when(ec2.createLaunchTemplate(any(), any(), any(), any())).thenReturn(template("lt-prof"));
|
||||
ObjectNode data = mapper.createObjectNode();
|
||||
data.putObject("IamInstanceProfile")
|
||||
.put("Arn", "arn:aws:iam::000000000000:instance-profile/explicit");
|
||||
@@ -193,19 +189,11 @@ class Ec2LaunchTemplateCfnProvisionerTest {
|
||||
|
||||
provisioner.provision(resource("Lt"), props, ctx());
|
||||
|
||||
verify(ec2).createLaunchTemplate(eq("us-east-1"), anyString(), isNull(), isNull(), isNull(),
|
||||
eq(List.of("sg-1", "sg-2")), isNull(), isNull(),
|
||||
eq("arn:aws:iam::000000000000:instance-profile/explicit"), isNull(), isNull());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteDelegatesToServiceById() {
|
||||
provisioner.delete("AWS::EC2::LaunchTemplate", "lt-abc123", "us-east-1");
|
||||
verify(ec2).deleteLaunchTemplate("us-east-1", "lt-abc123", null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void handlesOnlyLaunchTemplate() {
|
||||
assertEquals(Set.of("AWS::EC2::LaunchTemplate"), provisioner.resourceTypes());
|
||||
ArgumentCaptor<LaunchTemplateData> captor = ArgumentCaptor.forClass(LaunchTemplateData.class);
|
||||
verify(ec2).createLaunchTemplate(eq("us-east-1"), anyString(), captor.capture(), isNull());
|
||||
assertEquals("arn:aws:iam::000000000000:instance-profile/explicit",
|
||||
captor.getValue().getIamInstanceProfile().getArn());
|
||||
assertNull(captor.getValue().getIamInstanceProfile().getName());
|
||||
assertEquals(List.of("sg-1", "sg-2"), captor.getValue().getSecurityGroupIds());
|
||||
}
|
||||
}
|
||||
@@ -1594,8 +1594,10 @@ class Ec2IntegrationTest {
|
||||
equalTo("t3.micro"))
|
||||
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.userData",
|
||||
equalTo(launchTemplateUserData))
|
||||
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.iamInstanceProfile.arn",
|
||||
equalTo("arn:aws:iam::000000000000:instance-profile/sample-profile"))
|
||||
// Submitted as Name, so it reads back as Name. Rewriting it to an Arn is what made
|
||||
// aws_launch_template.iam_instance_profile.name diff forever.
|
||||
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.iamInstanceProfile.name",
|
||||
equalTo("sample-profile"))
|
||||
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.tagSpecificationSet.item.resourceType",
|
||||
equalTo("instance"))
|
||||
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.tagSpecificationSet.item.tagSet.item.find { it.key == 'example:ClusterId' }.value",
|
||||
@@ -1638,8 +1640,8 @@ class Ec2IntegrationTest {
|
||||
equalTo("t3.small"))
|
||||
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.userData",
|
||||
equalTo(launchTemplateVersionUserData))
|
||||
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.iamInstanceProfile.arn",
|
||||
equalTo("arn:aws:iam::000000000000:instance-profile/sample-profile-v2"))
|
||||
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.iamInstanceProfile.name",
|
||||
equalTo("sample-profile-v2"))
|
||||
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.tagSpecificationSet.item.tagSet.item.find { it.key == 'example:NodeType' }.value",
|
||||
equalTo("SECONDARY"));
|
||||
|
||||
|
||||
+354
@@ -0,0 +1,354 @@
|
||||
package io.github.hectorvent.floci.services.ec2;
|
||||
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.ValidatableResponse;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.contains;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
/**
|
||||
* Regression tests for CreateLaunchTemplate discarding nearly all of RequestLaunchTemplateData.
|
||||
*
|
||||
* <p>Only ImageId, InstanceType, KeyName, UserData, IamInstanceProfile, SecurityGroupIds and
|
||||
* TagSpecifications survived a create; MetadataOptions, BlockDeviceMappings, NetworkInterfaces and
|
||||
* every options block were dropped without an error. Terraform then read back its own input
|
||||
* missing and reported "Provider produced inconsistent result after apply", or diffed forever.
|
||||
*
|
||||
* <p>Field names and shapes here follow the EC2 service model's RequestLaunchTemplateData and
|
||||
* ResponseLaunchTemplateData. The request parameter names are the ones botocore's EC2 serializer
|
||||
* actually emits — note the singular {@code BlockDeviceMapping.1} / {@code NetworkInterface.1}
|
||||
* list prefixes, which come from each list member's locationName.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class Ec2LaunchTemplateFieldsIntegrationTest {
|
||||
|
||||
private static final String AUTH_HEADER =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
|
||||
|
||||
private static final String DATA =
|
||||
"DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.launchTemplateData.";
|
||||
|
||||
private String uniqueName(String prefix) {
|
||||
return prefix + "-" + UUID.randomUUID().toString().substring(0, 8);
|
||||
}
|
||||
|
||||
private String describeBody(String name) {
|
||||
return describeLatest(name).extract().body().asString();
|
||||
}
|
||||
|
||||
private ValidatableResponse describeLatest(String name) {
|
||||
return given()
|
||||
.formParam("Action", "DescribeLaunchTemplateVersions")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("Versions.1", "$Latest")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
void metadataOptionsAndBlockDeviceMappingsRoundTrip() {
|
||||
String name = uniqueName("repro-lt");
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
|
||||
.formParam("LaunchTemplateData.BlockDeviceMapping.1.DeviceName", "/dev/xvda")
|
||||
.formParam("LaunchTemplateData.BlockDeviceMapping.1.Ebs.VolumeSize", "20")
|
||||
.formParam("LaunchTemplateData.BlockDeviceMapping.1.Ebs.VolumeType", "gp3")
|
||||
.formParam("LaunchTemplateData.BlockDeviceMapping.1.Ebs.Encrypted", "true")
|
||||
.formParam("LaunchTemplateData.MetadataOptions.HttpTokens", "required")
|
||||
.formParam("LaunchTemplateData.MetadataOptions.HttpPutResponseHopLimit", "2")
|
||||
.formParam("LaunchTemplateData.EbsOptimized", "true")
|
||||
.formParam("LaunchTemplateData.Monitoring.Enabled", "true")
|
||||
.formParam("LaunchTemplateData.CpuOptions.CoreCount", "1")
|
||||
.formParam("LaunchTemplateData.CpuOptions.ThreadsPerCore", "1")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
describeLatest(name)
|
||||
// IMDSv2 — appears in essentially every Gruntwork ASG/ECS module.
|
||||
.body(DATA + "metadataOptions.httpTokens", equalTo("required"))
|
||||
.body(DATA + "metadataOptions.httpPutResponseHopLimit", equalTo("2"))
|
||||
.body(DATA + "metadataOptions.state", equalTo("applied"))
|
||||
.body(DATA + "blockDeviceMappingSet.item.deviceName", equalTo("/dev/xvda"))
|
||||
.body(DATA + "blockDeviceMappingSet.item.ebs.volumeSize", equalTo("20"))
|
||||
.body(DATA + "blockDeviceMappingSet.item.ebs.volumeType", equalTo("gp3"))
|
||||
.body(DATA + "blockDeviceMappingSet.item.ebs.encrypted", equalTo("true"))
|
||||
.body(DATA + "ebsOptimized", equalTo("true"))
|
||||
.body(DATA + "monitoring.enabled", equalTo("true"))
|
||||
.body(DATA + "cpuOptions.coreCount", equalTo("1"))
|
||||
.body(DATA + "cpuOptions.threadsPerCore", equalTo("1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void remainingOptionsBlocksRoundTrip() {
|
||||
String name = uniqueName("options-lt");
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.Placement.Tenancy", "default")
|
||||
.formParam("LaunchTemplateData.Placement.AvailabilityZone", "us-east-1a")
|
||||
.formParam("LaunchTemplateData.CreditSpecification.CpuCredits", "unlimited")
|
||||
.formParam("LaunchTemplateData.EnclaveOptions.Enabled", "false")
|
||||
.formParam("LaunchTemplateData.HibernationOptions.Configured", "false")
|
||||
.formParam("LaunchTemplateData.MaintenanceOptions.AutoRecovery", "default")
|
||||
.formParam("LaunchTemplateData.PrivateDnsNameOptions.HostnameType", "ip-name")
|
||||
.formParam("LaunchTemplateData.PrivateDnsNameOptions.EnableResourceNameDnsARecord", "true")
|
||||
.formParam("LaunchTemplateData.CapacityReservationSpecification.CapacityReservationPreference", "open")
|
||||
.formParam("LaunchTemplateData.DisableApiTermination", "false")
|
||||
.formParam("LaunchTemplateData.InstanceInitiatedShutdownBehavior", "terminate")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
describeLatest(name)
|
||||
.body(DATA + "placement.tenancy", equalTo("default"))
|
||||
.body(DATA + "placement.availabilityZone", equalTo("us-east-1a"))
|
||||
.body(DATA + "creditSpecification.cpuCredits", equalTo("unlimited"))
|
||||
.body(DATA + "enclaveOptions.enabled", equalTo("false"))
|
||||
.body(DATA + "hibernationOptions.configured", equalTo("false"))
|
||||
.body(DATA + "maintenanceOptions.autoRecovery", equalTo("default"))
|
||||
.body(DATA + "privateDnsNameOptions.hostnameType", equalTo("ip-name"))
|
||||
.body(DATA + "privateDnsNameOptions.enableResourceNameDnsARecord", equalTo("true"))
|
||||
.body(DATA + "capacityReservationSpecification.capacityReservationPreference", equalTo("open"))
|
||||
.body(DATA + "disableApiTermination", equalTo("false"))
|
||||
.body(DATA + "instanceInitiatedShutdownBehavior", equalTo("terminate"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void iamInstanceProfileKeepsTheFormItWasGiven() {
|
||||
// Terraform sets .name and read back .arn, so iam_instance_profile.name never converged.
|
||||
String byName = uniqueName("profile-name-lt");
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", byName)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.IamInstanceProfile.Name", "audit-ip")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
describeLatest(byName)
|
||||
.body(DATA + "iamInstanceProfile.name", equalTo("audit-ip"));
|
||||
assertFalse(describeBody(byName).contains("<arn>"),
|
||||
"a profile submitted as Name must not read back carrying an arn");
|
||||
|
||||
String byArn = uniqueName("profile-arn-lt");
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", byArn)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.IamInstanceProfile.Arn",
|
||||
"arn:aws:iam::000000000000:instance-profile/explicit")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
describeLatest(byArn)
|
||||
.body(DATA + "iamInstanceProfile.arn",
|
||||
equalTo("arn:aws:iam::000000000000:instance-profile/explicit"));
|
||||
assertFalse(describeBody(byArn).contains("<name>"),
|
||||
"a profile submitted as Arn must not read back carrying a name");
|
||||
}
|
||||
|
||||
@Test
|
||||
void networkInterfacesSurviveAsNetworkInterfacesInsteadOfBeingPromoted() {
|
||||
// Groups used to be hoisted into top-level SecurityGroupIds and the whole
|
||||
// NetworkInterfaces block discarded. On AWS the two are mutually exclusive, so the
|
||||
// network_interfaces block simply vanished from Terraform state.
|
||||
String name = uniqueName("eni-lt");
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.DeviceIndex", "0")
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.SubnetId", "subnet-0123456789abcdef0")
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.AssociatePublicIpAddress", "true")
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.DeleteOnTermination", "true")
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.SecurityGroupId.1", "sg-1111111111111111a")
|
||||
.formParam("LaunchTemplateData.NetworkInterface.1.SecurityGroupId.2", "sg-2222222222222222b")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
describeLatest(name)
|
||||
.body(DATA + "networkInterfaceSet.item.deviceIndex", equalTo("0"))
|
||||
.body(DATA + "networkInterfaceSet.item.subnetId", equalTo("subnet-0123456789abcdef0"))
|
||||
.body(DATA + "networkInterfaceSet.item.associatePublicIpAddress", equalTo("true"))
|
||||
.body(DATA + "networkInterfaceSet.item.deleteOnTermination", equalTo("true"))
|
||||
.body(DATA + "networkInterfaceSet.item.groupSet.item",
|
||||
contains("sg-1111111111111111a", "sg-2222222222222222b"));
|
||||
// Not promoted to the top level: that promotion is what made the block disappear.
|
||||
assertFalse(describeBody(name).contains("securityGroupIdSet"),
|
||||
"interface groups must not be hoisted into top-level SecurityGroupIds");
|
||||
}
|
||||
|
||||
@Test
|
||||
void createLaunchTemplateVersionInheritsOptionsBlocksItDoesNotRestate() {
|
||||
String name = uniqueName("version-lt");
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
|
||||
.formParam("LaunchTemplateData.MetadataOptions.HttpTokens", "required")
|
||||
.formParam("LaunchTemplateData.BlockDeviceMapping.1.DeviceName", "/dev/xvda")
|
||||
.formParam("LaunchTemplateData.BlockDeviceMapping.1.Ebs.VolumeSize", "20")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplateVersion")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("SourceVersion", "1")
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.small")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.instanceType",
|
||||
equalTo("t3.small"))
|
||||
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData"
|
||||
+ ".metadataOptions.httpTokens", equalTo("required"));
|
||||
|
||||
describeLatest(name)
|
||||
.body(DATA + "instanceType", equalTo("t3.small"))
|
||||
.body(DATA + "metadataOptions.httpTokens", equalTo("required"))
|
||||
.body(DATA + "blockDeviceMappingSet.item.deviceName", equalTo("/dev/xvda"))
|
||||
.body(DATA + "blockDeviceMappingSet.item.ebs.volumeSize", equalTo("20"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createLaunchTemplateVersionWithoutSourceVersionDoesNotInherit() {
|
||||
// AWS documents "no SourceVersion" as "no inheritance" — the new version must start from
|
||||
// an empty LaunchTemplateData, not merge onto the latest version the way an explicit
|
||||
// SourceVersion does (see createLaunchTemplateVersionInheritsOptionsBlocksItDoesNotRestate
|
||||
// above, which covers the explicit-SourceVersion case).
|
||||
String name = uniqueName("no-source-lt");
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.micro")
|
||||
.formParam("LaunchTemplateData.KeyName", "app-key")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplateVersion")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
// No SourceVersion parameter at all.
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.small")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.launchTemplateData.instanceType",
|
||||
equalTo("t3.small"));
|
||||
|
||||
String body = describeBody(name);
|
||||
assertFalse(body.contains("<imageId>"),
|
||||
"an omitted SourceVersion must not inherit ImageId from the latest version");
|
||||
assertFalse(body.contains("<keyName>"),
|
||||
"an omitted SourceVersion must not inherit KeyName from the latest version");
|
||||
}
|
||||
|
||||
@Test
|
||||
void versionDescriptionRoundTripsThroughCreateAndDescribe() {
|
||||
String name = uniqueName("described-lt");
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("VersionDescription", "initial rollout")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CreateLaunchTemplateResponse.launchTemplate.launchTemplateId", org.hamcrest.Matchers.notNullValue());
|
||||
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplateVersion")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("SourceVersion", "1")
|
||||
.formParam("LaunchTemplateData.InstanceType", "t3.small")
|
||||
.formParam("VersionDescription", "bump instance type")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("CreateLaunchTemplateVersionResponse.launchTemplateVersion.versionDescription",
|
||||
equalTo("bump instance type"));
|
||||
|
||||
given()
|
||||
.formParam("Action", "DescribeLaunchTemplateVersions")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("Versions.1", "1")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200)
|
||||
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.versionDescription",
|
||||
equalTo("initial rollout"));
|
||||
|
||||
describeLatest(name)
|
||||
.body("DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item.versionDescription",
|
||||
equalTo("bump instance type"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void securityGroupsByNameAreAcceptedAndIgnored() {
|
||||
// By-name SecurityGroups stay out of scope (see docs/services/ec2.md): resolving names to
|
||||
// IDs would need lookup machinery no other EC2 action here has either. The request must
|
||||
// still succeed, and SecurityGroupIds — the supported form — must be unaffected.
|
||||
String name = uniqueName("sg-by-name-lt");
|
||||
given()
|
||||
.formParam("Action", "CreateLaunchTemplate")
|
||||
.formParam("LaunchTemplateName", name)
|
||||
.formParam("LaunchTemplateData.ImageId", "ami-0abcdef1234567890")
|
||||
.formParam("LaunchTemplateData.SecurityGroup.1", "my-app-sg")
|
||||
.formParam("LaunchTemplateData.SecurityGroupId.1", "sg-1111111111111111a")
|
||||
.header("Authorization", AUTH_HEADER)
|
||||
.when()
|
||||
.post("/")
|
||||
.then()
|
||||
.statusCode(200);
|
||||
|
||||
describeLatest(name)
|
||||
.body(DATA + "securityGroupIdSet.item", equalTo("sg-1111111111111111a"));
|
||||
assertFalse(describeBody(name).contains("my-app-sg"),
|
||||
"SecurityGroups (by name) is accepted and ignored, not stored");
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import io.github.hectorvent.floci.services.ec2.model.Image;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NetworkAcl;
|
||||
import io.github.hectorvent.floci.services.ec2.model.KeyPair;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import io.github.hectorvent.floci.services.ec2.model.NatGateway;
|
||||
import io.github.hectorvent.floci.services.ec2.model.RouteTable;
|
||||
import io.github.hectorvent.floci.services.ec2.model.SecurityGroup;
|
||||
@@ -244,6 +245,84 @@ class Ec2ServicePersistenceTest {
|
||||
assertEquals(0, afterDelete.getRoutes().size(), "delete must actually remove the legacy route");
|
||||
}
|
||||
|
||||
/**
|
||||
* Regression test for the pre-unified-data schema migration in LaunchTemplate /
|
||||
* LaunchTemplateData: a launch template persisted before that PR stored the IAM instance
|
||||
* profile as a bare {@code iamInstanceProfileArn} string and instance tags as a flat
|
||||
* {@code instanceTags} list, both directly on LaunchTemplate and, separately, on each entry
|
||||
* of its {@code versions} map. Without the legacy {@code @JsonSetter}s those two keys are
|
||||
* unrecognized by the current model and ignoreUnknown drops them, so a template that used to
|
||||
* carry an IAM profile and instance tags would come back from a restart with neither.
|
||||
*
|
||||
* <p>This writes a hand-built ec2-launch-templates.json in the pre-migration shape directly
|
||||
* (rather than producing it by running old code), then loads a fresh Ec2Service over it and
|
||||
* asserts the profile ARN and instance tag survive - covering both the versions-map entry
|
||||
* (the path DescribeLaunchTemplateVersions and AutoScaling actually read) and the top-level
|
||||
* fields (the path ensureLaunchTemplateVersions falls back to for a template with no
|
||||
* versions map at all, i.e. one only ever read via {@code getData()} pre-migration).
|
||||
*/
|
||||
@Test
|
||||
void legacyIamProfileAndInstanceTagsSurviveRestart(@TempDir Path dir) throws java.io.IOException {
|
||||
String legacyJson = """
|
||||
{
|
||||
"us-east-1::lt-legacy-versioned": {
|
||||
"launchTemplateId": "lt-legacy-versioned",
|
||||
"launchTemplateName": "legacy-versioned",
|
||||
"defaultVersionNumber": "1",
|
||||
"latestVersionNumber": "1",
|
||||
"region": "us-east-1",
|
||||
"iamInstanceProfileArn": "arn:aws:iam::000000000000:instance-profile/legacy-profile",
|
||||
"instanceTags": [ { "key": "Name", "value": "legacy-versioned" } ],
|
||||
"versions": {
|
||||
"1": {
|
||||
"imageId": "ami-legacy",
|
||||
"instanceType": "t3.micro",
|
||||
"iamInstanceProfileArn": "arn:aws:iam::000000000000:instance-profile/legacy-profile",
|
||||
"instanceTags": [ { "key": "Name", "value": "legacy-versioned" } ]
|
||||
}
|
||||
}
|
||||
},
|
||||
"us-east-1::lt-legacy-no-versions": {
|
||||
"launchTemplateId": "lt-legacy-no-versions",
|
||||
"launchTemplateName": "legacy-no-versions",
|
||||
"defaultVersionNumber": "1",
|
||||
"latestVersionNumber": "1",
|
||||
"region": "us-east-1",
|
||||
"imageId": "ami-legacy",
|
||||
"instanceType": "t3.micro",
|
||||
"iamInstanceProfileArn": "arn:aws:iam::000000000000:instance-profile/legacy-profile",
|
||||
"instanceTags": [ { "key": "Name", "value": "legacy-no-versions" } ],
|
||||
"versions": {}
|
||||
}
|
||||
}
|
||||
""";
|
||||
Files.writeString(dir.resolve("ec2-launch-templates.json"), legacyJson);
|
||||
|
||||
Ec2Service restarted = newService(dir);
|
||||
|
||||
LaunchTemplateData versioned = restarted
|
||||
.describeLaunchTemplateVersions(REGION, "lt-legacy-versioned", null, List.of())
|
||||
.getFirst()
|
||||
.getData();
|
||||
assertEquals("arn:aws:iam::000000000000:instance-profile/legacy-profile",
|
||||
restarted.iamInstanceProfileArn(versioned),
|
||||
"IAM instance profile on a legacy versions-map entry must survive restart");
|
||||
assertEquals(List.of("legacy-versioned"),
|
||||
versioned.getInstanceTags().stream().map(Tag::getValue).toList(),
|
||||
"instance tags on a legacy versions-map entry must survive restart");
|
||||
|
||||
LaunchTemplateData noVersions = restarted
|
||||
.describeLaunchTemplateVersions(REGION, "lt-legacy-no-versions", null, List.of())
|
||||
.getFirst()
|
||||
.getData();
|
||||
assertEquals("arn:aws:iam::000000000000:instance-profile/legacy-profile",
|
||||
restarted.iamInstanceProfileArn(noVersions),
|
||||
"IAM instance profile on a legacy template with no versions map must survive restart");
|
||||
assertEquals(List.of("legacy-no-versions"),
|
||||
noVersions.getInstanceTags().stream().map(Tag::getValue).toList(),
|
||||
"instance tags on a legacy template with no versions map must survive restart");
|
||||
}
|
||||
|
||||
private BlockDeviceMapping blockDeviceMapping(String snapshotId, int volumeSize) {
|
||||
EbsBlockDevice ebs = new EbsBlockDevice();
|
||||
ebs.setSnapshotId(snapshotId);
|
||||
|
||||
@@ -17,6 +17,7 @@ import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
|
||||
import io.github.hectorvent.floci.services.ec2.model.UserIdGroupPair;
|
||||
import io.github.hectorvent.floci.services.ec2.model.InstanceState;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplate;
|
||||
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
|
||||
import io.github.hectorvent.floci.services.ec2.model.ManagedPrefixList;
|
||||
import io.github.hectorvent.floci.services.ec2.model.SecurityGroupRule;
|
||||
import io.github.hectorvent.floci.services.ec2.model.PrefixListId;
|
||||
@@ -221,28 +222,92 @@ class Ec2ServiceTest {
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
LaunchTemplate template = service.createLaunchTemplate("us-east-1", "app-template",
|
||||
"ami-source", "t3.micro", "app-key", List.of("sg-source"),
|
||||
"source-user-data", "c291cmNlLXVzZXItZGF0YQ==",
|
||||
"arn:aws:iam::000000000000:instance-profile/app-profile",
|
||||
List.of(), List.of(new Tag("Role", "source")));
|
||||
LaunchTemplateData source = new LaunchTemplateData();
|
||||
source.setImageId("ami-source");
|
||||
source.setInstanceType("t3.micro");
|
||||
source.setKeyName("app-key");
|
||||
source.setSecurityGroupIds(List.of("sg-source"));
|
||||
source.setUserData("source-user-data");
|
||||
source.setEncodedUserData("c291cmNlLXVzZXItZGF0YQ==");
|
||||
source.setIamInstanceProfile(new LaunchTemplateData.IamInstanceProfile(
|
||||
"arn:aws:iam::000000000000:instance-profile/app-profile", null));
|
||||
source.setTagSpecifications(List.of(
|
||||
new LaunchTemplateData.TagSpecification("instance", List.of(new Tag("Role", "source")))));
|
||||
LaunchTemplate template = service.createLaunchTemplate("us-east-1", "app-template", source, List.of());
|
||||
|
||||
service.createLaunchTemplateVersion("us-east-1", template.getLaunchTemplateId(), null,
|
||||
"1", null, "t3.small", null, List.of(), null, null, null, List.of());
|
||||
LaunchTemplateData override = new LaunchTemplateData();
|
||||
override.setInstanceType("t3.small");
|
||||
service.createLaunchTemplateVersion("us-east-1", template.getLaunchTemplateId(), null, "1", override);
|
||||
|
||||
LaunchTemplate version = service.describeLaunchTemplateVersions(
|
||||
"us-east-1", template.getLaunchTemplateId(), null, List.of("2")).getFirst();
|
||||
assertEquals("ami-source", version.getImageId());
|
||||
assertEquals("t3.small", version.getInstanceType());
|
||||
assertEquals("app-key", version.getKeyName());
|
||||
assertEquals(List.of("sg-source"), version.getSecurityGroupIds());
|
||||
assertEquals("source-user-data", version.getUserData());
|
||||
assertEquals("c291cmNlLXVzZXItZGF0YQ==", version.getEncodedUserData());
|
||||
assertEquals("arn:aws:iam::000000000000:instance-profile/app-profile", version.getIamInstanceProfileArn());
|
||||
LaunchTemplateData data = version.getData();
|
||||
assertEquals("ami-source", data.getImageId());
|
||||
assertEquals("t3.small", data.getInstanceType());
|
||||
assertEquals("app-key", data.getKeyName());
|
||||
assertEquals(List.of("sg-source"), data.getSecurityGroupIds());
|
||||
assertEquals("source-user-data", data.getUserData());
|
||||
assertEquals("c291cmNlLXVzZXItZGF0YQ==", data.getEncodedUserData());
|
||||
assertEquals("arn:aws:iam::000000000000:instance-profile/app-profile",
|
||||
data.getIamInstanceProfile().getArn());
|
||||
assertEquals("2", version.getLatestVersionNumber());
|
||||
assertEquals(1, version.getInstanceTags().size());
|
||||
assertEquals("Role", version.getInstanceTags().getFirst().getKey());
|
||||
assertEquals("source", version.getInstanceTags().getFirst().getValue());
|
||||
assertEquals(1, data.getInstanceTags().size());
|
||||
assertEquals("Role", data.getInstanceTags().getFirst().getKey());
|
||||
assertEquals("source", data.getInstanceTags().getFirst().getValue());
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchTemplateVersionWithoutSourceVersionDoesNotInheritFromLatest() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
LaunchTemplateData source = new LaunchTemplateData();
|
||||
source.setImageId("ami-source");
|
||||
source.setInstanceType("t3.micro");
|
||||
source.setKeyName("app-key");
|
||||
source.setSecurityGroupIds(List.of("sg-source"));
|
||||
LaunchTemplate template = service.createLaunchTemplate("us-east-1", "no-source-template", source, List.of());
|
||||
|
||||
LaunchTemplateData override = new LaunchTemplateData();
|
||||
override.setInstanceType("t3.small");
|
||||
// No SourceVersion at all — AWS documents this as "no source specified, no inheritance",
|
||||
// not as an implicit fallback onto the latest version.
|
||||
service.createLaunchTemplateVersion("us-east-1", template.getLaunchTemplateId(), null, null, override);
|
||||
|
||||
LaunchTemplate version = service.describeLaunchTemplateVersions(
|
||||
"us-east-1", template.getLaunchTemplateId(), null, List.of("2")).getFirst();
|
||||
LaunchTemplateData data = version.getData();
|
||||
assertEquals("t3.small", data.getInstanceType());
|
||||
assertNull(data.getImageId(), "omitted SourceVersion must not inherit ImageId from version 1");
|
||||
assertNull(data.getKeyName(), "omitted SourceVersion must not inherit KeyName from version 1");
|
||||
assertEquals(List.of(), data.getSecurityGroupIds(),
|
||||
"omitted SourceVersion must not inherit SecurityGroupIds from version 1");
|
||||
}
|
||||
|
||||
@Test
|
||||
void launchTemplateVersionDescriptionRoundTrips() {
|
||||
Ec2Service service = new Ec2Service(mockConfig(true), mock(Ec2ContainerManager.class),
|
||||
mock(Ec2PortForwardManager.class),
|
||||
mock(AmiImageResolver.class), mock(Ec2ImageCatalog.class), new Ec2InstanceTypeCatalog(),
|
||||
new InMemoryStorageFactory());
|
||||
LaunchTemplateData source = new LaunchTemplateData();
|
||||
source.setImageId("ami-source");
|
||||
LaunchTemplate template = service.createLaunchTemplate(
|
||||
"us-east-1", "described-template", source, List.of(), "initial version");
|
||||
|
||||
LaunchTemplateData override = new LaunchTemplateData();
|
||||
override.setInstanceType("t3.small");
|
||||
LaunchTemplate created = service.createLaunchTemplateVersion(
|
||||
"us-east-1", template.getLaunchTemplateId(), null, "1", override, "second version");
|
||||
assertEquals("second version", created.getVersionDescription());
|
||||
|
||||
LaunchTemplate v1 = service.describeLaunchTemplateVersions(
|
||||
"us-east-1", template.getLaunchTemplateId(), null, List.of("1")).getFirst();
|
||||
LaunchTemplate v2 = service.describeLaunchTemplateVersions(
|
||||
"us-east-1", template.getLaunchTemplateId(), null, List.of("2")).getFirst();
|
||||
assertEquals("initial version", v1.getVersionDescription());
|
||||
assertEquals("second version", v2.getVersionDescription());
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
Reference in new issue
Block a user