fix(cloudformation): carry EC2 MetadataOptions from templates and instances (#6050)

* fix(cloudformation): carry EC2 MetadataOptions from templates and instances

AWS::EC2::LaunchTemplate dropped LaunchTemplateData.MetadataOptions,
and AWS::EC2::Instance read only the image, type and key from its
launch template and ignored its own MetadataOptions. A CDK instance with
requireImdsv2 therefore launched with HttpTokens=optional, and
DescribeInstances reported that whatever the template declared.

The template now stores the block, the instance launches with its own
options over its template's, and an update that changes them applies
them in place with ModifyInstanceMetadataOptions, as the property's
"No interruption" update behavior allows. A hop limit that is not an
integer fails the resource.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): check MetadataOptions first and reset dropped ones

An update that keeps an AWS::EC2::Instance applied its MetadataOptions
last, after resizing it and rewriting its security groups, user data
and profile, so a bad value failed the update with the instance half
changed while the stack reported a rollback. The options are now
checked with EC2's own rules before anything changes, which needs
Ec2Service.validateMetadataOptions to be public.

An update that stopped declaring an option, its own or through its
launch template (CDK's requireImdsv2 turned off), left the instance
with it. The provisioner now records what it declared and returns an
option it no longer declares to the launch default, as it already does
for an instance profile it stops declaring.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): replace an instance whose launch template changes

LaunchTemplate is a replacement property of AWS::EC2::Instance, and
Floci's change-set preview already says so, but an update kept the
instance whatever happened to it: removing the template (CDK's
requireImdsv2 turned off) reset the instance's options in place where
AWS launches a new instance. The provisioner now records which template
it declared and replaces the instance when the update names another
one, adds one or drops it. A new version of the same template is still
applied in place, because Floci's AWS::EC2::LaunchTemplate publishes a
version on every stack update.

The record of declared MetadataOptions now keeps only the member names,
which is all the reset needs, instead of a serialized model object.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): track template versions and roll records back

The previous commit left a new version of the same launch template in
place, on the grounds that the template's provisioner publishes a
version on every stack update. It publishes one only when the template
itself changes, so an instance naming Fn::GetAtt LatestVersionNumber
sees its LaunchTemplate change exactly when AWS replaces it. The
recorded spec now includes the version, and the change-set preview and
the update agree: another template or version, or none, replaces the
instance; one added to an instance launched without one keeps it, and
an instance launched without one now carries no record at all.

When a later resource failed a replacing update, the rollback restored
the prior instance but kept the attempt's __FlociDeclared records, so a
retry compared against the wrong declaration (a retried template drop
kept the instance requiring tokens). The records as they stood before
the replacement are saved and put back by rollbackUpdate, and cleared
when the update completes.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): keep an instance whose launch template changes

Replacing an instance on another launch template, version or none could
not be made to agree with the change-set preview: a Version given by
Fn::GetAtt LatestVersionNumber previews no replacement, and the template
publishes a new, identical version for a Metadata-only change. Keep the
instance in place, as upstream does, and reconcile what the template
declares; the docs state this as a deviation from AWS.

A rollback whose delete of the replacement throws has already named the
prior instance again, and a rollback that then skips the resource never
calls back, so put the prior instance's declared records back before
rethrowing. A saved copy that cannot be read now fails the rollback.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): keep a rollback's delete failure over a bad record

When the replacement's delete fails and the saved declarations cannot
be read, report the delete failure with the read failure suppressed,
rather than replacing it.

The docs and the provisioner comment said every launch template change
keeps the instance; an ImageId or KeyName the template supplies still
replaces it, and a change set still previews a literal LaunchTemplate
change as a replacement. Tests pin the replacement and a retried
rollback.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* chore(cloudformation): vendor EC2 instance and launch template property types

AWS::EC2::Instance and AWS::EC2::LaunchTemplate are to read their
MetadataOptions through CfnPropertyTypes, so the generator lists them
and checks the MetadataOptions members they rely on. Only their entries
are added to the vendored file: a fresh generation also carries new
AWS::ECS::TaskDefinition members AWS has published since, which belong
to their own sync.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): refuse EC2 MetadataOptions of the wrong type

AWS::EC2::Instance and AWS::EC2::LaunchTemplate read a MetadataOptions
member given as a list or an object, such as HttpTokens: [required], as
absent, so the instance launched with HttpTokens=optional; a block that
was not an object was dropped the same way. Read the block through
CfnPropertyTypes against the shape each resource schema declares, as
AWS::AutoScaling::LaunchConfiguration is: a block or member of the
wrong type now fails the resource with CloudFormation's template
validation error, and a hop limit that is not a whole number says what
it is ("found: Float") rather than a message Floci made up.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): let AWS::NoValue omit launch template metadata options

The launch template read its MetadataOptions from LaunchTemplateData
after resolving it, which turns AWS::NoValue into an empty string, so
since the previous commit a block or hop limit left out with Fn::If and
AWS::NoValue failed the template as the wrong type. Read the block as
the template writes it, with AWS::NoValue already left out, as the
instance does.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* refactor(cloudformation): drop the launch template's unreachable options fallback

When LaunchTemplateData is absent or an intrinsic call, its resolved
form has no MetadataOptions member either, so the fallback to it always
gave null. Say so and use null. A test row also covers a launch template
whose MetadataOptions is a string.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): put back metadata options a stack rollback undoes

An update that kept the instance and changed its MetadataOptions left
them changed when a later resource failed and the stack rolled back:
rollbackUpdate undid replacements only, so the instance kept options
the stack no longer declared, and the stack reported that the update
could not be rolled back.

The update now saves the options it replaces, with their region and the
instance's __FlociDeclared records, and changes them last, after the
tags, so nothing else in the step can fail after them. rollbackUpdate
puts both back. The rollback counts as done only when the update changed
nothing else on the instance; the instance type, groups, user data,
profile and tags still have no rollback, so the stack keeps saying so
for them, with the options put back all the same. Ec2Tags.reconcile now
reports whether it changed anything, so a tag change counts. A committed
or cleared update drops the saved copy.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(ec2): describe CloudFormation MetadataOptions and launch template updates

The EC2 notes now say that AWS::EC2::LaunchTemplate stores
MetadataOptions and AWS::EC2::Instance launches with its own over its
template's, what a wrong type and AWS::NoValue do, that an update
applies and resets options in place and a rollback puts them back, and
that a changed or dropped LaunchTemplate keeps the instance where AWS
replaces it, unless the ImageId or KeyName it supplies changed.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): pin the tag change and order in an options rollback

A tag change in the same in-place update makes a rollback put the
MetadataOptions back but report the update undone, and a tag failure
leaves the options unchanged, since they are the update's last change.
The validation comment now lists tags among what runs before them.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* fix(cloudformation): roll back declaration-only updates and refuse blank options

An update that kept the instance saved a rollback record only when it
changed the instance's MetadataOptions. One that changed only what was
declared, such as declaring a default the instance already had, left
rollbackUpdate nothing to restore, so a later resource's failure ended
the stack with "Rollback is not implemented". Every update that keeps
the instance now saves its __FlociDeclared records, with the prior
options only when it changes them, and a rollback restores what was
saved and counts as done when nothing else on the instance changed.

A MetadataOptions member given as an empty or padded string read as
absent, so HttpTokens: "" launched with the default. The text is now
kept as written and EC2's checks refuse it, as EC2 does; AWS::NoValue
still leaves a member out.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* chore(cloudformation): sync the vendored property types with AWS

The vendored file lacked the AWS::ECS::TaskDefinition SharingStrategy
and NvidiaMpsAllocation members AWS has published since it was last
generated, so the drift check, which runs when a change touches the
file, failed. This is make cfn-property-types-sync, and the file now
matches AWS's schemas.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* test(cloudformation): cover tag-only and declaration-only rollbacks

A rolled-back update that changed only tags puts the declarations back
and reports that it could not undo the update, without touching the
options. A stack whose update only declares the default HttpTokens the
instance already has ends UPDATE_ROLLBACK_COMPLETE when a later
resource fails, and a string member left out with Fn::If and
AWS::NoValue keeps its default. The ec2 notes say that a blank member
is refused and that an update that changed no EC2 setting rolls back in
full, which covers any property Floci does not apply, not only
MetadataOptions. A stale test name and comment are corrected.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* revert(cloudformation): leave AWS's ECS schema change to its own sync

The drift check fails on main as well: AWS has added SharingStrategy and
NvidiaMpsAllocation to AWS::ECS::TaskDefinition since main vendored the
file, and a fresh generation from main's own tree shows the same three
ECS shapes. The AWS::EC2::Instance and AWS::EC2::LaunchTemplate entries
this PR vendors already match AWS. The resync is an unrelated change, so
the vendored file goes back to this PR's EC2-only addition; the check
stays red until main syncs.

This reverts commit 092eb432f.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* docs(ec2): say a launch template stores a blank metadata option unchecked

The ec2 notes said a blank MetadataOptions member is refused, in a
sentence about both resources, but AWS::EC2::LaunchTemplate stores it
unchecked, as CreateLaunchTemplate does, and only the instances launched
from it fail. The declaration-only rollback test also says that its
stack status, not the options, is what it checks.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

* chore(cloudformation): sync the vendored ECS task definition types with AWS

The vendored property types check has to pass before this change can
merge, and AWS::ECS::TaskDefinition's SharingStrategy and
NvidiaMpsAllocation members are the only drift left: the
AWS::EC2::Instance and AWS::EC2::LaunchTemplate types this change adds
already match AWS. This brings back the sync from 092eb432f, which
51dca7d0f had left out of this change.

This reverts commit 51dca7d0f.

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>

---------

Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
Jackson Price authored and GitHub committed 2026-10-20 11:55:39 -04:00
1 parent e14e5433ab
commit d09b3215d5
13 files changed
+2354 -35

No files matched your search

+2
View File
@@ -145,6 +145,8 @@ EC2 containers receive `AWS_EC2_METADATA_SERVICE_ENDPOINT` for IMDS and `AWS_END
CloudFormation `AWS::EC2::VPCEndpoint` resolves `IpAddressType` on create and update, including parameter references. Omission, a selected `AWS::NoValue` branch, or `not-specified` uses the default `ipv4`; an explicitly empty value is rejected. Updates retain the existing replacement behavior; synthetic interfaces remain IPv4-only.
CloudFormation `AWS::EC2::LaunchTemplate` stores `LaunchTemplateData.MetadataOptions`, and `AWS::EC2::Instance` launches with its own `MetadataOptions` over those of the launch template it names, as `RunInstances` merges them, so CDK's `requireImdsv2` sets `HttpTokens=required`. A block or member of the wrong type, such as `HttpTokens: [required]`, fails the resource with CloudFormation's type error, a member given as an empty or padded string fails an instance with `InvalidParameterValue` (a launch template stores it unchecked, as `CreateLaunchTemplate` does, and the instances launched from it fail), and `AWS::NoValue` leaves a member or the whole block out. A stack update checks the options before it changes anything, applies changed ones in place, returns options it no longer declares to their defaults, and puts them back if the stack update rolls back. An update that kept the instance and changed no EC2 setting, such as one that only declares the options the instance already has, rolls back in full. When the same update also changed the instance's type, security groups, user data, profile or tags, which have no in-place rollback, the options still go back but the stack ends `UPDATE_ROLLBACK_FAILED` for the instance ("Rollback is not implemented"). The options handling includes an update that changes or drops the instance's `LaunchTemplate` (another template or version, as `Fn::GetAtt LatestVersionNumber` gives after the template changes): AWS replaces the instance then, as `LaunchTemplate` is a replacement property, but Floci keeps it and applies what the new template declares, unless the `ImageId` or `KeyName` the template supplies changed, which replaces it. A change set still previews a literal `LaunchTemplate` change as a replacement.
## Instance Metadata Service (IMDS)
Floci runs an IMDS-compatible HTTP server on port `9169` of the host. Each launched container receives the environment variable `AWS_EC2_METADATA_SERVICE_ENDPOINT` pointing to this server.
@@ -72,6 +72,16 @@ final class CfnPropertyTypes {
return shape;
}
/** The shape the vendored shape {@code shapeName} declares for its member {@code member}. */
static String memberShape(String shapeName, String member) {
Shape owner = Holder.MODEL.shapes().get(shapeName);
String shape = owner == null || owner.members() == null ? null : owner.members().get(member);
if (shape == null) {
throw notVendored(shapeName + "." + member);
}
return shape;
}
private static IllegalStateException notVendored(String what) {
return new IllegalStateException(what + " is not in " + RESOURCE_NAME
+ "; add the type to tools/aws/regen_cfn_property_types.py");
@@ -0,0 +1,160 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.ec2.model.LaunchTemplateData;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
/**
* The {@code MetadataOptions} block that {@code AWS::EC2::Instance} and
* {@code AWS::EC2::LaunchTemplate}'s {@code LaunchTemplateData} share. A launch template stores it
* unchecked, as EC2 does; the instance provisioner checks the options it is about to apply with
* EC2's own rules before it launches or changes anything.
*/
final class Ec2CfnMetadataOptions {
private static final String HTTP_TOKENS = "HttpTokens";
private static final String HOP_LIMIT = "HttpPutResponseHopLimit";
private static final String HTTP_ENDPOINT = "HttpEndpoint";
private static final String HTTP_PROTOCOL_IPV6 = "HttpProtocolIpv6";
private static final String INSTANCE_METADATA_TAGS = "InstanceMetadataTags";
/** The shape AWS::EC2::Instance's resource schema declares for MetadataOptions. */
static final String INSTANCE_SHAPE = CfnPropertyTypes.propertyShape("AWS::EC2::Instance", "MetadataOptions");
/** The shape AWS::EC2::LaunchTemplate's resource schema declares for LaunchTemplateData's MetadataOptions. */
static final String LAUNCH_TEMPLATE_SHAPE = CfnPropertyTypes.memberShape(
CfnPropertyTypes.propertyShape("AWS::EC2::LaunchTemplate", "LaunchTemplateData"), "MetadataOptions");
private Ec2CfnMetadataOptions() {}
/**
* The options the block {@code raw}, at {@code path} in the resource's properties, names, with
* absent members left null, or null when there is no block. A member's text is kept as written,
* so an empty or padded value reaches EC2's checks and is refused, as EC2 refuses it, rather
* than reading as absent. {@code AWS::NoValue} is what leaves a member out. It is read against the
* schema shape {@code shape}, as {@code AWS::AutoScaling::LaunchConfiguration}'s is: a block or
* member of the wrong type, such as {@code HttpTokens: [required]}, fails the resource rather
* than reading as absent, which would leave tokens optional. A null member takes the launch
* default when an instance launches; on an update, {@link #toApply} decides it.
*/
static LaunchTemplateData.MetadataOptions read(String path, JsonNode raw, String shape,
CloudFormationTemplateEngine engine) {
CfnPropertyTypes.Reader types = new CfnPropertyTypes.Reader(engine);
JsonNode block = types.read(path, raw, shape);
types.finish();
if (block == null || block.isEmpty()) {
return null;
}
LaunchTemplateData.MetadataOptions options = new LaunchTemplateData.MetadataOptions();
options.setHttpTokens(member(block, HTTP_TOKENS));
options.setHttpEndpoint(member(block, HTTP_ENDPOINT));
options.setHttpProtocolIpv6(member(block, HTTP_PROTOCOL_IPV6));
options.setInstanceMetadataTags(member(block, INSTANCE_METADATA_TAGS));
JsonNode hopLimit = block.path(HOP_LIMIT);
if (hopLimit.isInt()) {
options.setHttpPutResponseHopLimit(hopLimit.intValue());
}
return options;
}
/** {@code declared} over {@code base}, member by member; either may be null. */
static LaunchTemplateData.MetadataOptions over(LaunchTemplateData.MetadataOptions base,
LaunchTemplateData.MetadataOptions declared) {
if (base == null) {
return declared;
}
return LaunchTemplateData.MetadataOptions.merge(base, declared);
}
/**
* What an update applies to the instance it keeps: every option the template declares now, and
* the launch default for any member it declared last time but no longer does, so turning an
* option off in the template turns it off on the instance. Members it never declared are left
* as the instance has them. Null when nothing was declared, then or now.
*/
static LaunchTemplateData.MetadataOptions toApply(Set<String> previouslyDeclared,
LaunchTemplateData.MetadataOptions declared) {
if (previouslyDeclared.isEmpty()) {
return declared;
}
LaunchTemplateData.MetadataOptions defaults = LaunchTemplateData.MetadataOptions.launchDefaults();
LaunchTemplateData.MetadataOptions reset = new LaunchTemplateData.MetadataOptions();
if (previouslyDeclared.contains(HTTP_TOKENS)) {
reset.setHttpTokens(defaults.getHttpTokens());
}
if (previouslyDeclared.contains(HOP_LIMIT)) {
reset.setHttpPutResponseHopLimit(defaults.getHttpPutResponseHopLimit());
}
if (previouslyDeclared.contains(HTTP_ENDPOINT)) {
reset.setHttpEndpoint(defaults.getHttpEndpoint());
}
if (previouslyDeclared.contains(HTTP_PROTOCOL_IPV6)) {
reset.setHttpProtocolIpv6(defaults.getHttpProtocolIpv6());
}
if (previouslyDeclared.contains(INSTANCE_METADATA_TAGS)) {
reset.setInstanceMetadataTags(defaults.getInstanceMetadataTags());
}
return LaunchTemplateData.MetadataOptions.merge(reset, declared);
}
/** Whether applying {@code declared} would change any option {@code current} has. */
static boolean changes(LaunchTemplateData.MetadataOptions current, LaunchTemplateData.MetadataOptions declared) {
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.merge(current, declared);
return !Objects.equals(current.getHttpTokens(), applied.getHttpTokens())
|| !Objects.equals(current.getHttpPutResponseHopLimit(), applied.getHttpPutResponseHopLimit())
|| !Objects.equals(current.getHttpEndpoint(), applied.getHttpEndpoint())
|| !Objects.equals(current.getHttpProtocolIpv6(), applied.getHttpProtocolIpv6())
|| !Objects.equals(current.getInstanceMetadataTags(), applied.getInstanceMetadataTags());
}
/**
* The CloudFormation names of the members {@code declared} sets, comma-separated, for a resource
* attribute, or null when it sets none. Only which members were declared is kept: that is all
* {@link #toApply} needs, and it does not depend on how the options are stored.
*/
static String declaredMembers(LaunchTemplateData.MetadataOptions declared) {
if (declared == null) {
return null;
}
List<String> members = new ArrayList<>();
if (declared.getHttpTokens() != null) {
members.add(HTTP_TOKENS);
}
if (declared.getHttpPutResponseHopLimit() != null) {
members.add(HOP_LIMIT);
}
if (declared.getHttpEndpoint() != null) {
members.add(HTTP_ENDPOINT);
}
if (declared.getHttpProtocolIpv6() != null) {
members.add(HTTP_PROTOCOL_IPV6);
}
if (declared.getInstanceMetadataTags() != null) {
members.add(INSTANCE_METADATA_TAGS);
}
return members.isEmpty() ? null : String.join(",", members);
}
/** The member names {@link #declaredMembers} recorded; empty when there is no record. */
static Set<String> parseDeclaredMembers(String recorded) {
if (recorded == null || recorded.isBlank()) {
return Set.of();
}
return Arrays.stream(recorded.split(",")).map(String::trim).filter(name -> !name.isEmpty())
.collect(Collectors.toUnmodifiableSet());
}
private static String member(JsonNode block, String name) {
JsonNode value = block.get(name);
if (value == null || value.isNull()) {
return null;
}
return value.asText();
}
}
@@ -1,6 +1,9 @@
package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.github.hectorvent.floci.core.common.AwsException;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
@@ -19,6 +22,7 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
@@ -39,6 +43,19 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
// The instance profile the template declared last time, so an update that drops the property
// can be told from one that never declared it (a launch template may have set the profile).
private static final String DECLARED_IAM_PROFILE_ATTR = "__FlociDeclaredIamInstanceProfile";
// The MetadataOptions members declared last time, the instance's own or its launch template's, so
// an update can return the ones it no longer declares to their launch defaults.
private static final String DECLARED_METADATA_OPTIONS_ATTR = "__FlociDeclaredMetadataOptions";
// The __FlociDeclared records as they stood before a replacing update, for rollbackUpdate to put
// back with the instance it restores; ReplacementCleanup leaves __Floci attributes alone.
private static final String PRIOR_DECLARATIONS_ATTR = "__FlociPriorDeclarations";
// What an update that kept the instance changed it from: its region, its MetadataOptions if the
// update changed them, its __FlociDeclared records, and whether the update also changed
// something with no rollback here (type, groups, user data, profile, tags), for rollbackUpdate
// to put back.
private static final String PRIOR_IN_PLACE_ATTR = "__FlociPriorInPlaceUpdate";
private static final String DECLARED_PREFIX = "__FlociDeclared";
private static final ObjectMapper MAPPER = new ObjectMapper();
private final Ec2Service ec2Service;
/** How long {@link #delete} waits for a terminated instance; package-visible so tests can shorten it. */
@@ -74,6 +91,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
// Only look one up when the property actually names a template. An Fn::If that selects
// AWS::NoValue resolves to an empty node here, which on AWS means the property is absent
// (launch without a template), so it must not turn into an InvalidLaunchTemplateId.NotFound.
LaunchTemplateData.MetadataOptions templateMetadataOptions = null;
if (ltRef != null && ltRef.isObject() && (ltId != null || ltName != null)) {
// A LaunchTemplate the stack references but that does not resolve is a real error, as on
// AWS: let it fail the resource rather than silently launching with default config.
@@ -88,7 +106,17 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
if (keyName == null || keyName.isBlank()) {
keyName = ltData.getKeyName();
}
templateMetadataOptions = ltData.getMetadataOptions();
}
// The instance's own MetadataOptions win member by member over its template's, as
// RunInstances merges a request over the launch template it names.
LaunchTemplateData.MetadataOptions metadataOptions = Ec2CfnMetadataOptions.over(templateMetadataOptions,
props != null ? Ec2CfnMetadataOptions.read("MetadataOptions", props.get("MetadataOptions"),
Ec2CfnMetadataOptions.INSTANCE_SHAPE, engine) : null);
// Checked before anything changes: a reused instance gets its options last, after its
// type, groups, user data, profile and tags, so a bad value found there would leave it half
// updated.
Ec2Service.validateMetadataOptions(metadataOptions);
if (instanceType == null || instanceType.isBlank()) {
instanceType = "t3.micro";
}
@@ -106,21 +134,41 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
// them), as does a changed PrivateIpAddress or AvailabilityZone (compared against the value
// declared last time, since the launch does not apply those to the instance). A mutable-only
// change (tags, and the like) reuses it. Launching unconditionally would leak the prior
// instance every update.
// instance every update. A changed LaunchTemplate reuses it too, where AWS replaces the
// instance: the change-set preview and the template's own versioning would have to agree on
// that property first. What the template declares is reconciled in place instead, unless
// the ImageId or KeyName it supplies changed, which replaces the instance as above.
Instance prior = ctx.isUpdate() ? findInstance(region, ctx.priorPhysicalId()) : null;
if (prior != null && !createOnlyChanged(prior, imageId, subnetId, keyName)
&& !declaredCreateOnlyChanged(attributesBefore, privateIpAddress, availabilityZone)) {
// A reused instance still has its mutable properties reconciled to the template rather
// than left at their prior values; re-read it so the published attributes reflect them.
reconcileMutableProperties(region, prior, instanceType, securityGroupIds, userData,
iamInstanceProfileArn, attributesBefore.get(DECLARED_IAM_PROFILE_ATTR));
LaunchTemplateData.MetadataOptions metadataOptionsToApply = Ec2CfnMetadataOptions.toApply(
Ec2CfnMetadataOptions.parseDeclaredMembers(attributesBefore.get(DECLARED_METADATA_OPTIONS_ATTR)),
metadataOptions);
LaunchTemplateData.MetadataOptions optionsBefore = prior.effectiveMetadataOptions();
boolean metadataOptionsChange = metadataOptionsToApply != null
&& Ec2CfnMetadataOptions.changes(optionsBefore, metadataOptionsToApply);
boolean otherChange = reconcileMutableProperties(region, prior, instanceType, securityGroupIds,
userData, iamInstanceProfileArn, attributesBefore.get(DECLARED_IAM_PROFILE_ATTR));
boolean tagsChanged = Ec2Tags.reconcile(ec2Service, region, prior.getInstanceId(), desiredTags);
// Saved on every update that keeps the instance, also one that changes no EC2 setting but
// only what is declared, so a rollback can always put the declarations back.
r.getAttributes().put(PRIOR_IN_PLACE_ATTR, priorInPlaceUpdate(region,
metadataOptionsChange ? optionsBefore : null, attributesBefore, otherChange || tagsChanged));
if (metadataOptionsChange) {
// The last change the step makes: when an earlier one fails, the engine restores the
// resource as it was, without the record saved above, so the options must not have
// changed yet.
ec2Service.modifyInstanceMetadataOptions(region, prior.getInstanceId(), metadataOptionsToApply);
}
Instance reconciled = findInstance(region, prior.getInstanceId());
Instance current = reconciled != null ? reconciled : prior;
r.setPhysicalId(current.getInstanceId());
publishInstanceAttributes(r, current);
storeDeclaredCreateOnly(r, privateIpAddress, availabilityZone);
putOrRemove(r, DECLARED_IAM_PROFILE_ATTR, iamInstanceProfileArn);
Ec2Tags.reconcile(ec2Service, region, current.getInstanceId(), desiredTags);
putOrRemove(r, DECLARED_METADATA_OPTIONS_ATTR, Ec2CfnMetadataOptions.declaredMembers(metadataOptions));
ReplacementCleanup.record(r, ctx, attributesBefore);
return;
}
@@ -138,9 +186,13 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
}
}
r.getAttributes().remove(PRIOR_IN_PLACE_ATTR);
if (ctx.isUpdate()) {
r.getAttributes().put(PRIOR_DECLARATIONS_ATTR, declarations(attributesBefore));
}
Reservation reservation = ec2Service.runInstances(region, imageId, instanceType, 1, 1, keyName,
securityGroupIds, subnetId, null, tags, userData, iamInstanceProfileArn,
associatePublicIp);
associatePublicIp, null, 0, null, metadataOptions);
Instance instance = reservation.getInstances().get(0);
r.setPhysicalId(instance.getInstanceId());
r.getAttributes().put("InstanceId", instance.getInstanceId());
@@ -153,6 +205,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
publishInstanceAttributes(r, launched != null ? launched : instance);
storeDeclaredCreateOnly(r, privateIpAddress, availabilityZone);
putOrRemove(r, DECLARED_IAM_PROFILE_ATTR, iamInstanceProfileArn);
putOrRemove(r, DECLARED_METADATA_OPTIONS_ATTR, Ec2CfnMetadataOptions.declaredMembers(metadataOptions));
// A createOnly change that landed a new instance id replaced the prior one: record it so
// the stack cleans the displaced instance up after the update commits.
ReplacementCleanup.record(r, ctx, attributesBefore);
@@ -216,22 +269,29 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
* "some interruptions" the property is documented with), and a changed IamInstanceProfile is
* associated or replaced, or disassociated when the template declared one last time and drops it
* now. Only a declared SecurityGroupIds or UserData is reconciled, so a template that omits them
* does not strip what the instance already has (a launch template may have set it).
* does not strip what the instance already has (a launch template may have set it). Returns
* whether it changed anything, which a stack rollback has no way to put back here. MetadataOptions
* is applied after it, as the property's "No interruption" update allows, by the caller, which
* keeps what it replaces for {@link #rollbackUpdate}.
*/
private void reconcileMutableProperties(String region, Instance prior, String instanceType,
List<String> securityGroupIds, String userData,
String iamInstanceProfileArn, String priorDeclaredProfileArn) {
private boolean reconcileMutableProperties(String region, Instance prior, String instanceType,
List<String> securityGroupIds, String userData,
String iamInstanceProfileArn, String priorDeclaredProfileArn) {
boolean changed = false;
if (instanceType != null && !instanceType.isBlank()
&& !instanceType.equals(prior.getInstanceType())) {
ec2Service.modifyInstanceAttribute(region, prior.getInstanceId(), "instanceType", instanceType);
changed = true;
}
if (!securityGroupIds.isEmpty() && !sameSecurityGroups(prior, securityGroupIds)) {
ec2Service.modifyInstanceGroups(region, prior.getInstanceId(), securityGroupIds);
changed = true;
}
if (userData != null && !userData.equals(prior.getUserData())) {
rewriteUserData(region, prior, userData);
changed = true;
}
reconcileIamInstanceProfile(region, prior, iamInstanceProfileArn, priorDeclaredProfileArn);
return reconcileIamInstanceProfile(region, prior, iamInstanceProfileArn, priorDeclaredProfileArn) || changed;
}
/**
@@ -253,19 +313,24 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
}
}
private void reconcileIamInstanceProfile(String region, Instance prior, String desiredArn,
String priorDeclaredArn) {
/** Returns whether it changed the instance's profile. */
private boolean reconcileIamInstanceProfile(String region, Instance prior, String desiredArn,
String priorDeclaredArn) {
String currentArn = prior.getIamInstanceProfileArn();
String associationId = Ec2Service.iamInstanceProfileAssociationId(prior.getInstanceId());
if (desiredArn != null) {
if (currentArn == null) {
ec2Service.associateIamInstanceProfile(region, prior.getInstanceId(), desiredArn);
return true;
} else if (!desiredArn.equals(currentArn)) {
ec2Service.replaceIamInstanceProfileAssociation(region, associationId, desiredArn);
return true;
}
} else if (priorDeclaredArn != null && currentArn != null) {
ec2Service.disassociateIamInstanceProfile(region, associationId);
return true;
}
return false;
}
private String resolveIamInstanceProfileArn(String nameOrArn) {
@@ -383,17 +448,138 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
@Override
public UpdateCleanupResult completeUpdate(StackResource resource) {
resource.getAttributes().remove(PRIOR_DECLARATIONS_ATTR);
resource.getAttributes().remove(PRIOR_IN_PLACE_ATTR);
return ReplacementCleanup.complete(resource, this::delete);
}
@Override
public void clearUpdate(StackResource resource) {
resource.getAttributes().remove(PRIOR_DECLARATIONS_ATTR);
resource.getAttributes().remove(PRIOR_IN_PLACE_ATTR);
ReplacementCleanup.clear(resource);
}
/**
* Undoes a replacement through the cleanup record, and puts back the {@code __FlociDeclared}
* records of the instance it restores, so a retried update compares against what that instance
* was declared with. The cleanup names the prior instance again before it deletes the
* replacement, so when that delete throws the records go back too: a rollback that then skips
* this resource, or is forced, never calls here again.
*/
@Override
public boolean rollbackUpdate(StackResource resource) {
return ReplacementCleanup.rollback(resource, this::delete);
String physicalIdBefore = resource.getPhysicalId();
boolean replaced;
try {
replaced = ReplacementCleanup.rollback(resource, this::delete);
} catch (RuntimeException e) {
if (!Objects.equals(physicalIdBefore, resource.getPhysicalId())) {
try {
restoreSavedDeclarations(resource);
} catch (RuntimeException restoreFailure) {
e.addSuppressed(restoreFailure);
}
}
throw e;
}
if (replaced) {
restoreSavedDeclarations(resource);
resource.getAttributes().remove(PRIOR_IN_PLACE_ATTR);
}
resource.getAttributes().remove(PRIOR_DECLARATIONS_ATTR);
return replaced || restoreInPlaceUpdate(resource);
}
/**
* Undoes an update that kept the instance: puts back the MetadataOptions it changed, if it
* changed any, and the instance's {@code __FlociDeclared} records, so a stack rollback leaves
* neither options nor declarations the stack no longer has. The rollback counts as done only
* when nothing else changed in that update: the instance type, groups, user data, profile and
* tags have no rollback here, and the stack says so for them. An update that changed no EC2
* setting at all, only what is declared, is undone in full.
*/
private boolean restoreInPlaceUpdate(StackResource resource) {
String saved = resource.getAttributes().get(PRIOR_IN_PLACE_ATTR);
if (saved == null) {
return false;
}
JsonNode prior;
try {
prior = MAPPER.readTree(saved);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the saved in-place update of " + resource.getLogicalId(), e);
}
JsonNode options = prior.path("options");
if (options.isObject()) {
LaunchTemplateData.MetadataOptions restored = new LaunchTemplateData.MetadataOptions();
restored.setHttpTokens(options.path("HttpTokens").asText(null));
restored.setHttpEndpoint(options.path("HttpEndpoint").asText(null));
restored.setHttpProtocolIpv6(options.path("HttpProtocolIpv6").asText(null));
restored.setInstanceMetadataTags(options.path("InstanceMetadataTags").asText(null));
if (options.path("HttpPutResponseHopLimit").isInt()) {
restored.setHttpPutResponseHopLimit(options.path("HttpPutResponseHopLimit").intValue());
}
ec2Service.modifyInstanceMetadataOptions(prior.path("region").asText(), resource.getPhysicalId(), restored);
}
resource.getAttributes().keySet().removeIf(key -> key.startsWith(DECLARED_PREFIX));
prior.path("declarations").fields()
.forEachRemaining(e -> resource.getAttributes().put(e.getKey(), e.getValue().asText()));
resource.getAttributes().remove(PRIOR_IN_PLACE_ATTR);
return !prior.path("otherChanges").asBoolean(true);
}
/**
* What {@link #restoreInPlaceUpdate} needs, as a JSON object: {@code options} is the instance's
* MetadataOptions before the update, or null when the update left them as they were.
*/
private static String priorInPlaceUpdate(String region, LaunchTemplateData.MetadataOptions options,
Map<String, String> attributesBefore, boolean otherChanges) {
ObjectNode saved = MAPPER.createObjectNode();
saved.put("region", region);
if (options != null) {
ObjectNode members = saved.putObject("options");
members.put("HttpTokens", options.getHttpTokens());
members.put("HttpPutResponseHopLimit", options.getHttpPutResponseHopLimit());
members.put("HttpEndpoint", options.getHttpEndpoint());
members.put("HttpProtocolIpv6", options.getHttpProtocolIpv6());
members.put("InstanceMetadataTags", options.getInstanceMetadataTags());
}
ObjectNode declared = saved.putObject("declarations");
attributesBefore.forEach((key, value) -> {
if (key.startsWith(DECLARED_PREFIX) && value != null) {
declared.put(key, value);
}
});
saved.put("otherChanges", otherChanges);
return saved.toString();
}
/** The {@code __FlociDeclared} attributes of {@code attributes}, as a JSON object. */
private static String declarations(Map<String, String> attributes) {
ObjectNode declared = MAPPER.createObjectNode();
attributes.forEach((key, value) -> {
if (key.startsWith(DECLARED_PREFIX) && value != null) {
declared.put(key, value);
}
});
return declared.toString();
}
/** Puts back the records {@link #declarations} saved, if any, and drops the saved copy. */
private static void restoreSavedDeclarations(StackResource resource) {
String saved = resource.getAttributes().remove(PRIOR_DECLARATIONS_ATTR);
if (saved == null) {
return;
}
JsonNode prior;
try {
prior = MAPPER.readTree(saved);
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the saved declarations of " + resource.getLogicalId(), e);
}
resource.getAttributes().keySet().removeIf(key -> key.startsWith(DECLARED_PREFIX));
prior.fields().forEachRemaining(e -> resource.getAttributes().put(e.getKey(), e.getValue().asText()));
}
/**
@@ -3,6 +3,7 @@ package io.github.hectorvent.floci.services.cloudformation.provisioners;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.github.hectorvent.floci.services.cloudformation.CloudFormationTemplateEngine;
import io.github.hectorvent.floci.services.cloudformation.model.StackResource;
import io.github.hectorvent.floci.services.ec2.Ec2Service;
import io.github.hectorvent.floci.services.ec2.Ec2UserDataDecoder;
@@ -64,6 +65,14 @@ public class Ec2LaunchTemplateCfnProvisioner implements CfnResourceProvisioner {
data.setEncodedUserData(encodedUserData);
data.setUserData(Ec2UserDataDecoder.decode(encodedUserData));
data.setIamInstanceProfile(iamInstanceProfile(node.path("IamInstanceProfile")));
// MetadataOptions is read as the template writes it: resolving turns AWS::NoValue into ""
// first, which the typed read would refuse for the block or the hop limit. A
// LaunchTemplateData that is absent or an intrinsic call carries no MetadataOptions member.
JsonNode written = ctx.engine().omitNoValue(props.get("LaunchTemplateData"));
JsonNode metadataOptions = written.isObject() && !CloudFormationTemplateEngine.callsIntrinsic(written)
? written.get("MetadataOptions") : null;
data.setMetadataOptions(Ec2CfnMetadataOptions.read("LaunchTemplateData/MetadataOptions",
metadataOptions, Ec2CfnMetadataOptions.LAUNCH_TEMPLATE_SHAPE, ctx.engine()));
if (node.has("SecurityGroupIds")) {
List<String> securityGroupIds = new ArrayList<>();
for (JsonNode securityGroup : node.get("SecurityGroupIds")) {
@@ -7,6 +7,7 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
/**
* Tag reconciliation shared by the EC2 provisioners ({@code Ec2InstanceCfnProvisioner},
@@ -42,12 +43,17 @@ final class Ec2Tags {
/**
* Brings a resource's tags to {@code desired}: removes the keys AWS currently has that the
* template no longer declares, then creates or overwrites the declared ones.
* template no longer declares, then creates or overwrites the declared ones. Returns whether the
* tags were anything other than {@code desired} before.
*/
static void reconcile(Ec2Service ec2Service, String region, String resourceId, Map<String, String> desired) {
static boolean reconcile(Ec2Service ec2Service, String region, String resourceId, Map<String, String> desired) {
List<Tag> add = validatedTags(desired);
Map<String, String> current = current(ec2Service, region, resourceId);
List<String> stale = ProvisionContext.staleTagKeys(current, desired);
boolean changed = !stale.isEmpty();
for (Tag tag : add) {
changed |= !current.containsKey(tag.getKey()) || !Objects.equals(tag.getValue(), current.get(tag.getKey()));
}
if (!stale.isEmpty()) {
List<Tag> remove = new ArrayList<>();
for (String key : stale) {
@@ -58,5 +64,6 @@ final class Ec2Tags {
if (!add.isEmpty()) {
ec2Service.createTags(region, List.of(resourceId), add);
}
return changed;
}
}
@@ -5119,7 +5119,7 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider, Resettab
return inst;
}
static void validateMetadataOptions(LaunchTemplateData.MetadataOptions options) {
public static void validateMetadataOptions(LaunchTemplateData.MetadataOptions options) {
if (options == null) {
return;
}
+845 -1
View File
@@ -2,11 +2,13 @@
"_source": {
"generator": "tools/aws/regen_cfn_property_types.py",
"schemas": "https://schema.cloudformation.us-east-1.amazonaws.com/CloudformationSchema.zip",
"retrieved": "2026-10-19",
"retrieved": "2026-10-20",
"note": "make cfn-property-types-verify checks the file against AWS."
},
"operations": {
"AWS::AutoScaling::LaunchConfiguration": "AWS::AutoScaling::LaunchConfiguration",
"AWS::EC2::Instance": "AWS::EC2::Instance",
"AWS::EC2::LaunchTemplate": "AWS::EC2::LaunchTemplate",
"AWS::ECS::TaskDefinition": "AWS::ECS::TaskDefinition",
"AWS::Events::Rule": "AWS::Events::Rule",
"AWS::Lambda::Function": "AWS::Lambda::Function",
@@ -85,6 +87,828 @@
"HttpEndpoint": "String"
}
},
"AWS::EC2::Instance": {
"type": "structure",
"members": {
"PrivateDnsName": "String",
"Volumes": "AWS::EC2::Instance.Volumes",
"PrivateIp": "String",
"EnclaveOptions": "AWS::EC2::Instance.EnclaveOptions",
"ImageId": "String",
"Tags": "AWS::EC2::Instance.Tags",
"AdditionalInfo": "String",
"HibernationOptions": "AWS::EC2::Instance.HibernationOptions",
"LicenseSpecifications": "AWS::EC2::Instance.LicenseSpecifications",
"MetadataOptions": "AWS::EC2::Instance/MetadataOptions",
"InstanceId": "String",
"CpuOptions": "AWS::EC2::Instance.CpuOptions",
"AvailabilityZone": "String",
"PrivateDnsNameOptions": "AWS::EC2::Instance/PrivateDnsNameOptions",
"HostId": "String",
"PublicDnsName": "String",
"SecurityGroupIds": "AWS::EC2::Instance.SecurityGroupIds",
"PlacementGroupName": "String",
"SsmAssociations": "AWS::EC2::Instance.SsmAssociations",
"VpcId": "String",
"State": "AWS::EC2::Instance/State",
"Affinity": "String",
"Tenancy": "String",
"SecurityGroups": "AWS::EC2::Instance.SecurityGroups",
"PrivateIpAddress": "String",
"UserData": "String",
"BlockDeviceMappings": "AWS::EC2::Instance.BlockDeviceMappings",
"IamInstanceProfile": "String",
"Ipv6Addresses": "AWS::EC2::Instance.Ipv6Addresses",
"KernelId": "String",
"SubnetId": "String",
"EbsOptimized": "Boolean",
"PropagateTagsToVolumeOnCreation": "Boolean",
"ElasticGpuSpecifications": "AWS::EC2::Instance.ElasticGpuSpecifications",
"ElasticInferenceAccelerators": "AWS::EC2::Instance.ElasticInferenceAccelerators",
"Ipv6AddressCount": "Integer",
"LaunchTemplate": "AWS::EC2::Instance/LaunchTemplateSpecification",
"NetworkInterfaces": "AWS::EC2::Instance.NetworkInterfaces",
"InstanceType": "String",
"Monitoring": "Boolean",
"PublicIp": "String",
"InstanceInitiatedShutdownBehavior": "String",
"HostResourceGroupArn": "String",
"DisableApiTermination": "Boolean",
"KeyName": "String",
"RamdiskId": "String",
"SourceDestCheck": "Boolean",
"CreditSpecification": "AWS::EC2::Instance.CreditSpecification"
}
},
"AWS::EC2::Instance.BlockDeviceMappings": {
"type": "list",
"member": "AWS::EC2::Instance/BlockDeviceMapping"
},
"AWS::EC2::Instance.CpuOptions": {
"type": "structure",
"members": {
"ThreadsPerCore": "Integer",
"CoreCount": "Integer"
}
},
"AWS::EC2::Instance.CreditSpecification": {
"type": "structure",
"members": {
"CPUCredits": "String"
}
},
"AWS::EC2::Instance.ElasticGpuSpecifications": {
"type": "list",
"member": "AWS::EC2::Instance/ElasticGpuSpecification"
},
"AWS::EC2::Instance.ElasticInferenceAccelerators": {
"type": "list",
"member": "AWS::EC2::Instance/ElasticInferenceAccelerator"
},
"AWS::EC2::Instance.EnclaveOptions": {
"type": "structure",
"members": {
"Enabled": "Boolean"
}
},
"AWS::EC2::Instance.HibernationOptions": {
"type": "structure",
"members": {
"Configured": "Boolean"
}
},
"AWS::EC2::Instance.Ipv6Addresses": {
"type": "list",
"member": "AWS::EC2::Instance/InstanceIpv6Address"
},
"AWS::EC2::Instance.LicenseSpecifications": {
"type": "list",
"member": "AWS::EC2::Instance/LicenseSpecification"
},
"AWS::EC2::Instance.NetworkInterfaces": {
"type": "list",
"member": "AWS::EC2::Instance/NetworkInterface"
},
"AWS::EC2::Instance.SecurityGroupIds": {
"type": "list",
"member": "String"
},
"AWS::EC2::Instance.SecurityGroups": {
"type": "list",
"member": "String"
},
"AWS::EC2::Instance.SsmAssociations": {
"type": "list",
"member": "AWS::EC2::Instance/SsmAssociation"
},
"AWS::EC2::Instance.Tags": {
"type": "list",
"member": "AWS::EC2::Instance/Tag"
},
"AWS::EC2::Instance.Volumes": {
"type": "list",
"member": "AWS::EC2::Instance/Volume"
},
"AWS::EC2::Instance/AssociationParameter": {
"type": "structure",
"members": {
"Value": "AWS::EC2::Instance/AssociationParameter.Value",
"Key": "String"
},
"required": [
"Value",
"Key"
]
},
"AWS::EC2::Instance/AssociationParameter.Value": {
"type": "list",
"member": "String"
},
"AWS::EC2::Instance/BlockDeviceMapping": {
"type": "structure",
"members": {
"Ebs": "AWS::EC2::Instance/Ebs",
"NoDevice": "Json",
"VirtualName": "String",
"DeviceName": "String"
},
"required": [
"DeviceName"
]
},
"AWS::EC2::Instance/Ebs": {
"type": "structure",
"members": {
"SnapshotId": "String",
"VolumeType": "String",
"KmsKeyId": "String",
"Encrypted": "Boolean",
"Iops": "Integer",
"VolumeSize": "Integer",
"DeleteOnTermination": "Boolean"
}
},
"AWS::EC2::Instance/ElasticGpuSpecification": {
"type": "structure",
"members": {
"Type": "String"
},
"required": [
"Type"
]
},
"AWS::EC2::Instance/ElasticInferenceAccelerator": {
"type": "structure",
"members": {
"Type": "String",
"Count": "Integer"
},
"required": [
"Type"
]
},
"AWS::EC2::Instance/EnaSrdSpecification": {
"type": "structure",
"members": {
"EnaSrdEnabled": "Boolean",
"EnaSrdUdpSpecification": "AWS::EC2::Instance/EnaSrdUdpSpecification"
}
},
"AWS::EC2::Instance/EnaSrdUdpSpecification": {
"type": "structure",
"members": {
"EnaSrdUdpEnabled": "Boolean"
}
},
"AWS::EC2::Instance/InstanceIpv6Address": {
"type": "structure",
"members": {
"Ipv6Address": "String"
},
"required": [
"Ipv6Address"
]
},
"AWS::EC2::Instance/LaunchTemplateSpecification": {
"type": "structure",
"members": {
"LaunchTemplateName": "String",
"Version": "String",
"LaunchTemplateId": "String"
}
},
"AWS::EC2::Instance/LicenseSpecification": {
"type": "structure",
"members": {
"LicenseConfigurationArn": "String"
},
"required": [
"LicenseConfigurationArn"
]
},
"AWS::EC2::Instance/MetadataOptions": {
"type": "structure",
"members": {
"HttpPutResponseHopLimit": "Integer",
"HttpProtocolIpv6": "String",
"HttpTokens": "String",
"InstanceMetadataTags": "String",
"HttpEndpoint": "String"
}
},
"AWS::EC2::Instance/NetworkInterface": {
"type": "structure",
"members": {
"Description": "String",
"PrivateIpAddress": "String",
"PrivateIpAddresses": "AWS::EC2::Instance/NetworkInterface.PrivateIpAddresses",
"SecondaryPrivateIpAddressCount": "Integer",
"DeviceIndex": "String",
"GroupSet": "AWS::EC2::Instance/NetworkInterface.GroupSet",
"Ipv6Addresses": "AWS::EC2::Instance/NetworkInterface.Ipv6Addresses",
"SubnetId": "String",
"AssociatePublicIpAddress": "Boolean",
"NetworkInterfaceId": "String",
"AssociateCarrierIpAddress": "Boolean",
"EnaSrdSpecification": "AWS::EC2::Instance/EnaSrdSpecification",
"Ipv6AddressCount": "Integer",
"DeleteOnTermination": "Boolean"
},
"required": [
"DeviceIndex"
]
},
"AWS::EC2::Instance/NetworkInterface.GroupSet": {
"type": "list",
"member": "String"
},
"AWS::EC2::Instance/NetworkInterface.Ipv6Addresses": {
"type": "list",
"member": "AWS::EC2::Instance/InstanceIpv6Address"
},
"AWS::EC2::Instance/NetworkInterface.PrivateIpAddresses": {
"type": "list",
"member": "AWS::EC2::Instance/PrivateIpAddressSpecification"
},
"AWS::EC2::Instance/PrivateDnsNameOptions": {
"type": "structure",
"members": {
"EnableResourceNameDnsARecord": "Boolean",
"HostnameType": "String",
"EnableResourceNameDnsAAAARecord": "Boolean"
}
},
"AWS::EC2::Instance/PrivateIpAddressSpecification": {
"type": "structure",
"members": {
"PrivateIpAddress": "String",
"Primary": "Boolean"
},
"required": [
"PrivateIpAddress",
"Primary"
]
},
"AWS::EC2::Instance/SsmAssociation": {
"type": "structure",
"members": {
"AssociationParameters": "AWS::EC2::Instance/SsmAssociation.AssociationParameters",
"DocumentName": "String"
},
"required": [
"DocumentName"
]
},
"AWS::EC2::Instance/SsmAssociation.AssociationParameters": {
"type": "list",
"member": "AWS::EC2::Instance/AssociationParameter"
},
"AWS::EC2::Instance/State": {
"type": "structure",
"members": {
"Code": "String",
"Name": "String"
}
},
"AWS::EC2::Instance/Tag": {
"type": "structure",
"members": {
"Value": "String",
"Key": "String"
},
"required": [
"Value",
"Key"
]
},
"AWS::EC2::Instance/Volume": {
"type": "structure",
"members": {
"VolumeId": "String",
"Device": "String"
},
"required": [
"VolumeId",
"Device"
]
},
"AWS::EC2::LaunchTemplate": {
"type": "structure",
"members": {
"LaunchTemplateName": "String",
"LaunchTemplateData": "AWS::EC2::LaunchTemplate/LaunchTemplateData",
"VersionDescription": "String",
"TagSpecifications": "AWS::EC2::LaunchTemplate.TagSpecifications",
"LatestVersionNumber": "String",
"LaunchTemplateId": "String",
"DefaultVersionNumber": "String"
},
"required": [
"LaunchTemplateData"
]
},
"AWS::EC2::LaunchTemplate.TagSpecifications": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/LaunchTemplateTagSpecification"
},
"AWS::EC2::LaunchTemplate/AcceleratorCount": {
"type": "structure",
"members": {
"Min": "Integer",
"Max": "Integer"
}
},
"AWS::EC2::LaunchTemplate/AcceleratorTotalMemoryMiB": {
"type": "structure",
"members": {
"Min": "Integer",
"Max": "Integer"
}
},
"AWS::EC2::LaunchTemplate/BaselineEbsBandwidthMbps": {
"type": "structure",
"members": {
"Min": "Integer",
"Max": "Integer"
}
},
"AWS::EC2::LaunchTemplate/BaselinePerformanceFactors": {
"type": "structure",
"members": {
"Cpu": "AWS::EC2::LaunchTemplate/Cpu"
}
},
"AWS::EC2::LaunchTemplate/BlockDeviceMapping": {
"type": "structure",
"members": {
"Ebs": "AWS::EC2::LaunchTemplate/Ebs",
"NoDevice": "String",
"VirtualName": "String",
"DeviceName": "String"
}
},
"AWS::EC2::LaunchTemplate/CapacityReservationSpecification": {
"type": "structure",
"members": {
"CapacityReservationPreference": "String",
"CapacityReservationTarget": "AWS::EC2::LaunchTemplate/CapacityReservationTarget"
}
},
"AWS::EC2::LaunchTemplate/CapacityReservationTarget": {
"type": "structure",
"members": {
"CapacityReservationResourceGroupArn": "String",
"CapacityReservationId": "String"
}
},
"AWS::EC2::LaunchTemplate/ConnectionTrackingSpecification": {
"type": "structure",
"members": {
"UdpTimeout": "Integer",
"TcpEstablishedTimeout": "Integer",
"UdpStreamTimeout": "Integer"
}
},
"AWS::EC2::LaunchTemplate/Cpu": {
"type": "structure",
"members": {
"References": "AWS::EC2::LaunchTemplate/References"
}
},
"AWS::EC2::LaunchTemplate/CpuOptions": {
"type": "structure",
"members": {
"ThreadsPerCore": "Integer",
"AmdSevSnp": "String",
"NestedVirtualization": "String",
"CoreCount": "Integer"
}
},
"AWS::EC2::LaunchTemplate/CreditSpecification": {
"type": "structure",
"members": {
"CpuCredits": "String"
}
},
"AWS::EC2::LaunchTemplate/Ebs": {
"type": "structure",
"members": {
"SnapshotId": "String",
"VolumeType": "String",
"KmsKeyId": "String",
"Encrypted": "Boolean",
"EbsCardIndex": "Integer",
"Throughput": "Integer",
"Iops": "Integer",
"VolumeInitializationRate": "Integer",
"VolumeSize": "Integer",
"DeleteOnTermination": "Boolean"
}
},
"AWS::EC2::LaunchTemplate/EnaSrdSpecification": {
"type": "structure",
"members": {
"EnaSrdEnabled": "Boolean",
"EnaSrdUdpSpecification": "AWS::EC2::LaunchTemplate/EnaSrdUdpSpecification"
}
},
"AWS::EC2::LaunchTemplate/EnaSrdUdpSpecification": {
"type": "structure",
"members": {
"EnaSrdUdpEnabled": "Boolean"
}
},
"AWS::EC2::LaunchTemplate/EnclaveOptions": {
"type": "structure",
"members": {
"Enabled": "Boolean"
}
},
"AWS::EC2::LaunchTemplate/HibernationOptions": {
"type": "structure",
"members": {
"Configured": "Boolean"
}
},
"AWS::EC2::LaunchTemplate/IamInstanceProfile": {
"type": "structure",
"members": {
"Arn": "String",
"Name": "String"
}
},
"AWS::EC2::LaunchTemplate/InstanceMarketOptions": {
"type": "structure",
"members": {
"SpotOptions": "AWS::EC2::LaunchTemplate/SpotOptions",
"MarketType": "String"
}
},
"AWS::EC2::LaunchTemplate/InstanceRequirements": {
"type": "structure",
"members": {
"InstanceGenerations": "AWS::EC2::LaunchTemplate/InstanceRequirements.InstanceGenerations",
"MemoryGiBPerVCpu": "AWS::EC2::LaunchTemplate/MemoryGiBPerVCpu",
"AcceleratorTypes": "AWS::EC2::LaunchTemplate/InstanceRequirements.AcceleratorTypes",
"VCpuCount": "AWS::EC2::LaunchTemplate/VCpuCount",
"AcceleratorManufacturers": "AWS::EC2::LaunchTemplate/InstanceRequirements.AcceleratorManufacturers",
"LocalStorage": "String",
"CpuManufacturers": "AWS::EC2::LaunchTemplate/InstanceRequirements.CpuManufacturers",
"BareMetal": "String",
"RequireHibernateSupport": "Boolean",
"MaxSpotPriceAsPercentageOfOptimalOnDemandPrice": "Integer",
"OnDemandMaxPricePercentageOverLowestPrice": "Integer",
"MemoryMiB": "AWS::EC2::LaunchTemplate/MemoryMiB",
"LocalStorageTypes": "AWS::EC2::LaunchTemplate/InstanceRequirements.LocalStorageTypes",
"NetworkInterfaceCount": "AWS::EC2::LaunchTemplate/NetworkInterfaceCount",
"ExcludedInstanceTypes": "AWS::EC2::LaunchTemplate/InstanceRequirements.ExcludedInstanceTypes",
"AllowedInstanceTypes": "AWS::EC2::LaunchTemplate/InstanceRequirements.AllowedInstanceTypes",
"AcceleratorCount": "AWS::EC2::LaunchTemplate/AcceleratorCount",
"NetworkBandwidthGbps": "AWS::EC2::LaunchTemplate/NetworkBandwidthGbps",
"BaselinePerformanceFactors": "AWS::EC2::LaunchTemplate/BaselinePerformanceFactors",
"SpotMaxPricePercentageOverLowestPrice": "Integer",
"BaselineEbsBandwidthMbps": "AWS::EC2::LaunchTemplate/BaselineEbsBandwidthMbps",
"AcceleratorNames": "AWS::EC2::LaunchTemplate/InstanceRequirements.AcceleratorNames",
"AcceleratorTotalMemoryMiB": "AWS::EC2::LaunchTemplate/AcceleratorTotalMemoryMiB",
"BurstablePerformance": "String",
"TotalLocalStorageGB": "AWS::EC2::LaunchTemplate/TotalLocalStorageGB"
}
},
"AWS::EC2::LaunchTemplate/InstanceRequirements.AcceleratorManufacturers": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/InstanceRequirements.AcceleratorNames": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/InstanceRequirements.AcceleratorTypes": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/InstanceRequirements.AllowedInstanceTypes": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/InstanceRequirements.CpuManufacturers": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/InstanceRequirements.ExcludedInstanceTypes": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/InstanceRequirements.InstanceGenerations": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/InstanceRequirements.LocalStorageTypes": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/Ipv4PrefixSpecification": {
"type": "structure",
"members": {
"Ipv4Prefix": "String"
}
},
"AWS::EC2::LaunchTemplate/Ipv6Add": {
"type": "structure",
"members": {
"Ipv6Address": "String"
}
},
"AWS::EC2::LaunchTemplate/Ipv6PrefixSpecification": {
"type": "structure",
"members": {
"Ipv6Prefix": "String"
}
},
"AWS::EC2::LaunchTemplate/LaunchTemplateData": {
"type": "structure",
"members": {
"SecurityGroups": "AWS::EC2::LaunchTemplate/LaunchTemplateData.SecurityGroups",
"TagSpecifications": "AWS::EC2::LaunchTemplate/LaunchTemplateData.TagSpecifications",
"NetworkPerformanceOptions": "AWS::EC2::LaunchTemplate/NetworkPerformanceOptions",
"UserData": "String",
"BlockDeviceMappings": "AWS::EC2::LaunchTemplate/LaunchTemplateData.BlockDeviceMappings",
"MaintenanceOptions": "AWS::EC2::LaunchTemplate/MaintenanceOptions",
"IamInstanceProfile": "AWS::EC2::LaunchTemplate/IamInstanceProfile",
"KernelId": "String",
"EbsOptimized": "Boolean",
"Placement": "AWS::EC2::LaunchTemplate/Placement",
"NetworkInterfaces": "AWS::EC2::LaunchTemplate/LaunchTemplateData.NetworkInterfaces",
"EnclaveOptions": "AWS::EC2::LaunchTemplate/EnclaveOptions",
"ImageId": "String",
"InstanceType": "String",
"Monitoring": "AWS::EC2::LaunchTemplate/Monitoring",
"HibernationOptions": "AWS::EC2::LaunchTemplate/HibernationOptions",
"MetadataOptions": "AWS::EC2::LaunchTemplate/MetadataOptions",
"LicenseSpecifications": "AWS::EC2::LaunchTemplate/LaunchTemplateData.LicenseSpecifications",
"InstanceInitiatedShutdownBehavior": "String",
"DisableApiStop": "Boolean",
"CpuOptions": "AWS::EC2::LaunchTemplate/CpuOptions",
"PrivateDnsNameOptions": "AWS::EC2::LaunchTemplate/PrivateDnsNameOptions",
"SecurityGroupIds": "AWS::EC2::LaunchTemplate/LaunchTemplateData.SecurityGroupIds",
"KeyName": "String",
"DisableApiTermination": "Boolean",
"InstanceMarketOptions": "AWS::EC2::LaunchTemplate/InstanceMarketOptions",
"InstanceRequirements": "AWS::EC2::LaunchTemplate/InstanceRequirements",
"RamDiskId": "String",
"CapacityReservationSpecification": "AWS::EC2::LaunchTemplate/CapacityReservationSpecification",
"CreditSpecification": "AWS::EC2::LaunchTemplate/CreditSpecification"
}
},
"AWS::EC2::LaunchTemplate/LaunchTemplateData.BlockDeviceMappings": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/BlockDeviceMapping"
},
"AWS::EC2::LaunchTemplate/LaunchTemplateData.LicenseSpecifications": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/LicenseSpecification"
},
"AWS::EC2::LaunchTemplate/LaunchTemplateData.NetworkInterfaces": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/NetworkInterface"
},
"AWS::EC2::LaunchTemplate/LaunchTemplateData.SecurityGroupIds": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/LaunchTemplateData.SecurityGroups": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/LaunchTemplateData.TagSpecifications": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/TagSpecification"
},
"AWS::EC2::LaunchTemplate/LaunchTemplateTagSpecification": {
"type": "structure",
"members": {
"ResourceType": "String",
"Tags": "AWS::EC2::LaunchTemplate/LaunchTemplateTagSpecification.Tags"
}
},
"AWS::EC2::LaunchTemplate/LaunchTemplateTagSpecification.Tags": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/Tag"
},
"AWS::EC2::LaunchTemplate/LicenseSpecification": {
"type": "structure",
"members": {
"LicenseConfigurationArn": "String"
}
},
"AWS::EC2::LaunchTemplate/MaintenanceOptions": {
"type": "structure",
"members": {
"AutoRecovery": "String"
}
},
"AWS::EC2::LaunchTemplate/MemoryGiBPerVCpu": {
"type": "structure",
"members": {
"Min": "Double",
"Max": "Double"
}
},
"AWS::EC2::LaunchTemplate/MemoryMiB": {
"type": "structure",
"members": {
"Min": "Integer",
"Max": "Integer"
}
},
"AWS::EC2::LaunchTemplate/MetadataOptions": {
"type": "structure",
"members": {
"HttpPutResponseHopLimit": "Integer",
"HttpTokens": "String",
"HttpProtocolIpv6": "String",
"InstanceMetadataTags": "String",
"HttpEndpoint": "String"
}
},
"AWS::EC2::LaunchTemplate/Monitoring": {
"type": "structure",
"members": {
"Enabled": "Boolean"
}
},
"AWS::EC2::LaunchTemplate/NetworkBandwidthGbps": {
"type": "structure",
"members": {
"Min": "Double",
"Max": "Double"
}
},
"AWS::EC2::LaunchTemplate/NetworkInterface": {
"type": "structure",
"members": {
"Description": "String",
"PrivateIpAddress": "String",
"PrivateIpAddresses": "AWS::EC2::LaunchTemplate/NetworkInterface.PrivateIpAddresses",
"SecondaryPrivateIpAddressCount": "Integer",
"Ipv6PrefixCount": "Integer",
"Ipv4Prefixes": "AWS::EC2::LaunchTemplate/NetworkInterface.Ipv4Prefixes",
"DeviceIndex": "Integer",
"PrimaryIpv6": "Boolean",
"Ipv4PrefixCount": "Integer",
"EnaQueueCount": "Integer",
"Ipv6Prefixes": "AWS::EC2::LaunchTemplate/NetworkInterface.Ipv6Prefixes",
"SubnetId": "String",
"Ipv6Addresses": "AWS::EC2::LaunchTemplate/NetworkInterface.Ipv6Addresses",
"AssociatePublicIpAddress": "Boolean",
"NetworkInterfaceId": "String",
"NetworkCardIndex": "Integer",
"InterfaceType": "String",
"AssociateCarrierIpAddress": "Boolean",
"EnaSrdSpecification": "AWS::EC2::LaunchTemplate/EnaSrdSpecification",
"Ipv6AddressCount": "Integer",
"Groups": "AWS::EC2::LaunchTemplate/NetworkInterface.Groups",
"DeleteOnTermination": "Boolean",
"ConnectionTrackingSpecification": "AWS::EC2::LaunchTemplate/ConnectionTrackingSpecification"
}
},
"AWS::EC2::LaunchTemplate/NetworkInterface.Groups": {
"type": "list",
"member": "String"
},
"AWS::EC2::LaunchTemplate/NetworkInterface.Ipv4Prefixes": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/Ipv4PrefixSpecification"
},
"AWS::EC2::LaunchTemplate/NetworkInterface.Ipv6Addresses": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/Ipv6Add"
},
"AWS::EC2::LaunchTemplate/NetworkInterface.Ipv6Prefixes": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/Ipv6PrefixSpecification"
},
"AWS::EC2::LaunchTemplate/NetworkInterface.PrivateIpAddresses": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/PrivateIpAdd"
},
"AWS::EC2::LaunchTemplate/NetworkInterfaceCount": {
"type": "structure",
"members": {
"Min": "Integer",
"Max": "Integer"
}
},
"AWS::EC2::LaunchTemplate/NetworkPerformanceOptions": {
"type": "structure",
"members": {
"BandwidthWeighting": "String"
}
},
"AWS::EC2::LaunchTemplate/Placement": {
"type": "structure",
"members": {
"GroupName": "String",
"Tenancy": "String",
"SpreadDomain": "String",
"PartitionNumber": "Integer",
"AvailabilityZone": "String",
"Affinity": "String",
"HostId": "String",
"HostResourceGroupArn": "String",
"GroupId": "String"
}
},
"AWS::EC2::LaunchTemplate/PrivateDnsNameOptions": {
"type": "structure",
"members": {
"EnableResourceNameDnsARecord": "Boolean",
"HostnameType": "String",
"EnableResourceNameDnsAAAARecord": "Boolean"
}
},
"AWS::EC2::LaunchTemplate/PrivateIpAdd": {
"type": "structure",
"members": {
"PrivateIpAddress": "String",
"Primary": "Boolean"
}
},
"AWS::EC2::LaunchTemplate/Reference": {
"type": "structure",
"members": {
"InstanceFamily": "String"
}
},
"AWS::EC2::LaunchTemplate/References": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/Reference"
},
"AWS::EC2::LaunchTemplate/SpotOptions": {
"type": "structure",
"members": {
"SpotInstanceType": "String",
"InstanceInterruptionBehavior": "String",
"MaxPrice": "String",
"BlockDurationMinutes": "Integer",
"ValidUntil": "String"
}
},
"AWS::EC2::LaunchTemplate/Tag": {
"type": "structure",
"members": {
"Value": "String",
"Key": "String"
},
"required": [
"Value",
"Key"
]
},
"AWS::EC2::LaunchTemplate/TagSpecification": {
"type": "structure",
"members": {
"ResourceType": "String",
"Tags": "AWS::EC2::LaunchTemplate/TagSpecification.Tags"
}
},
"AWS::EC2::LaunchTemplate/TagSpecification.Tags": {
"type": "list",
"member": "AWS::EC2::LaunchTemplate/Tag"
},
"AWS::EC2::LaunchTemplate/TotalLocalStorageGB": {
"type": "structure",
"members": {
"Min": "Double",
"Max": "Double"
}
},
"AWS::EC2::LaunchTemplate/VCpuCount": {
"type": "structure",
"members": {
"Min": "Integer",
"Max": "Integer"
}
},
"AWS::ECS::TaskDefinition": {
"type": "structure",
"members": {
@@ -467,6 +1291,16 @@
"ContainerPath": "String"
}
},
"AWS::ECS::TaskDefinition/NvidiaMpsAllocation": {
"type": "structure",
"members": {
"Memory": "Integer",
"MaxComputePercent": "Integer"
},
"required": [
"Memory"
]
},
"AWS::ECS::TaskDefinition/PortMapping": {
"type": "structure",
"members": {
@@ -503,6 +1337,7 @@
"type": "structure",
"members": {
"Type": "String",
"SharingStrategy": "AWS::ECS::TaskDefinition/SharingStrategy",
"Value": "String"
},
"required": [
@@ -551,6 +1386,15 @@
"ValueFrom"
]
},
"AWS::ECS::TaskDefinition/SharingStrategy": {
"type": "structure",
"members": {
"NvidiaMps": "AWS::ECS::TaskDefinition/NvidiaMpsAllocation"
},
"required": [
"NvidiaMps"
]
},
"AWS::ECS::TaskDefinition/SystemControl": {
"type": "structure",
"members": {
@@ -0,0 +1,560 @@
package io.github.hectorvent.floci.services.cloudformation;
import io.github.hectorvent.floci.testing.EnforcementFixtures;
import io.quarkus.test.junit.QuarkusTest;
import io.restassured.path.xml.XmlPath;
import io.restassured.specification.RequestSpecification;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
import java.util.UUID;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.containsString;
import static org.junit.jupiter.api.Assertions.assertEquals;
/**
* MetadataOptions declared through CloudFormation reach the instance: an AWS::EC2::LaunchTemplate
* stores them, an AWS::EC2::Instance launches with its template's options under its own, and an
* update changes them in place, as the property's "No interruption" update behavior says, and a
* rollback puts them back. A template with {@code HttpTokens: required} is what CDK's
* {@code requireImdsv2} generates; the instance then carries it as RunInstances or
* ModifyInstanceMetadataOptions would have set it.
*/
@QuarkusTest
class CloudFormationEc2MetadataOptionsIntegrationTest {
private static final String ACCOUNT = "468024680246";
private static final String REGION = "us-east-1";
private static final String INSTANCE = "DescribeInstancesResponse.reservationSet.item.instancesSet.item.";
@Test
void launchTemplateMetadataOptionsReachTheInstance() {
String stackName = "cfn-metadata-lt-" + UUID.randomUUID().toString().substring(0, 8);
String template = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateData": {
"ImageId": "ami-12345678",
"InstanceType": "t3.micro",
"MetadataOptions": {
"HttpTokens": "required",
"HttpPutResponseHopLimit": 2,
"InstanceMetadataTags": "enabled"
}
}
}
},
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
}
}
}
},
"Outputs": {
"InstanceId": {"Value": {"Ref": "Inst"}},
"TemplateId": {"Value": {"Ref": "Lt"}}
}
}
""";
try {
cfn("CreateStack", stackName, template);
XmlPath stack = describeStack(stackName, "CREATE_COMPLETE");
String instanceId = output(stack, "InstanceId");
XmlPath versions = ec2Request("DescribeLaunchTemplateVersions")
.formParam("LaunchTemplateId", output(stack, "TemplateId"))
.post("/").then().statusCode(200).extract().xmlPath();
String stored = "DescribeLaunchTemplateVersionsResponse.launchTemplateVersionSet.item"
+ ".launchTemplateData.metadataOptions.";
assertEquals("required", versions.getString(stored + "httpTokens"));
assertEquals("2", versions.getString(stored + "httpPutResponseHopLimit"));
assertEquals("enabled", versions.getString(stored + "instanceMetadataTags"));
XmlPath described = describeInstance(instanceId);
assertEquals("required", described.getString(INSTANCE + "metadataOptions.httpTokens"));
assertEquals("2", described.getString(INSTANCE + "metadataOptions.httpPutResponseHopLimit"));
assertEquals("enabled", described.getString(INSTANCE + "metadataOptions.instanceMetadataTags"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
@Test
void instanceMetadataOptionsOverrideItsTemplateAndUpdateInPlace() {
String stackName = "cfn-metadata-inst-" + UUID.randomUUID().toString().substring(0, 8);
String template = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateData": {
"ImageId": "ami-12345678",
"MetadataOptions": {"HttpTokens": "optional", "HttpPutResponseHopLimit": "3"}
}
}
},
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
},
"MetadataOptions": {"HttpTokens": "%s"}
}
}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""";
try {
cfn("CreateStack", stackName, template.formatted("required"));
String instanceId = output(describeStack(stackName, "CREATE_COMPLETE"), "InstanceId");
XmlPath created = describeInstance(instanceId);
assertEquals("required", created.getString(INSTANCE + "metadataOptions.httpTokens"));
assertEquals("3", created.getString(INSTANCE + "metadataOptions.httpPutResponseHopLimit"));
cfn("UpdateStack", stackName, template.formatted("optional"));
assertEquals(instanceId, output(describeStack(stackName, "UPDATE_COMPLETE"), "InstanceId"));
XmlPath updated = describeInstance(instanceId);
assertEquals("optional", updated.getString(INSTANCE + "metadataOptions.httpTokens"));
assertEquals("3", updated.getString(INSTANCE + "metadataOptions.httpPutResponseHopLimit"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
@Test
void optionsTheInstanceStopsDeclaringReturnToTheLaunchDefaults() {
String stackName = "cfn-metadata-unset-" + UUID.randomUUID().toString().substring(0, 8);
String declared = """
{
"Resources": {
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": "ami-12345678",
"MetadataOptions": {"HttpTokens": "required", "HttpPutResponseHopLimit": 2}
}
}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""";
String undeclared = """
{
"Resources": {
"Inst": {"Type": "AWS::EC2::Instance", "Properties": {"ImageId": "ami-12345678"}}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""";
try {
cfn("CreateStack", stackName, declared);
String instanceId = output(describeStack(stackName, "CREATE_COMPLETE"), "InstanceId");
cfn("UpdateStack", stackName, undeclared);
assertEquals(instanceId, output(describeStack(stackName, "UPDATE_COMPLETE"), "InstanceId"));
XmlPath updated = describeInstance(instanceId);
assertEquals("optional", updated.getString(INSTANCE + "metadataOptions.httpTokens"));
assertEquals("1", updated.getString(INSTANCE + "metadataOptions.httpPutResponseHopLimit"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
@Test
void removingTheLaunchTemplateKeepsTheInstanceAndResetsItsOptions() {
String stackName = "cfn-metadata-drop-" + UUID.randomUUID().toString().substring(0, 8);
String withTemplate = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateData": {"ImageId": "ami-12345678", "MetadataOptions": {"HttpTokens": "required"}}
}
},
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
}
}
}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""";
// What CDK's requireImdsv2 turned off produces: the template and the reference are gone.
// AWS replaces the instance, LaunchTemplate being createOnly; Floci keeps it and returns
// what the template set to the launch defaults.
String withoutTemplate = """
{
"Resources": {
"Inst": {"Type": "AWS::EC2::Instance", "Properties": {"ImageId": "ami-12345678"}}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""";
try {
cfn("CreateStack", stackName, withTemplate);
String instanceId = output(describeStack(stackName, "CREATE_COMPLETE"), "InstanceId");
assertEquals("required", describeInstance(instanceId).getString(INSTANCE + "metadataOptions.httpTokens"));
cfn("UpdateStack", stackName, withoutTemplate);
assertEquals(instanceId, output(describeStack(stackName, "UPDATE_COMPLETE"), "InstanceId"));
assertEquals("optional", describeInstance(instanceId).getString(INSTANCE + "metadataOptions.httpTokens"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
/**
* The instance names {@code Fn::GetAtt LatestVersionNumber}, so updating the template changes
* its LaunchTemplate property. AWS replaces the instance; Floci keeps it and applies what the
* new version declares, here no token requirement.
*/
@Test
void aNewVersionOfTheLaunchTemplateUpdatesTheInstanceInPlace() {
String stackName = "cfn-metadata-version-" + UUID.randomUUID().toString().substring(0, 8);
String template = """
{
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {"LaunchTemplateData": {"ImageId": "ami-12345678"%s}}
},
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {
"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"},
"Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}
}
}
}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""";
try {
cfn("CreateStack", stackName, template.formatted(", \"MetadataOptions\": {\"HttpTokens\": \"required\"}"));
String instanceId = output(describeStack(stackName, "CREATE_COMPLETE"), "InstanceId");
cfn("UpdateStack", stackName, template.formatted(""));
assertEquals(instanceId, output(describeStack(stackName, "UPDATE_COMPLETE"), "InstanceId"));
assertEquals("optional", describeInstance(instanceId).getString(INSTANCE + "metadataOptions.httpTokens"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
@Test
void invalidMetadataOptionsFailTheUpdateBeforeTheInstanceChanges() {
String stackName = "cfn-metadata-invalid-" + UUID.randomUUID().toString().substring(0, 8);
String template = """
{
"Resources": {
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": "ami-12345678",
"InstanceType": "%s",
"MetadataOptions": {"HttpTokens": "%s"}
}
}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""";
try {
cfn("CreateStack", stackName, template.formatted("t3.micro", "required"));
String instanceId = output(describeStack(stackName, "CREATE_COMPLETE"), "InstanceId");
cfn("UpdateStack", stackName, template.formatted("t3.small", "Required"));
describeStack(stackName, "UPDATE_ROLLBACK_COMPLETE");
XmlPath unchanged = describeInstance(instanceId);
assertEquals("t3.micro", unchanged.getString(INSTANCE + "instanceType"));
assertEquals("required", unchanged.getString(INSTANCE + "metadataOptions.httpTokens"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
/**
* An update that changes the instance's MetadataOptions in place, then fails on a later
* resource, rolls the instance back; the stack ends rolled back, not stuck. That holds both for
* an update that turns the token requirement off and for one that only declares the default
* the instance already has, which changes no EC2 setting. For that second row the options are
* {@code optional} either way; what tells a working rollback apart is the stack ending
* {@code UPDATE_ROLLBACK_COMPLETE} rather than {@code UPDATE_ROLLBACK_FAILED}.
*/
@ParameterizedTest
@CsvSource({"required,optional,required", "'',optional,optional"})
void aFailedUpdateRollsTheInstancesMetadataOptionsBack(String createdTokens, String updatedTokens,
String httpTokens) {
String stackName = "cfn-metadata-rollback-" + UUID.randomUUID().toString().substring(0, 8);
String createdOptions = createdTokens.isEmpty() ? ""
: ", \"MetadataOptions\": {\"HttpTokens\": \"" + createdTokens + "\"}";
String created = """
{
"Resources": {
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {"ImageId": "ami-12345678"%s}
}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""".formatted(createdOptions);
// The second instance names a launch template that does not exist, so it fails after Inst
// has been updated, which it depends on.
String failing = """
{
"Resources": {
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {"ImageId": "ami-12345678", "MetadataOptions": {"HttpTokens": "%s"}}
},
"Later": {
"Type": "AWS::EC2::Instance",
"DependsOn": "Inst",
"Properties": {"LaunchTemplate": {"LaunchTemplateId": "lt-0123456789abcdef0", "Version": "1"}}
}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""".formatted(updatedTokens);
try {
cfn("CreateStack", stackName, created);
String instanceId = output(describeStack(stackName, "CREATE_COMPLETE"), "InstanceId");
cfn("UpdateStack", stackName, failing);
describeStack(stackName, "UPDATE_ROLLBACK_COMPLETE");
assertEquals(httpTokens, describeInstance(instanceId).getString(INSTANCE + "metadataOptions.httpTokens"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
/**
* LaunchTemplateData given as an {@code Fn::If} keeps the MetadataOptions of the branch its
* condition chooses, as it keeps that branch's ImageId.
*/
@ParameterizedTest
@CsvSource({"true,required", "false,optional"})
void launchTemplateDataChosenByFnIfKeepsItsMetadataOptions(String require, String httpTokens) {
String stackName = "cfn-metadata-lt-if-" + UUID.randomUUID().toString().substring(0, 8);
String template = """
{
"Parameters": {"Require": {"Type": "String", "Default": "%s"}},
"Conditions": {"Requires": {"Fn::Equals": [{"Ref": "Require"}, "true"]}},
"Resources": {
"Lt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateData": {"Fn::If": ["Requires",
{"ImageId": "ami-12345678", "MetadataOptions": {"HttpTokens": "required"}},
{"ImageId": "ami-12345678"}]}
}
},
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {"LaunchTemplate": {"LaunchTemplateId": {"Ref": "Lt"}, "Version": "1"}}
}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""".formatted(require);
try {
cfn("CreateStack", stackName, template);
String instanceId = output(describeStack(stackName, "CREATE_COMPLETE"), "InstanceId");
assertEquals(httpTokens, describeInstance(instanceId).getString(INSTANCE + "metadataOptions.httpTokens"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
@Test
void intrinsicsAndNoValueResolveInsideMetadataOptions() {
String stackName = "cfn-metadata-intrinsic-" + UUID.randomUUID().toString().substring(0, 8);
String template = """
{
"Parameters": {"Tokens": {"Type": "String", "Default": "required"}},
"Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},
"Resources": {
"Inst": {
"Type": "AWS::EC2::Instance",
"Properties": {
"ImageId": "ami-12345678",
"MetadataOptions": {
"HttpTokens": {"Ref": "Tokens"},
"HttpPutResponseHopLimit": {"Fn::If": ["Never", 5, {"Ref": "AWS::NoValue"}]},
"HttpEndpoint": {"Fn::If": ["Never", "disabled", {"Ref": "AWS::NoValue"}]}
}
}
}
},
"Outputs": {"InstanceId": {"Value": {"Ref": "Inst"}}}
}
""";
try {
cfn("CreateStack", stackName, template);
XmlPath described = describeInstance(output(describeStack(stackName, "CREATE_COMPLETE"), "InstanceId"));
assertEquals("required", described.getString(INSTANCE + "metadataOptions.httpTokens"));
assertEquals("1", described.getString(INSTANCE + "metadataOptions.httpPutResponseHopLimit"));
assertEquals("enabled", described.getString(INSTANCE + "metadataOptions.httpEndpoint"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
/**
* The same holds inside a launch template's LaunchTemplateData, for a member and for the whole
* block: AWS::NoValue leaves it out rather than failing the template.
*/
@Test
void intrinsicsAndNoValueResolveInsideLaunchTemplateMetadataOptions() {
String stackName = "cfn-metadata-lt-intrinsic-" + UUID.randomUUID().toString().substring(0, 8);
String template = """
{
"Parameters": {"Tokens": {"Type": "String", "Default": "required"}},
"Conditions": {"Never": {"Fn::Equals": ["a", "b"]}},
"Resources": {
"MemberLt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateData": {
"ImageId": "ami-12345678",
"MetadataOptions": {
"HttpTokens": {"Ref": "Tokens"},
"HttpPutResponseHopLimit": {"Fn::If": ["Never", 5, {"Ref": "AWS::NoValue"}]}
}
}
}
},
"BlockLt": {
"Type": "AWS::EC2::LaunchTemplate",
"Properties": {
"LaunchTemplateData": {
"ImageId": "ami-12345678",
"MetadataOptions": {"Fn::If": ["Never", {"HttpTokens": "required"}, {"Ref": "AWS::NoValue"}]}
}
}
},
"MemberInst": {
"Type": "AWS::EC2::Instance",
"Properties": {"LaunchTemplate": {"LaunchTemplateId": {"Ref": "MemberLt"}, "Version": "1"}}
},
"BlockInst": {
"Type": "AWS::EC2::Instance",
"Properties": {"LaunchTemplate": {"LaunchTemplateId": {"Ref": "BlockLt"}, "Version": "1"}}
}
},
"Outputs": {
"MemberInstance": {"Value": {"Ref": "MemberInst"}},
"BlockInstance": {"Value": {"Ref": "BlockInst"}}
}
}
""";
try {
cfn("CreateStack", stackName, template);
XmlPath stack = describeStack(stackName, "CREATE_COMPLETE");
XmlPath member = describeInstance(output(stack, "MemberInstance"));
assertEquals("required", member.getString(INSTANCE + "metadataOptions.httpTokens"));
assertEquals("1", member.getString(INSTANCE + "metadataOptions.httpPutResponseHopLimit"));
assertEquals("optional",
describeInstance(output(stack, "BlockInstance")).getString(INSTANCE + "metadataOptions.httpTokens"));
} finally {
cfn("DeleteStack", stackName, null);
}
}
/**
* A MetadataOptions block or member of the wrong type fails the resource with CloudFormation's
* template validation error, on the instance and on the launch template alike. A list or object
* member must not read as absent: {@code HttpTokens: [required]} would otherwise launch an
* instance that still serves IMDSv1.
*/
@ParameterizedTest
@CsvSource(delimiter = '|', value = {
"Instance|{\"HttpTokens\": [\"required\"]}|Property [HttpTokens] expected type: String, found: JSONArray",
"Instance|{\"HttpTokens\": {\"Value\": \"required\"}}|Property [HttpTokens] expected type: String, found: JSONObject",
"Instance|\"required\"|Property [MetadataOptions] expected type: JSONObject, found: String",
"Instance|{\"HttpPutResponseHopLimit\": \"two\"}|Property [HttpPutResponseHopLimit] expected type: Integer, found: String",
"Instance|{\"HttpPutResponseHopLimit\": 4.5}|Property [HttpPutResponseHopLimit] expected type: Integer, found: Float",
"LaunchTemplate|{\"HttpTokens\": [\"required\"]}|Property [HttpTokens] expected type: String, found: JSONArray",
"LaunchTemplate|[\"required\"]|Property [MetadataOptions] expected type: JSONObject, found: JSONArray",
"LaunchTemplate|\"required\"|Property [MetadataOptions] expected type: JSONObject, found: String",
"LaunchTemplate|{\"HttpTokens\": {\"Value\": \"required\"}}|Property [HttpTokens] expected type: String, found: JSONObject",
"LaunchTemplate|{\"HttpPutResponseHopLimit\": \"two\"}|Property [HttpPutResponseHopLimit] expected type: Integer, found: String",
"LaunchTemplate|{\"HttpPutResponseHopLimit\": 4.5}|Property [HttpPutResponseHopLimit] expected type: Integer, found: Float"
})
void aMetadataOptionsValueOfTheWrongTypeFailsTheResource(String resource, String block, String message) {
String stackName = "cfn-metadata-type-" + UUID.randomUUID().toString().substring(0, 8);
String properties = "Instance".equals(resource)
? "{\"ImageId\": \"ami-12345678\", \"MetadataOptions\": " + block + "}"
: "{\"LaunchTemplateData\": {\"ImageId\": \"ami-12345678\", \"MetadataOptions\": " + block + "}}";
String template = "{\"Resources\": {\"R\": {\"Type\": \"AWS::EC2::" + resource + "\", \"Properties\": "
+ properties + "}}}";
try {
cfn("CreateStack", stackName, template);
describeStack(stackName, "ROLLBACK_COMPLETE");
cfnRequest("DescribeStackEvents").formParam("StackName", stackName)
.post("/").then().statusCode(200)
.body(containsString(message));
} finally {
cfn("DeleteStack", stackName, null);
}
}
private static void cfn(String action, String stackName, String template) {
RequestSpecification request = cfnRequest(action).formParam("StackName", stackName);
if (template != null) {
request.formParam("TemplateBody", template);
}
request.post("/").then().statusCode(200);
}
private static XmlPath describeStack(String stackName, String expectedStatus) {
return cfnRequest("DescribeStacks").formParam("StackName", stackName)
.post("/").then().statusCode(200)
.body(containsString("<StackStatus>" + expectedStatus + "</StackStatus>"))
.extract().xmlPath();
}
private static String output(XmlPath stack, String key) {
return stack.getString("DescribeStacksResponse.DescribeStacksResult.Stacks.member.Outputs.member"
+ ".find { it.OutputKey == '" + key + "' }.OutputValue");
}
private static XmlPath describeInstance(String instanceId) {
return ec2Request("DescribeInstances").formParam("InstanceId.1", instanceId)
.post("/").then().statusCode(200).extract().xmlPath();
}
private static RequestSpecification cfnRequest(String action) {
return request("cloudformation", action);
}
private static RequestSpecification ec2Request(String action) {
return request("ec2", action);
}
private static RequestSpecification request(String service, String action) {
return given().header("Authorization", EnforcementFixtures.auth(ACCOUNT, REGION, service))
.contentType("application/x-www-form-urlencoded").formParam("Action", action);
}
}
@@ -51,7 +51,7 @@ class CloudFormationEc2ProvisionerTest {
Reservation reservation = new Reservation();
reservation.getInstances().add(instance);
when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any())).thenReturn(reservation);
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation);
doThrow(new AwsException("InternalError", "EC2 instance i-launch-failed failed to launch because its container terminated during launch", 500))
.when(ec2Service).awaitContainerLaunch(instance);
@@ -73,7 +73,7 @@ class CloudFormationEc2ProvisionerTest {
Reservation reservation = new Reservation();
reservation.getInstances().add(instance);
when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any())).thenReturn(reservation);
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation);
doThrow(new AwsException("InternalError",
"EC2 instance i-launch-timed-out failed to launch because it did not reach running state before the launch timeout",
500)).when(ec2Service).awaitContainerLaunch(instance);
@@ -96,7 +96,7 @@ class CloudFormationEc2ProvisionerTest {
Reservation reservation = new Reservation();
reservation.getInstances().add(instance);
when(ec2Service.runInstances(anyString(), anyString(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any())).thenReturn(reservation);
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation);
StackResource resource = provisioner.provision("Server", "AWS::EC2::Instance", properties(), engine(),
"us-east-1", "000000000000", "test-stack");
@@ -22,10 +22,12 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
@@ -134,7 +136,7 @@ class Ec2InstanceCfnProvisionerTest {
"""), ctx());
verify(ec2).runInstances(eq("us-east-1"), eq("ami-from-template"), eq("m5.large"), eq(1), eq(1),
eq("template-key"), anyList(), any(), any(), anyList(), any(), any(), any());
eq("template-key"), anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
@Test
@@ -165,7 +167,7 @@ class Ec2InstanceCfnProvisionerTest {
assertEquals("i-nolt", r.getPhysicalId());
verify(ec2).runInstances(eq("us-east-1"), any(), eq("t3.micro"), eq(1), eq(1), any(),
anyList(), any(), any(), anyList(), any(), any(), any());
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
@Test
@@ -269,7 +271,7 @@ class Ec2InstanceCfnProvisionerTest {
assertEquals("i-1", r.getPhysicalId());
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
anyList(), any(), any(), anyList(), any(), any(), any());
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
@Test
@@ -378,7 +380,7 @@ class Ec2InstanceCfnProvisionerTest {
ArgumentCaptor<String> profile = ArgumentCaptor.forClass(String.class);
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), profile.capture(), any());
any(), any(), anyList(), any(), profile.capture(), any(), any(), anyInt(), any(), any());
assertEquals(PROFILE_A, profile.getValue());
assertEquals(PROFILE_A, r.getAttributes().get("__FlociDeclaredIamInstanceProfile"));
}
@@ -402,7 +404,7 @@ class Ec2InstanceCfnProvisionerTest {
i2.setInstanceId("i-2");
i2.setImageId("ami-2");
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any()))
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
.thenReturn(reservationOf(i1), reservationOf(i2));
StackResource r = resource("Server");
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx(null));
@@ -426,7 +428,7 @@ class Ec2InstanceCfnProvisionerTest {
i2.setInstanceId("i-2");
i2.setImageId("ami-1");
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any()))
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
.thenReturn(reservationOf(i1), reservationOf(i2));
StackResource r = resource("Server");
provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"PrivateIpAddress\": \"10.0.0.5\"}"), ctx(null));
@@ -450,7 +452,7 @@ class Ec2InstanceCfnProvisionerTest {
i2.setInstanceId("i-2");
i2.setImageId("ami-1");
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any()))
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
.thenReturn(reservationOf(i1), reservationOf(i2));
StackResource r = resource("Server");
provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"AvailabilityZone\": \"us-east-1a\"}"), ctx(null));
@@ -480,7 +482,7 @@ class Ec2InstanceCfnProvisionerTest {
assertEquals("i-1", r.getPhysicalId());
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
anyList(), any(), any(), anyList(), any(), any(), any());
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
@Test
@@ -500,7 +502,7 @@ class Ec2InstanceCfnProvisionerTest {
assertEquals("i-1", r.getPhysicalId());
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
anyList(), any(), any(), anyList(), any(), any(), any());
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
@Test
@@ -531,6 +533,513 @@ class Ec2InstanceCfnProvisionerTest {
assertEquals("old", removed.getValue().get(0).getKey());
}
@Test
void reusedInstanceModifiesOnlyAChangedMetadataOptions() throws Exception {
Instance i1 = new Instance();
i1.setInstanceId("i-1");
i1.setImageId("ami-1");
stubLaunch(i1);
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx(null));
ArgumentCaptor<LaunchTemplateData.MetadataOptions> launched =
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), launched.capture());
assertEquals("required", launched.getValue().getHttpTokens());
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults();
applied.setHttpTokens("required");
i1.setMetadataOptions(applied);
when(ec2.describeInstances("us-east-1", List.of("i-1"), null))
.thenReturn(List.of(reservationOf(i1)));
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx("i-1"));
verify(ec2, never()).modifyInstanceMetadataOptions(any(), any(), any());
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "optional"}}
"""), ctx("i-1"));
ArgumentCaptor<LaunchTemplateData.MetadataOptions> modified =
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), modified.capture());
assertEquals("optional", modified.getValue().getHttpTokens());
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
@Test
void reusedInstanceResetsMetadataOptionsTheTemplateNoLongerDeclares() throws Exception {
Instance i1 = new Instance();
i1.setInstanceId("i-1");
i1.setImageId("ami-1");
stubLaunch(i1);
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required", "HttpPutResponseHopLimit": 2}}
"""), ctx(null));
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults();
applied.setHttpTokens("required");
applied.setHttpPutResponseHopLimit(2);
i1.setMetadataOptions(applied);
when(ec2.describeInstances("us-east-1", List.of("i-1"), null))
.thenReturn(List.of(reservationOf(i1)));
// The instance dropped its MetadataOptions, so what it set last time goes back to the launch
// default, and what it never set is left alone.
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx("i-1"));
ArgumentCaptor<LaunchTemplateData.MetadataOptions> reset =
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), reset.capture());
assertEquals("optional", reset.getValue().getHttpTokens());
assertEquals(1, reset.getValue().getHttpPutResponseHopLimit());
assertNull(reset.getValue().getHttpEndpoint());
}
/**
* A changed LaunchTemplate keeps the instance, where AWS replaces it: what the new version
* declares is reconciled in place, here an HttpTokens the new version no longer sets.
*/
@Test
void changingTheInstancesLaunchTemplateKeepsItAndReconcilesWhatItDeclares() throws Exception {
LaunchTemplateData withTokens = new LaunchTemplateData();
withTokens.setImageId("ami-1");
LaunchTemplateData.MetadataOptions required = new LaunchTemplateData.MetadataOptions();
required.setHttpTokens("required");
withTokens.setMetadataOptions(required);
LaunchTemplateData withoutTokens = new LaunchTemplateData();
withoutTokens.setImageId("ami-1");
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, "1", false)).thenReturn(withTokens);
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-2", null, "2", false)).thenReturn(withoutTokens);
Instance i1 = stubLaunches("i-1", "i-2").get(0);
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"LaunchTemplate": {"LaunchTemplateId": "lt-1", "Version": "1"}}
"""), ctx(null));
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults();
applied.setHttpTokens("required");
i1.setMetadataOptions(applied);
provisioner.provision(r, props("""
{"LaunchTemplate": {"LaunchTemplateId": "lt-2", "Version": "2"}}
"""), ctx("i-1"));
assertEquals("i-1", r.getPhysicalId());
assertFalse(provisioner.hasReplacementUpdate(r));
ArgumentCaptor<LaunchTemplateData.MetadataOptions> reset =
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), reset.capture());
assertEquals("optional", reset.getValue().getHttpTokens());
verify(ec2, times(1)).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
/**
* The engine restores the prior instance when a later resource fails a replacing update; its
* records go back with it, so retrying the update decides from what that instance was declared
* with rather than from the attempt that was rolled back: the HttpTokens it declared and the
* retry drops returns to the launch default.
*/
@Test
void aRolledBackReplacementPutsBackTheRecordsOfTheInstanceItRestores() throws Exception {
List<Instance> instances = stubLaunches("i-1", "i-2");
StackResource r = launchRequiringTokensThenReplace(instances.get(0));
instances.get(1).setState(InstanceState.terminated());
provisioner.terminateTimeoutMillis = 20L;
assertTrue(provisioner.rollbackUpdate(r));
assertEquals("i-1", r.getPhysicalId());
assertEquals(Map.of("__FlociDeclaredMetadataOptions", "HttpTokens"), declarations(r));
assertFalse(r.getAttributes().containsKey("__FlociPriorDeclarations"));
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx("i-1"));
assertEquals("i-1", r.getPhysicalId());
ArgumentCaptor<LaunchTemplateData.MetadataOptions> reset =
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), reset.capture());
assertEquals("optional", reset.getValue().getHttpTokens());
}
/**
* A rollback whose delete of the replacement fails has already named the prior instance again,
* and a rollback that then skips the resource never calls back, so the records go back first.
*/
@Test
void aRollbackThatFailsToDeleteTheReplacementStillPutsBackTheRecords() throws Exception {
List<Instance> instances = stubLaunches("i-1", "i-2");
StackResource r = launchRequiringTokensThenReplace(instances.get(0));
doThrow(new AwsException("InternalError", "terminate failed", 500))
.when(ec2).terminateInstances("us-east-1", List.of("i-2"));
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertEquals("i-1", r.getPhysicalId());
assertEquals(Map.of("__FlociDeclaredMetadataOptions", "HttpTokens"), declarations(r));
assertFalse(r.getAttributes().containsKey("__FlociPriorDeclarations"));
}
/**
* A retried rollback goes through the delete it still owes: whether that delete fails again or
* succeeds, the prior instance keeps the records the first attempt put back.
*/
@Test
void aRetriedRollbackKeepsThePriorRecordsWhicheverWayTheDeleteGoes() throws Exception {
List<Instance> instances = stubLaunches("i-1", "i-2");
StackResource r = launchRequiringTokensThenReplace(instances.get(0));
when(ec2.terminateInstances("us-east-1", List.of("i-2")))
.thenThrow(new AwsException("InternalError", "terminate failed", 500))
.thenThrow(new AwsException("InternalError", "terminate failed", 500))
.thenReturn(List.of());
Map<String, String> declared = Map.of("__FlociDeclaredMetadataOptions", "HttpTokens");
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertEquals("i-1", r.getPhysicalId());
assertEquals(declared, declarations(r));
instances.get(1).setState(InstanceState.terminated());
provisioner.terminateTimeoutMillis = 20L;
assertTrue(provisioner.rollbackUpdate(r));
assertEquals("i-1", r.getPhysicalId());
assertEquals(declared, declarations(r));
assertFalse(r.getAttributes().containsKey("__FlociPriorDeclarations"));
}
/** A saved copy that cannot be read does not hide the delete failure the rollback reports. */
@Test
void anUnreadableSavedCopyDoesNotHideTheDeleteFailure() throws Exception {
List<Instance> instances = stubLaunches("i-1", "i-2");
StackResource r = launchRequiringTokensThenReplace(instances.get(0));
r.getAttributes().put("__FlociPriorDeclarations", "{not json");
AwsException deleteFailure = new AwsException("InternalError", "terminate failed", 500);
doThrow(deleteFailure).when(ec2).terminateInstances("us-east-1", List.of("i-2"));
AwsException thrown = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertEquals(deleteFailure, thrown);
assertEquals(1, thrown.getSuppressed().length);
assertTrue(thrown.getSuppressed()[0] instanceof IllegalStateException);
}
/**
* A launch template change keeps the instance only while what the template supplies to the
* createOnly ImageId stays the same; a new image replaces it, as a changed ImageId does.
*/
@Test
void aNewTemplateVersionWithAnotherImageStillReplacesTheInstance() throws Exception {
LaunchTemplateData first = new LaunchTemplateData();
first.setImageId("ami-1");
LaunchTemplateData second = new LaunchTemplateData();
second.setImageId("ami-2");
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, "1", false)).thenReturn(first);
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, "2", false)).thenReturn(second);
stubLaunches("i-1", "i-2");
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"LaunchTemplate": {"LaunchTemplateId": "lt-1", "Version": "1"}}
"""), ctx(null));
provisioner.provision(r, props("""
{"LaunchTemplate": {"LaunchTemplateId": "lt-1", "Version": "2"}}
"""), ctx("i-1"));
assertEquals("i-2", r.getPhysicalId());
assertTrue(provisioner.hasReplacementUpdate(r));
}
/**
* A stack update that changes only the instance's MetadataOptions in place, and then rolls back
* because a later resource failed, puts the options and their record back and reports the
* rollback done: otherwise the instance would keep options the stack no longer declares.
*/
@Test
void aRolledBackInPlaceUpdatePutsTheMetadataOptionsBack() throws Exception {
Instance i1 = launchRequiringTokens();
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx(null));
Map<String, String> declared = declarations(r);
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "optional", "HttpPutResponseHopLimit": 3}}
"""), ctx("i-1"));
assertTrue(provisioner.rollbackUpdate(r));
ArgumentCaptor<LaunchTemplateData.MetadataOptions> applied =
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
verify(ec2, times(2)).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), applied.capture());
assertEquals("optional", applied.getAllValues().get(0).getHttpTokens());
LaunchTemplateData.MetadataOptions restored = applied.getAllValues().get(1);
assertEquals("required", restored.getHttpTokens());
assertEquals(1, restored.getHttpPutResponseHopLimit());
assertEquals(i1.effectiveMetadataOptions().getHttpEndpoint(), restored.getHttpEndpoint());
assertEquals(declared, declarations(r));
assertFalse(r.getAttributes().containsKey("__FlociPriorInPlaceUpdate"));
}
/**
* When the same update also changed something CloudFormation cannot put back in place here
* (the instance type), the options still go back, and the rollback still reports that it could
* not undo the update.
*/
@Test
void aRolledBackUpdateWithOtherInPlaceChangesStillPutsTheMetadataOptionsBack() throws Exception {
Instance i1 = launchRequiringTokens();
i1.setInstanceType("t3.micro");
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "InstanceType": "t3.micro", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx(null));
provisioner.provision(r, props("""
{"ImageId": "ami-1", "InstanceType": "t3.large", "MetadataOptions": {"HttpTokens": "optional"}}
"""), ctx("i-1"));
assertFalse(provisioner.rollbackUpdate(r));
ArgumentCaptor<LaunchTemplateData.MetadataOptions> applied =
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
verify(ec2, times(2)).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), applied.capture());
assertEquals("required", applied.getAllValues().get(1).getHttpTokens());
assertFalse(r.getAttributes().containsKey("__FlociPriorInPlaceUpdate"));
}
/** A tag change in the same update has no rollback either, so the options go back and the rollback reports it. */
@Test
void aRolledBackUpdateThatAlsoChangedTagsPutsTheOptionsBackButReportsItUndone() throws Exception {
launchRequiringTokens();
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx(null));
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "optional"},
"Tags": [{"Key": "env", "Value": "prod"}]}
"""), ctx("i-1"));
assertFalse(provisioner.rollbackUpdate(r));
ArgumentCaptor<LaunchTemplateData.MetadataOptions> applied =
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
verify(ec2, times(2)).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), applied.capture());
assertEquals("required", applied.getAllValues().get(1).getHttpTokens());
}
/**
* An update that changes only the tags, which have no rollback here, still has its declarations
* put back, and the rollback reports that it could not undo the update; the options are untouched.
*/
@Test
void aRolledBackTagOnlyUpdatePutsTheRecordBackAndReportsItCouldNotUndoIt() throws Exception {
launchRequiringTokens();
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx(null));
Map<String, String> declared = declarations(r);
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required", "HttpPutResponseHopLimit": 1},
"Tags": [{"Key": "env", "Value": "prod"}]}
"""), ctx("i-1"));
assertFalse(provisioner.rollbackUpdate(r));
assertEquals(declared, declarations(r));
assertFalse(r.getAttributes().containsKey("__FlociPriorInPlaceUpdate"));
verify(ec2, never()).modifyInstanceMetadataOptions(any(), any(), any());
}
/**
* The options are the update's last change: when the tags fail first, the engine restores the
* resource without a saved copy, so the options must not have changed.
*/
@Test
void aTagFailureInAnInPlaceUpdateLeavesTheMetadataOptionsAlone() throws Exception {
launchRequiringTokens();
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx(null));
doThrow(new AwsException("InternalError", "tags failed", 500))
.when(ec2).createTags(eq("us-east-1"), eq(List.of("i-1")), anyList());
assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "optional"},
"Tags": [{"Key": "env", "Value": "prod"}]}
"""), ctx("i-1")));
verify(ec2, never()).modifyInstanceMetadataOptions(any(), any(), any());
}
/**
* An update that declares an option the instance already has changes no EC2 setting, only the
* declaration record. A rollback puts the record back and reports the update undone, without
* touching the instance.
*/
@Test
void aRolledBackUpdateThatOnlyDeclaresTheCurrentOptionsPutsTheRecordBack() throws Exception {
launchRequiringTokens();
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx(null));
Map<String, String> declared = declarations(r);
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required", "HttpPutResponseHopLimit": 1}}
"""), ctx("i-1"));
assertTrue(provisioner.rollbackUpdate(r));
assertEquals(declared, declarations(r));
assertFalse(r.getAttributes().containsKey("__FlociPriorInPlaceUpdate"));
verify(ec2, never()).modifyInstanceMetadataOptions(any(), any(), any());
}
/**
* A MetadataOptions member given as an empty string is a value, not an omission, and EC2 refuses
* it, as it refuses any value outside the allowed set.
*/
@Test
void aBlankMetadataOptionFailsBeforeTheInstanceLaunches() throws Exception {
StackResource r = resource("Server");
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": ""}}
"""), ctx(null)));
assertEquals("InvalidParameterValue", failure.getErrorCode());
verify(ec2, never()).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
@Test
void aCommittedOrClearedInPlaceUpdateDropsTheSavedRecord() throws Exception {
Instance i1 = launchRequiringTokens();
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx(null));
String optional = """
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "optional"}}
""";
provisioner.provision(r, props(optional), ctx("i-1"));
assertTrue(r.getAttributes().containsKey("__FlociPriorInPlaceUpdate"));
provisioner.completeUpdate(r);
assertFalse(r.getAttributes().containsKey("__FlociPriorInPlaceUpdate"));
i1.getMetadataOptions().setHttpTokens("optional");
provisioner.provision(r, props(optional.replace("optional", "required")), ctx("i-1"));
assertTrue(r.getAttributes().containsKey("__FlociPriorInPlaceUpdate"));
provisioner.clearUpdate(r);
assertFalse(r.getAttributes().containsKey("__FlociPriorInPlaceUpdate"));
}
/**
* One stubbed instance, i-1, of the default type, whose applied options require tokens, as a
* launch declaring them gives.
*/
private Instance launchRequiringTokens() {
Instance i1 = stubLaunches("i-1").get(0);
i1.setInstanceType("t3.micro");
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults();
applied.setHttpTokens("required");
i1.setMetadataOptions(applied);
return i1;
}
@Test
void aCommittedOrClearedReplacementDropsTheSavedRecords() throws Exception {
List<Instance> instances = stubLaunches("i-1", "i-2", "i-3", "i-4");
StackResource committed = launchRequiringTokensThenReplace(instances.get(0));
assertTrue(committed.getAttributes().containsKey("__FlociPriorDeclarations"));
instances.get(0).setState(InstanceState.terminated());
provisioner.terminateTimeoutMillis = 20L;
provisioner.completeUpdate(committed);
assertFalse(committed.getAttributes().containsKey("__FlociPriorDeclarations"));
StackResource cleared = launchRequiringTokensThenReplace(instances.get(2));
assertTrue(cleared.getAttributes().containsKey("__FlociPriorDeclarations"));
provisioner.clearUpdate(cleared);
assertFalse(cleared.getAttributes().containsKey("__FlociPriorDeclarations"));
}
/**
* Launches {@code first} declaring HttpTokens required, then replaces it with the next stubbed
* launch through an ImageId change that drops the MetadataOptions.
*/
private StackResource launchRequiringTokensThenReplace(Instance first) throws Exception {
StackResource r = resource("Server");
provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "required"}}
"""), ctx(null));
assertEquals(first.getInstanceId(), r.getPhysicalId());
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults();
applied.setHttpTokens("required");
first.setMetadataOptions(applied);
provisioner.provision(r, props("{\"ImageId\": \"ami-2\"}"), ctx(first.getInstanceId()));
assertTrue(provisioner.hasReplacementUpdate(r));
assertEquals(Map.of(), declarations(r));
return r;
}
/**
* With the same template and version (here {@code $Latest}) the instance is kept, and options
* its template stopped declaring go back to their launch defaults.
*/
@Test
void reusedInstanceResetsOptionsItsTemplateStopsDeclaring() throws Exception {
LaunchTemplateData withTokens = new LaunchTemplateData();
withTokens.setImageId("ami-1");
LaunchTemplateData.MetadataOptions required = new LaunchTemplateData.MetadataOptions();
required.setHttpTokens("required");
withTokens.setMetadataOptions(required);
LaunchTemplateData withoutTokens = new LaunchTemplateData();
withoutTokens.setImageId("ami-1");
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, "$Latest", false))
.thenReturn(withTokens, withoutTokens);
Instance i1 = stubLaunches("i-1").get(0);
StackResource r = resource("Server");
String template = """
{"LaunchTemplate": {"LaunchTemplateId": "lt-1", "Version": "$Latest"}}
""";
provisioner.provision(r, props(template), ctx(null));
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults();
applied.setHttpTokens("required");
i1.setMetadataOptions(applied);
provisioner.provision(r, props(template), ctx("i-1"));
assertEquals("i-1", r.getPhysicalId());
ArgumentCaptor<LaunchTemplateData.MetadataOptions> reset =
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), reset.capture());
assertEquals("optional", reset.getValue().getHttpTokens());
}
@Test
void invalidMetadataOptionsFailBeforeAReusedInstanceChanges() throws Exception {
StackResource r = resource("Server");
r.setPhysicalId("i-1");
r.getAttributes().put("InstanceId", "i-1");
Instance prior = new Instance();
prior.setInstanceId("i-1");
prior.setImageId("ami-1");
prior.setInstanceType("t3.micro");
when(ec2.describeInstances("us-east-1", List.of("i-1"), null))
.thenReturn(List.of(reservationOf(prior)));
AwsException failure = assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"ImageId": "ami-1", "InstanceType": "t3.large", "MetadataOptions": {"HttpTokens": "Required"}}
"""), ctx("i-1")));
assertEquals("InvalidParameterValue", failure.getErrorCode());
verifyNoInteractions(ec2);
}
@Test
void reservedUpdateTagsFailBeforeChangingTheInstanceOrItsTags() throws Exception {
StackResource r = resource("Server");
@@ -636,7 +1145,7 @@ class Ec2InstanceCfnProvisionerTest {
assertEquals("i-9", r.getPhysicalId());
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
anyList(), any(), any(), anyList(), any(), any(), any());
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
@Test
@@ -657,7 +1166,7 @@ class Ec2InstanceCfnProvisionerTest {
assertEquals("i-9", r.getPhysicalId());
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
anyList(), any(), any(), anyList(), any(), any(), any());
anyList(), any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any());
}
@Test
@@ -670,7 +1179,7 @@ class Ec2InstanceCfnProvisionerTest {
withoutPublicIp.setInstanceId("i-2");
withoutPublicIp.setImageId("ami-2");
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any()))
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
.thenReturn(reservationOf(withPublicIp), reservationOf(withoutPublicIp));
StackResource r = resource("Server");
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx(null));
@@ -690,6 +1199,31 @@ class Ec2InstanceCfnProvisionerTest {
return reservation;
}
/** The provisioner's records of what the template declared, by attribute name. */
private static Map<String, String> declarations(StackResource r) {
return r.getAttributes().entrySet().stream().filter(e -> e.getKey().startsWith("__FlociDeclared"))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
}
/** One launch per id, in order, each instance then found by DescribeInstances. */
private List<Instance> stubLaunches(String... instanceIds) {
List<Instance> instances = new ArrayList<>();
List<Reservation> reservations = new ArrayList<>();
for (String instanceId : instanceIds) {
Instance instance = new Instance();
instance.setInstanceId(instanceId);
instance.setImageId("ami-1");
instances.add(instance);
reservations.add(reservationOf(instance));
when(ec2.describeInstances("us-east-1", List.of(instanceId), null))
.thenReturn(List.of(reservationOf(instance)));
}
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any()))
.thenReturn(reservations.get(0), reservations.subList(1, reservations.size()).toArray(Reservation[]::new));
return instances;
}
private static Map<String, String> tagEntry(String resourceId, String key, String value) {
Map<String, String> entry = new HashMap<>();
entry.put("resourceId", resourceId);
@@ -702,7 +1236,7 @@ class Ec2InstanceCfnProvisionerTest {
Reservation reservation = new Reservation();
reservation.getInstances().add(instance);
when(ec2.runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), any(), any())).thenReturn(reservation);
any(), any(), anyList(), any(), any(), any(), any(), anyInt(), any(), any())).thenReturn(reservation);
}
private ProvisionContext ctx() {
@@ -716,6 +1250,7 @@ class Ec2InstanceCfnProvisionerTest {
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.omitNoValue(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
}
@@ -56,6 +56,7 @@ class Ec2LaunchTemplateCfnProvisionerTest {
return node == null ? null : node.asText();
});
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
when(engine.omitNoValue(any())).thenAnswer(inv -> inv.getArgument(0));
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack");
}
+7 -2
View File
@@ -50,8 +50,9 @@ ARCHIVE_URL = "https://schema.cloudformation.us-east-1.amazonaws.com/Cloudformat
FETCH_TIMEOUT_SECONDS = 60
# The resource types whose provisioners read their properties through CfnPropertyTypes.
RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::ECS::TaskDefinition", "AWS::Events::Rule",
"AWS::Lambda::Function", "AWS::Lambda::LayerVersion"]
RESOURCE_TYPES = ["AWS::AutoScaling::LaunchConfiguration", "AWS::EC2::Instance", "AWS::EC2::LaunchTemplate",
"AWS::ECS::TaskDefinition", "AWS::Events::Rule", "AWS::Lambda::Function",
"AWS::Lambda::LayerVersion"]
# The shared shape each scalar body is written as, inline; a definition keeps its own name.
SCALAR_SHAPES = {"string": "String", "integer": "Integer", "boolean": "Boolean", "double": "Double", "json": "Json"}
@@ -67,6 +68,10 @@ ANCHORS = {
("AWS::Lambda::Function/Environment", "Variables"): {"String"},
("AWS::Lambda::Function/EphemeralStorage", "Size"): "Integer",
("AWS::AutoScaling::LaunchConfiguration/MetadataOptions", "HttpPutResponseHopLimit"): "Integer",
("AWS::EC2::Instance/MetadataOptions", "HttpTokens"): "String",
("AWS::EC2::Instance/MetadataOptions", "HttpPutResponseHopLimit"): "Integer",
("AWS::EC2::LaunchTemplate/MetadataOptions", "HttpTokens"): "String",
("AWS::EC2::LaunchTemplate/MetadataOptions", "HttpPutResponseHopLimit"): "Integer",
("AWS::ECS::TaskDefinition/ContainerDefinition", "Memory"): "Integer",
("AWS::ECS::TaskDefinition/ContainerDefinition", "Essential"): "Boolean",
("AWS::ECS::TaskDefinition/KernelCapabilities", "Add"): ["String"],