fix(cloudformation): give an instance its launch template's instance profile (#7761)

An AWS::EC2::Instance that names a launch template took the template's
image, type, key and metadata options but never its IamInstanceProfile,
so describe-instances showed no profile. When the instance declares no
profile of its own, it now launches with the template's, resolved the
same way RunInstances resolves it. The instance's own profile still wins.

A stack update that moves the instance to a template version naming
another profile, or none, changes or removes the profile in place, and a
dropped LaunchTemplate removes the profile it supplied. A rollback of an
update that changed the profile, whether the instance or its template
declared it, now puts the previous profile back instead of ending
UPDATE_ROLLBACK_FAILED.

Part of #7603
This commit is contained in:
Suja Shaj authored and GitHub committed 2026-11-08 05:25:15 -04:00
1 parent a3a3efec32
commit e27a307622
8 files changed
+434 -109

No files matched your search

+1 -1
View File
@@ -738,7 +738,7 @@ an API key's `Expires`, a GraphQL API's `ApiType` and `Visibility`, a UNIT resol
a `NatGateway`'s `PrivateIpAddress`, a `PrefixList`'s `MaxEntries`, a `Stage`'s `StageName` and an
`Instance`'s `SecurityGroupIds`, `NetworkInterfaces` and `LaunchTemplate`. A dropped `LaunchTemplate` keeps
the instance, but the instance type and the `MetadataOptions` members the template supplied go back to
their defaults. A `Stage`'s dropped `StageVariables` become empty. An `Instance`'s dropped `UserData` is
their defaults, and the instance profile it supplied is disassociated. A `Stage`'s dropped `StageVariables` become empty. An `Instance`'s dropped `UserData` is
cleared: a running instance is stopped for the rewrite and started again, and a stopped one stays stopped.
An update that drops a `PrefixList`'s `AddressFamily` or `PrefixListName` fails. Create-only members are
not cleared either.
+3 -1
View File
@@ -199,7 +199,9 @@ 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.
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 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.
An `AWS::EC2::Instance` that declares no `IamInstanceProfile` launches with the profile of the launch template it names, as `RunInstances` does, and its own `IamInstanceProfile` wins when it declares one. A template profile that IAM does not know fails the instance with `InvalidParameterValue`. A stack update that moves the instance to a template version naming another profile, or none, changes or removes the instance's profile in place, the same way it applies the version's `MetadataOptions`, and a stack rollback puts the previous profile back, whether the instance declared it or its launch template did.
## Instance Metadata Service (IMDS)
@@ -44,8 +44,9 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
// an auto-assigned address. The __Floci prefix keeps them off the published Fn::GetAtt attributes.
private static final String DECLARED_PRIVATE_IP_ATTR = "__FlociDeclaredPrivateIpAddress";
private static final String DECLARED_AZ_ATTR = "__FlociDeclaredAvailabilityZone";
// 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).
// The instance profile declared last time, the instance's own or its launch template's, so an
// update that drops it can be told from one that never declared one (the profile may have been
// associated outside the stack).
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.
@@ -56,10 +57,10 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
// 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.
// What an update that kept the instance changed it from: its region, its MetadataOptions and its
// instance profile if the update changed them, its __FlociDeclared records, and whether the
// update also changed something with no rollback here (type, groups, user data, 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();
@@ -98,11 +99,11 @@ 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;
LaunchTemplateData ltData = 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.
LaunchTemplateData ltData = ec2Service.resolveLaunchTemplateData(region, ltId, ltName,
ltData = ec2Service.resolveLaunchTemplateData(region, ltId, ltName,
ltRef.path("Version").asText(null), false);
if (imageId == null || imageId.isBlank()) {
imageId = ltData.getImageId();
@@ -113,11 +114,11 @@ 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,
LaunchTemplateData.MetadataOptions metadataOptions = Ec2CfnMetadataOptions.over(
ltData != null ? ltData.getMetadataOptions() : null,
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
@@ -134,7 +135,12 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
String userData = ctx.resolveOptional(props, "UserData");
// The property names a profile; it is resolved to the ARN here, at provision time, as the
// RunInstances handler resolves IamInstanceProfile.Name, so an unknown name fails the resource.
// Without it the launch template's profile applies, as RunInstances falls back to the
// template's when the request names none.
String iamInstanceProfileArn = resolveIamInstanceProfileArn(ctx.resolveOptional(props, "IamInstanceProfile"));
if (iamInstanceProfileArn == null) {
iamInstanceProfileArn = ec2Service.iamInstanceProfileArn(ltData);
}
// On update, keep the existing instance unless a createOnly property changed: a changed
// ImageId, SubnetId or KeyName replaces it (compared against the instance, which carries
@@ -157,14 +163,21 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
boolean metadataOptionsChange = metadataOptionsToApply != null
&& Ec2CfnMetadataOptions.changes(optionsBefore, metadataOptionsToApply);
boolean otherChange = reconcileMutableProperties(region, prior, instanceType, securityGroupIds,
userData, ctx.droppedProperties(props).contains("UserData"), iamInstanceProfileArn,
attributesBefore.get(DECLARED_IAM_PROFILE_ATTR));
userData, ctx.droppedProperties(props).contains("UserData"));
boolean tagsChanged = Ec2Tags.reconcileOwned(ec2Service, region, prior.getInstanceId(),
Ec2Tags.ownedKeys(r, DECLARED_TAG_KEYS_ATTR, ctx), desiredTags);
// The profile and the options are the changes a rollback can undo, so they come after
// everything else: when an earlier step fails, the engine restores the resource without
// the record saved below, so neither may have changed yet. The options, checked up front,
// cannot fail once the profile has changed.
String profileBefore = prior.getIamInstanceProfileArn();
boolean profileChange = reconcileIamInstanceProfile(region, prior, iamInstanceProfileArn,
attributesBefore.get(DECLARED_IAM_PROFILE_ATTR));
// 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));
metadataOptionsChange ? optionsBefore : null, profileChange, profileBefore, 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
@@ -283,19 +296,17 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
* through the same Ec2Service calls the API actions use: a changed InstanceType is resized in
* place, a changed SecurityGroupIds set is reattached, a changed UserData is rewritten the way
* ModifyInstanceAttribute requires it (the instance stopped first and started again after, the
* "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); UserData the
* previous template declared and this one drops is cleared. 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}.
* "some interruptions" the property is documented with). Only a declared SecurityGroupIds or
* UserData is reconciled, so a template that omits them does not strip what the instance already
* has (it may have been set outside the stack); UserData the previous template declared and this
* one drops is cleared. Returns whether it changed anything, which a stack rollback has no way to
* put back here. The IamInstanceProfile and then the MetadataOptions are applied after it, as
* their "No interruption" updates allow, by the caller, which keeps what they replace for
* {@link #rollbackUpdate}.
*/
private boolean reconcileMutableProperties(String region, Instance prior, String instanceType,
List<String> securityGroupIds, String userData,
boolean userDataDropped, String iamInstanceProfileArn,
String priorDeclaredProfileArn) {
boolean userDataDropped) {
boolean changed = false;
if (instanceType != null && !instanceType.isBlank()
&& !instanceType.equals(prior.getInstanceType())) {
@@ -313,7 +324,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
rewriteUserData(region, prior, null);
changed = true;
}
return reconcileIamInstanceProfile(region, prior, iamInstanceProfileArn, priorDeclaredProfileArn) || changed;
return changed;
}
/**
@@ -335,7 +346,11 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
}
}
/** Returns whether it changed the instance's profile. */
/**
* Associates the profile {@code desiredArn}, or replaces the instance's with it. With none desired,
* disassociates the instance's profile only when {@code priorDeclaredArn} says the stack declared
* one last time, on the instance or its launch template. Returns whether it changed the profile.
*/
private boolean reconcileIamInstanceProfile(String region, Instance prior, String desiredArn,
String priorDeclaredArn) {
String currentArn = prior.getIamInstanceProfileArn();
@@ -514,10 +529,10 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
}
/**
* 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
* Undoes an update that kept the instance: puts back the MetadataOptions and the instance profile
* it changed, if it changed them, and the instance's {@code __FlociDeclared} records, so a stack
* rollback leaves neither settings 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 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.
*/
@@ -532,6 +547,11 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
} catch (JsonProcessingException e) {
throw new IllegalStateException("Could not read the saved in-place update of " + resource.getLogicalId(), e);
}
JsonNode profile = prior.path("profile");
if (profile.isObject()) {
restoreIamInstanceProfile(prior.path("region").asText(), resource.getPhysicalId(),
profile.path("arn").isTextual() ? profile.path("arn").asText() : null);
}
JsonNode options = prior.path("options");
if (options.isObject()) {
LaunchTemplateData.MetadataOptions restored = new LaunchTemplateData.MetadataOptions();
@@ -551,11 +571,28 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
return !prior.path("otherChanges").asBoolean(true);
}
/**
* Gives the instance back the profile {@code arnBefore}, or none when it is null. An instance gone
* since the update fails the rollback rather than reporting a profile it could not put back.
*/
private void restoreIamInstanceProfile(String region, String instanceId, String arnBefore) {
Instance current = findInstance(region, instanceId);
if (current == null) {
throw new AwsException("InvalidInstanceID.NotFound", "The instance ID '" + instanceId + "' does not exist",
400);
}
// The current profile counts as declared, so it is disassociated when there was none before.
reconcileIamInstanceProfile(region, current, arnBefore, current.getIamInstanceProfileArn());
}
/**
* 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.
* MetadataOptions before the update, or null when the update left them as they were, and
* {@code profile} holds the instance profile ARN before the update, null for none, only when the
* update changed it.
*/
private static String priorInPlaceUpdate(String region, LaunchTemplateData.MetadataOptions options,
boolean profileChanged, String profileBefore,
Map<String, String> attributesBefore, boolean otherChanges) {
ObjectNode saved = MAPPER.createObjectNode();
saved.put("region", region);
@@ -567,6 +604,9 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
members.put("HttpProtocolIpv6", options.getHttpProtocolIpv6());
members.put("InstanceMetadataTags", options.getInstanceMetadataTags());
}
if (profileChanged) {
saved.putObject("profile").put("arn", profileBefore);
}
ObjectNode declared = saved.putObject("declarations");
attributesBefore.forEach((key, value) -> {
if (key.startsWith(DECLARED_PREFIX) && value != null) {
@@ -3,10 +3,16 @@ package io.floci.aws.services.cloudformation;
import io.floci.aws.services.ec2.Ec2Service;
import io.floci.aws.services.ec2.model.Instance;
import io.floci.aws.services.ec2.model.Tag;
import io.floci.aws.testing.AwsTestClients;
import io.floci.aws.testing.CfnStackWaits;
import io.quarkus.test.junit.QuarkusTest;
import jakarta.inject.Inject;
import org.junit.jupiter.api.Test;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
import software.amazon.awssdk.services.cloudformation.model.Stack;
import software.amazon.awssdk.services.ec2.Ec2Client;
import software.amazon.awssdk.services.ec2.model.IamInstanceProfile;
import java.util.ArrayList;
import java.util.HashMap;
@@ -372,6 +378,74 @@ class CloudFormationEc2InstanceIntegrationTest {
assertEquals("running", instance.getState().getName());
}
@Test
void anInstanceTakesItsLaunchTemplatesInstanceProfileOnCreateUpdateAndRollback() {
String stackName = "cfn-ec2-lt-profile-" + Long.toString(System.nanoTime(), 36);
try (CloudFormationClient cloudFormation = AwsTestClients.create(CloudFormationClient.builder(), "test",
Region.of(REGION))) {
cloudFormation.createStack(request -> request.stackName(stackName)
.templateBody(launchTemplateProfileStack("First", false)));
try {
Stack created = CfnStackWaits.awaitStatus(cloudFormation, stackName, "CREATE_COMPLETE");
String instanceId = CfnStackWaits.output(created, "InstanceId");
assertInstanceProfile(instanceId, CfnStackWaits.output(created, "FirstArn"));
// A template version naming another profile gives the same instance that profile, a
// failed update puts it back, and a version naming none leaves the instance without one.
Stack changed = updateStack(cloudFormation, stackName, launchTemplateProfileStack("Second", false),
"UPDATE_COMPLETE");
assertEquals(instanceId, CfnStackWaits.output(changed, "InstanceId"));
assertInstanceProfile(instanceId, CfnStackWaits.output(changed, "SecondArn"));
Stack rolledBack = updateStack(cloudFormation, stackName, launchTemplateProfileStack("First", true),
"UPDATE_ROLLBACK_COMPLETE");
assertInstanceProfile(instanceId, CfnStackWaits.output(rolledBack, "SecondArn"));
Stack cleared = updateStack(cloudFormation, stackName, launchTemplateProfileStack(null, false),
"UPDATE_COMPLETE");
assertEquals(instanceId, CfnStackWaits.output(cleared, "InstanceId"));
assertInstanceProfile(instanceId, null);
} finally {
CfnStackWaits.deleteStack(stackName, CFN_AUTH);
}
}
}
private static Stack updateStack(CloudFormationClient cloudFormation, String stackName, String template,
String expectedStatus) {
cloudFormation.updateStack(request -> request.stackName(stackName).templateBody(template));
return CfnStackWaits.awaitStatus(cloudFormation, stackName, expectedStatus);
}
/**
* An instance launched from a launch template whose IamInstanceProfile names the stack's profile
* {@code profile}, First or Second, or no profile when it is null. With {@code laterFails}, a
* second instance that names a missing launch template fails after the first is updated.
*/
private static String launchTemplateProfileStack(String profile, boolean laterFails) {
String member = profile == null ? "" : """
, "IamInstanceProfile": {"Name": {"Ref": "%s"}}""".formatted(profile);
String later = !laterFails ? "" : """
,
"Later": {"Type": "AWS::EC2::Instance", "DependsOn": "Server", "Properties": {"LaunchTemplate": {
"LaunchTemplateId": "lt-0123456789abcdef0", "Version": "1"}}}""";
return """
{"Resources": {
"Role": {"Type": "AWS::IAM::Role", "Properties": {"AssumeRolePolicyDocument": {
"Version": "2012-10-17", "Statement": [{"Effect": "Allow",
"Principal": {"Service": "ec2.amazonaws.com"}, "Action": "sts:AssumeRole"}]}}},
"First": {"Type": "AWS::IAM::InstanceProfile", "Properties": {"Roles": [{"Ref": "Role"}]}},
"Second": {"Type": "AWS::IAM::InstanceProfile", "Properties": {"Roles": [{"Ref": "Role"}]}},
"Lt": {"Type": "AWS::EC2::LaunchTemplate", "Properties": {"LaunchTemplateData": {
"ImageId": "ami-12345678", "InstanceType": "t3.micro"%s}}},
"Server": {"Type": "AWS::EC2::Instance", "Properties": {"LaunchTemplate": {
"LaunchTemplateId": {"Ref": "Lt"}, "Version": {"Fn::GetAtt": ["Lt", "LatestVersionNumber"]}}}}%s
}, "Outputs": {
"InstanceId": {"Value": {"Ref": "Server"}},
"FirstArn": {"Value": {"Fn::GetAtt": ["First", "Arn"]}},
"SecondArn": {"Value": {"Fn::GetAtt": ["Second", "Arn"]}}
}}
""".formatted(member, later);
}
private static void assertUserData(String instanceId, String encoded) {
given()
.contentType("application/x-www-form-urlencoded")
@@ -383,15 +457,13 @@ class CloudFormationEc2InstanceIntegrationTest {
.body(containsString("<value>" + encoded + "</value>"));
}
/** DescribeInstances, through the SDK, reports the profile {@code arn} on the instance, or none when it is null. */
private static void assertInstanceProfile(String instanceId, String arn) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeIamInstanceProfileAssociations")
.formParam("Filter.1.Name", "instance-id")
.formParam("Filter.1.Value.1", instanceId)
.when().post("/").then().statusCode(200)
.body(containsString("<arn>" + arn + "</arn>"));
try (Ec2Client ec2Client = AwsTestClients.create(Ec2Client.builder(), "test", Region.of(REGION))) {
IamInstanceProfile profile = ec2Client.describeInstances(request -> request.instanceIds(instanceId))
.reservations().get(0).instances().get(0).iamInstanceProfile();
assertEquals(arn, profile == null ? null : profile.arn());
}
}
private static String createInstanceProfile(String name) {
@@ -277,8 +277,7 @@ class CloudFormationSesReceiptRuleIntegrationTest {
template.withObject("/Outputs").putObject("BucketName").putObject("Value").put("Ref", "Bucket");
cfn.createStack(r -> r.stackName(stackName).templateBody(template.toString()));
Stack created = CfnStackWaits.awaitStatus(cfn, stackName, "CREATE_COMPLETE");
String bucket = created.outputs().stream().filter(o -> "BucketName".equals(o.outputKey()))
.findFirst().orElseThrow().outputValue();
String bucket = CfnStackWaits.output(created, "BucketName");
ReceiptRule rule = ses.describeReceiptRule(ruleSet, "store", "us-east-1");
assertEquals("S3Action", rule.getActions().getFirst().getType());
assertEquals(bucket, rule.getActions().getFirst().property("BucketName"));
@@ -2,6 +2,7 @@ package io.floci.aws.services.cloudformation.provisioners;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import io.floci.aws.core.common.AwsException;
import io.floci.aws.services.cloudformation.CloudFormationTemplateEngine;
import io.floci.aws.services.cloudformation.model.StackResource;
@@ -159,11 +160,10 @@ class Ec2InstanceCfnProvisionerTest {
@Test
void launchTemplateFillsWhatThePropertiesLeaveUnset() throws Exception {
LaunchTemplateData data = new LaunchTemplateData();
LaunchTemplateData data = templateVersion("lt-1", "1");
data.setImageId("ami-from-template");
data.setInstanceType("m5.large");
data.setKeyName("template-key");
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, "1", false)).thenReturn(data);
Instance instance = new Instance();
instance.setInstanceId("i-2");
stubLaunch(instance);
@@ -443,6 +443,26 @@ class Ec2InstanceCfnProvisionerTest {
verify(ec2).modifyInstanceAttribute("us-east-1", "i-1", "instanceType", "t3.micro");
}
@Test
void droppingTheLaunchTemplateDisassociatesTheProfileItSupplied() throws Exception {
StackResource r = launchedWithTemplateProfile();
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"),
ctx("i-1", props("{\"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\", \"Version\": \"1\"}}")));
verifyProfileDisassociated();
}
@Test
void droppingTheIamInstanceProfileWhileTheLaunchTemplateSuppliesOneSwitchesToIt() throws Exception {
ObjectNode previous = fromTemplate("1", PROFILE_B).put("IamInstanceProfile", PROFILE_A);
StackResource r = launchedCarrying(previous, PROFILE_A);
provisioner.provision(r, fromTemplate("1", PROFILE_B), ctx("i-1", previous));
verifyProfileReplacedWith(PROFILE_B);
}
@Test
void droppingCreateOnlyAndLaunchOnlyPropertiesKeepsTheInstance() throws Exception {
Instance i1 = reusable("i-1");
@@ -481,9 +501,7 @@ class Ec2InstanceCfnProvisionerTest {
@Test
void droppingImageIdWhileTheLaunchTemplateSuppliesADifferentImageReplacesTheInstance() throws Exception {
LaunchTemplateData data = new LaunchTemplateData();
data.setImageId("ami-2");
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, null, false)).thenReturn(data);
templateVersion("lt-1", null).setImageId("ami-2");
stubLaunches("i-1", "i-2");
StackResource r = resource("Server");
String previous = "{\"ImageId\": \"ami-1\", \"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}";
@@ -502,9 +520,7 @@ class Ec2InstanceCfnProvisionerTest {
@Test
void droppingImageIdWhileTheLaunchTemplateSuppliesTheSameImageKeepsTheInstance() throws Exception {
LaunchTemplateData data = new LaunchTemplateData();
data.setImageId("ami-1");
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, null, false)).thenReturn(data);
templateVersion("lt-1", null);
reusable("i-1");
StackResource r = resource("Server");
@@ -520,10 +536,7 @@ class Ec2InstanceCfnProvisionerTest {
@Test
void droppingKeyNameWhileTheLaunchTemplateSuppliesADifferentKeyReplacesTheInstance() throws Exception {
LaunchTemplateData data = new LaunchTemplateData();
data.setImageId("ami-1");
data.setKeyName("key-2");
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, null, false)).thenReturn(data);
templateVersion("lt-1", null).setKeyName("key-2");
List<Instance> instances = stubLaunches("i-1", "i-2");
instances.get(0).setKeyName("key-1");
StackResource r = resource("Server");
@@ -541,10 +554,7 @@ class Ec2InstanceCfnProvisionerTest {
@Test
void droppingKeyNameWhileTheLaunchTemplateSuppliesTheSameKeyKeepsTheInstance() throws Exception {
LaunchTemplateData data = new LaunchTemplateData();
data.setImageId("ami-1");
data.setKeyName("key-1");
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, null, false)).thenReturn(data);
templateVersion("lt-1", null).setKeyName("key-1");
Instance i1 = reusable("i-1");
i1.setKeyName("key-1");
StackResource r = resource("Server");
@@ -560,12 +570,9 @@ class Ec2InstanceCfnProvisionerTest {
@Test
void droppingMetadataOptionsWhileTheLaunchTemplateSuppliesAMemberAppliesItsValueAndLaunchDefaultsToTheRest()
throws Exception {
LaunchTemplateData data = new LaunchTemplateData();
data.setImageId("ami-1");
LaunchTemplateData.MetadataOptions supplied = new LaunchTemplateData.MetadataOptions();
supplied.setHttpTokens("required");
data.setMetadataOptions(supplied);
when(ec2.resolveLaunchTemplateData("us-east-1", "lt-1", null, null, false)).thenReturn(data);
templateVersion("lt-1", null).setMetadataOptions(supplied);
Instance i1 = stubLaunches("i-1", "i-2").get(0);
StackResource r = resource("Server");
String previous = "{\"ImageId\": \"ami-1\", "
@@ -611,41 +618,36 @@ class Ec2InstanceCfnProvisionerTest {
provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"IamInstanceProfile\": \"web\"}"), ctx("i-1"));
verify(ec2).associateIamInstanceProfile("us-east-1", "i-1", PROFILE_A);
verifyProfileAssociated(PROFILE_A);
assertEquals(PROFILE_A, r.getAttributes().get("__FlociDeclaredIamInstanceProfile"));
assertFalse(r.getAttributes().containsKey("IamInstanceProfile"));
}
@Test
void changingTheIamInstanceProfileReplacesTheAssociation() throws Exception {
Instance i1 = reusable("i-1");
i1.setIamInstanceProfileArn(PROFILE_A);
reusableWithProfile("i-1", PROFILE_A);
provisioner.provision(resource("Server"),
props("{\"ImageId\": \"ami-1\", \"IamInstanceProfile\": \"" + PROFILE_B + "\"}"), ctx("i-1"));
provisioner.provision(resource("Server"), withOwnProfile(PROFILE_B), ctx("i-1"));
verify(ec2).replaceIamInstanceProfileAssociation("us-east-1",
Ec2Service.iamInstanceProfileAssociationId("i-1"), PROFILE_B);
verifyProfileReplacedWith(PROFILE_B);
verify(ec2, never()).associateIamInstanceProfile(anyString(), anyString(), anyString());
}
@Test
void droppingADeclaredIamInstanceProfileDisassociatesIt() throws Exception {
Instance i1 = reusable("i-1");
i1.setIamInstanceProfileArn(PROFILE_A);
reusableWithProfile("i-1", PROFILE_A);
StackResource r = resource("Server");
r.getAttributes().put("__FlociDeclaredIamInstanceProfile", PROFILE_A);
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"), ctx("i-1"));
verify(ec2).disassociateIamInstanceProfile("us-east-1", Ec2Service.iamInstanceProfileAssociationId("i-1"));
verifyProfileDisassociated();
assertFalse(r.getAttributes().containsKey("__FlociDeclaredIamInstanceProfile"));
}
@Test
void aProfileTheTemplateNeverDeclaredIsKeptWhenItStaysUndeclared() throws Exception {
Instance i1 = reusable("i-1");
i1.setIamInstanceProfileArn(PROFILE_A);
reusableWithProfile("i-1", PROFILE_A);
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\"}"), ctx("i-1"));
@@ -655,32 +657,249 @@ class Ec2InstanceCfnProvisionerTest {
@Test
void launchResolvesAProfileNameThroughIam() throws Exception {
Instance instance = new Instance();
instance.setInstanceId("i-1");
stubLaunch(instance);
when(ec2.resolveIamInstanceProfileName("web")).thenReturn(PROFILE_A);
StackResource r = resource("Server");
provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"IamInstanceProfile\": \"web\"}"), ctx());
StackResource r = launch(props("{\"ImageId\": \"ami-1\", \"IamInstanceProfile\": \"web\"}"));
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(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
assertEquals(PROFILE_A, profile.getValue());
assertLaunchedWithProfile(r, PROFILE_A);
}
@Test
void aLaunchTemplatesInstanceProfileAppliesWhenTheInstanceNamesNone() {
assertLaunchedWithProfile(launchedWithTemplateProfile(), PROFILE_A);
}
@Test
void theInstancesOwnInstanceProfileWinsOverItsLaunchTemplates() {
assertLaunchedWithProfile(launch(fromTemplate("1", PROFILE_B).put("IamInstanceProfile", PROFILE_A)), PROFILE_A);
// Left unresolved, as the RunInstances handler leaves it.
verify(ec2, never()).iamInstanceProfileArn(any());
}
@Test
void aTemplateProfileIamDoesNotKnowFailsTheInstance() {
JsonNode props = fromTemplate("1", PROFILE_A);
when(ec2.iamInstanceProfileArn(any())).thenThrow(
new AwsException("InvalidParameterValue", "Invalid IAM Instance Profile: " + PROFILE_A, 400));
AwsException e = assertThrows(AwsException.class, () -> launch(props));
assertEquals("InvalidParameterValue", e.getErrorCode());
}
@Test
void aNewTemplateVersionWithAnotherProfileReplacesTheAssociation() {
StackResource r = updatedFromTemplateProfile(fromTemplate("2", PROFILE_B));
verifyProfileReplacedWith(PROFILE_B);
assertEquals(PROFILE_B, r.getAttributes().get("__FlociDeclaredIamInstanceProfile"));
}
/** An instance launched before its template's profile was applied gets it on the next update. */
@Test
void anInstanceLaunchedWithoutItsTemplatesProfileGetsItOnTheNextUpdate() {
updatedOntoTemplateProfile();
verifyProfileAssociated(PROFILE_A);
}
@Test
void aNewTemplateVersionWithoutAProfileDisassociatesTheOldOne() {
StackResource r = updatedFromTemplateProfile(fromTemplate("2", null));
verifyProfileDisassociated();
assertFalse(r.getAttributes().containsKey("__FlociDeclaredIamInstanceProfile"));
}
/**
* The profile changes after the tags, so a tag failure, which the engine undoes without a
* rollback, leaves it as it was.
*/
@Test
void aTagFailureInAnInPlaceUpdateLeavesTheProfileAlone() {
StackResource r = launchedWithTemplateProfile();
ObjectNode update = fromTemplate("2", PROFILE_B);
update.putArray("Tags").addObject().put("Key", "env").put("Value", "prod");
failTagging();
assertThrows(AwsException.class, () -> provisioner.provision(r, update, ctx("i-1")));
verify(ec2, never()).replaceIamInstanceProfileAssociation(anyString(), anyString(), anyString());
}
@Test
void aRolledBackUpdatePutsBackTheProfileItReplaced() {
StackResource r = updatedFromTemplateProfile(fromTemplate("2", PROFILE_B));
assertTrue(rolledBack(r, PROFILE_B));
verifyProfileReplacedWith(PROFILE_A);
assertEquals(PROFILE_A, r.getAttributes().get("__FlociDeclaredIamInstanceProfile"));
}
/** An instance the update finds and keeps: same image as the template, no createOnly change. */
@Test
void aRolledBackUpdatePutsBackTheProfileItRemoved() {
assertTrue(rolledBack(updatedFromTemplateProfile(fromTemplate("2", null)), null));
verifyProfileAssociated(PROFILE_A);
}
@Test
void aRolledBackUpdateRemovesTheProfileItAdded() {
assertTrue(rolledBack(updatedOntoTemplateProfile(), PROFILE_A));
verifyProfileDisassociated();
}
@Test
void aRolledBackUpdatePutsBackAProfileTheInstanceDeclaredItself() {
StackResource r = launchedCarrying(withOwnProfile(PROFILE_A), PROFILE_A);
provisioner.provision(r, withOwnProfile(PROFILE_B), ctx("i-1"));
assertTrue(rolledBack(r, PROFILE_B));
verifyProfileReplacedWith(PROFILE_A);
}
/** A resize in the same update has no rollback, so the profile goes back and the rollback reports it undone. */
@Test
void aRolledBackUpdateThatAlsoResizedPutsTheProfileBackButReportsItUndone() {
StackResource r = updatedFromTemplateProfile(fromTemplate("2", PROFILE_B).put("InstanceType", "t3.large"));
assertFalse(rolledBack(r, PROFILE_B));
verifyProfileReplacedWith(PROFILE_A);
}
@Test
void aRollbackOfAnInstanceGoneSinceTheUpdateFails() {
StackResource r = updatedFromTemplateProfile(fromTemplate("2", PROFILE_B));
when(ec2.describeInstances("us-east-1", List.of("i-1"), null)).thenReturn(List.of());
AwsException e = assertThrows(AwsException.class, () -> provisioner.rollbackUpdate(r));
assertEquals("InvalidInstanceID.NotFound", e.getErrorCode());
}
/**
* An instance the update finds and keeps: same image as the template, no createOnly change, and
* the default type, so a template that declares none does not resize it.
*/
private Instance reusable(String instanceId) {
Instance instance = new Instance();
instance.setInstanceId(instanceId);
instance.setImageId("ami-1");
instance.setInstanceType("t3.micro");
when(ec2.describeInstances("us-east-1", List.of(instanceId), null))
.thenReturn(List.of(reservationOf(instance)));
return instance;
}
/** A reusable instance that already carries the instance profile {@code profileArn}. */
private void reusableWithProfile(String instanceId, String profileArn) {
reusable(instanceId).setIamInstanceProfileArn(profileArn);
}
/** Launches i-1 from {@code props}, as a stack create does. */
private StackResource launch(JsonNode props) {
stubLaunches("i-1");
StackResource r = resource("Server");
provisioner.provision(r, props, ctx());
return r;
}
/** Launches i-1 from {@code props}; the next update finds it carrying the profile {@code profileArn}. */
private StackResource launchedCarrying(JsonNode props, String profileArn) {
StackResource r = launch(props);
reusableWithProfile("i-1", profileArn);
return r;
}
/** An instance launched from version 1 of lt-1, which supplies PROFILE_A, as the next update finds it. */
private StackResource launchedWithTemplateProfile() {
return launchedCarrying(fromTemplate("1", PROFILE_A), PROFILE_A);
}
/** The instance {@link #launchedWithTemplateProfile} gives, updated to {@code update}. */
private StackResource updatedFromTemplateProfile(JsonNode update) {
StackResource r = launchedWithTemplateProfile();
provisioner.provision(r, update, ctx("i-1"));
return r;
}
/** A reusable instance with no profile, updated to version 1 of lt-1, which supplies PROFILE_A. */
private StackResource updatedOntoTemplateProfile() {
reusable("i-1");
StackResource r = resource("Server");
provisioner.provision(r, fromTemplate("1", PROFILE_A), ctx("i-1"));
return r;
}
/**
* Rolls back the last update of i-1, which left it carrying {@code profileAfter}; returns whether the
* rollback counted as done.
*/
private boolean rolledBack(StackResource r, String profileAfter) {
reusableWithProfile("i-1", profileAfter);
return provisioner.rollbackUpdate(r);
}
/** Properties declaring image ami-1 and the instance's own profile {@code profileArn}. */
private ObjectNode withOwnProfile(String profileArn) {
return mapper.createObjectNode().put("ImageId", "ami-1").put("IamInstanceProfile", profileArn);
}
/** Version {@code version} of launch template {@code launchTemplateId}, stubbed to supply image ami-1. */
private LaunchTemplateData templateVersion(String launchTemplateId, String version) {
LaunchTemplateData data = new LaunchTemplateData();
data.setImageId("ami-1");
when(ec2.resolveLaunchTemplateData("us-east-1", launchTemplateId, null, version, false)).thenReturn(data);
return data;
}
/**
* Properties naming version {@code version} of launch template lt-1, whose instance profile
* resolves to {@code profileArn}, or which has none when it is null.
*/
private ObjectNode fromTemplate(String version, String profileArn) {
when(ec2.iamInstanceProfileArn(templateVersion("lt-1", version))).thenReturn(profileArn);
ObjectNode props = mapper.createObjectNode();
props.putObject("LaunchTemplate").put("LaunchTemplateId", "lt-1").put("Version", version);
return props;
}
/** The profile of instance i-1 was replaced with {@code profileArn} through its association. */
private void verifyProfileReplacedWith(String profileArn) {
verify(ec2).replaceIamInstanceProfileAssociation("us-east-1",
Ec2Service.iamInstanceProfileAssociationId("i-1"), profileArn);
}
/** Makes an update's tagging of i-1 fail. */
private void failTagging() {
doThrow(new AwsException("InternalError", "tags failed", 500))
.when(ec2).createTags(eq("us-east-1"), eq(List.of("i-1")), anyList());
}
/** Instance i-1 was associated with the profile {@code profileArn}. */
private void verifyProfileAssociated(String profileArn) {
verify(ec2).associateIamInstanceProfile("us-east-1", "i-1", profileArn);
}
/** The profile of instance i-1 was disassociated. */
private void verifyProfileDisassociated() {
verify(ec2).disassociateIamInstanceProfile("us-east-1", Ec2Service.iamInstanceProfileAssociationId("i-1"));
}
/** The one launch was given {@code profileArn}, and the resource records it as declared. */
private void assertLaunchedWithProfile(StackResource r, String profileArn) {
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(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
assertEquals(profileArn, profile.getValue());
assertEquals(profileArn, r.getAttributes().get("__FlociDeclaredIamInstanceProfile"));
}
@Test
void changingImageIdReplacesTheInstanceAndRecordsTheCleanup() throws Exception {
Instance i1 = new Instance();
@@ -900,15 +1119,10 @@ class Ec2InstanceCfnProvisionerTest {
*/
@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);
templateVersion("lt-1", "1").setMetadataOptions(required);
templateVersion("lt-2", "2");
Instance i1 = stubLaunches("i-1", "i-2").get(0);
StackResource r = resource("Server");
provisioner.provision(r, props("""
@@ -1026,12 +1240,8 @@ class Ec2InstanceCfnProvisionerTest {
*/
@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);
templateVersion("lt-1", "1");
templateVersion("lt-1", "2").setImageId("ami-2");
stubLaunches("i-1", "i-2");
StackResource r = resource("Server");
provisioner.provision(r, props("""
@@ -1159,8 +1369,7 @@ class Ec2InstanceCfnProvisionerTest {
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());
failTagging();
assertThrows(AwsException.class, () -> provisioner.provision(r, props("""
{"ImageId": "ami-1", "MetadataOptions": {"HttpTokens": "optional"},
@@ -1289,15 +1498,9 @@ class Ec2InstanceCfnProvisionerTest {
*/
@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);
templateVersion("lt-1", "$Latest").setMetadataOptions(required);
Instance i1 = stubLaunches("i-1").get(0);
StackResource r = resource("Server");
String template = """
@@ -1307,6 +1510,7 @@ class Ec2InstanceCfnProvisionerTest {
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults();
applied.setHttpTokens("required");
i1.setMetadataOptions(applied);
templateVersion("lt-1", "$Latest");
provisioner.provision(r, props(template), ctx("i-1"));
@@ -139,6 +139,14 @@ public final class CfnStackWaits {
stack.stackStatusReason() == null ? "" : stack.stackStatusReason())));
}
/** The value of {@code stack}'s output {@code key}; fails when the stack has no such output. */
public static String output(Stack stack, String key) {
return stack.outputs().stream().filter(output -> key.equals(output.outputKey())).findFirst()
.orElseThrow(() -> new AssertionError(
"Stack " + stack.stackName() + " has no output " + key + ": " + stack.outputs()))
.outputValue();
}
private static boolean hasExpectedStatus(String stackName, String expectedStatus, StackState state) {
if (expectedStatus.equals(state.status())) {
return true;
@@ -68,11 +68,11 @@ AWS::AppSync::Resolver SyncConfig clear
AWS::AppSync::Resolver TypeName create-only
AWS::EC2::EIP Tags clear
AWS::EC2::Instance AvailabilityZone create-only a drop differs from the declared value, so the instance is replaced
AWS::EC2::Instance IamInstanceProfile clear the profile is disassociated
AWS::EC2::Instance IamInstanceProfile clear the profile is disassociated, unless a launch template still supplies one, which takes its place
AWS::EC2::Instance ImageId create-only a drop is read as no preference and the instance is kept, unless a launch template still supplies a different image, which replaces it
AWS::EC2::Instance InstanceType default:t3.micro when no launch template supplies a type
AWS::EC2::Instance KeyName create-only a drop is read as no preference and the instance is kept, unless a launch template still supplies a different key, which replaces it
AWS::EC2::Instance LaunchTemplate keep:the instance is kept, and the instance type and the MetadataOptions members the template supplied go back to their defaults
AWS::EC2::Instance LaunchTemplate keep:the instance is kept, the instance type and the MetadataOptions members the template supplied go back to their defaults, and the instance profile it supplied is disassociated
AWS::EC2::Instance MetadataOptions default:launch defaults, member by member a member the launch template still supplies takes the template's value
AWS::EC2::Instance NetworkInterfaces keep:read only when an instance launches
AWS::EC2::Instance PrivateIpAddress create-only a drop differs from the declared value, so the instance is replaced
1 AWS::ApiGatewayV2::Stage ApiId create-only a drop fails: the stage is not found
68 AWS::AppSync::Resolver TypeName create-only
69 AWS::EC2::EIP Tags clear
70 AWS::EC2::Instance AvailabilityZone create-only a drop differs from the declared value, so the instance is replaced
71 AWS::EC2::Instance IamInstanceProfile clear the profile is disassociated the profile is disassociated, unless a launch template still supplies one, which takes its place
72 AWS::EC2::Instance ImageId create-only a drop is read as no preference and the instance is kept, unless a launch template still supplies a different image, which replaces it
73 AWS::EC2::Instance InstanceType default:t3.micro when no launch template supplies a type
74 AWS::EC2::Instance KeyName create-only a drop is read as no preference and the instance is kept, unless a launch template still supplies a different key, which replaces it
75 AWS::EC2::Instance LaunchTemplate keep:the instance is kept, and the instance type and the MetadataOptions members the template supplied go back to their defaults keep:the instance is kept, the instance type and the MetadataOptions members the template supplied go back to their defaults, and the instance profile it supplied is disassociated
76 AWS::EC2::Instance MetadataOptions default:launch defaults, member by member a member the launch template still supplies takes the template's value
77 AWS::EC2::Instance NetworkInterfaces keep:read only when an instance launches
78 AWS::EC2::Instance PrivateIpAddress create-only a drop differs from the declared value, so the instance is replaced