fix(cloudformation): apply EC2 Instance UserData and IamInstanceProfile in place (#4206)

UpdateStack kept a reused AWS::EC2::Instance's prior UserData and
IamInstanceProfile because Ec2Service had no in-place path for either: the
provisioner reconciled only InstanceType and SecurityGroupIds. On AWS both are
mutable, UserData with the "some interruptions" of a stop and a start.

EC2 gains the three association actions, AssociateIamInstanceProfile,
ReplaceIamInstanceProfileAssociation and DisassociateIamInstanceProfile, with
botocore's wire names, all five members of the association including the
timestamp the instance now records, and the errors moto documents
(IncorrectState for a second association, InvalidAssociationID.NotFound for
an unknown id). ModifyInstanceAttribute accepts UserData.Value on a stopped
instance, answering IncorrectInstanceState otherwise, the order Terraform's
provider performs as stop, modify, start. The association id derivation moves
from the handler into Ec2Service so the provisioner can name an association.

Ec2InstanceCfnProvisioner rewrites a changed UserData across a stop and a
start (an already stopped instance stays stopped), resolves the profile name
to its ARN at provision time as the RunInstances handler does, associates or
replaces a changed profile, and disassociates one only when the template
declared it last time, recorded in a __Floci attribute so a profile a launch
template set is never stripped. A dropped UserData is left as it is, the same
rule SecurityGroupIds follows.

Tests: Ec2InstanceCfnProvisionerTest covers the stop/modify/start order, the
stopped case, associate, replace, disassociate and the undeclared-profile
guard; Ec2IamInstanceProfileAssociationIntegrationTest and
Ec2UserDataAttributeIntegrationTest pin the wire behaviour;
CloudFormationEc2InstanceIntegrationTest updates both properties on one
instance and reads them back through EC2.
This commit is contained in:
Hector Ventura authored and GitHub committed 2026-09-23 08:51:47 -04:00
1 parent 678b50f14b
commit 6fadba8d57
10 files changed
+649 -42

No files matched your search

@@ -36,6 +36,9 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
// __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).
private static final String DECLARED_IAM_PROFILE_ATTR = "__FlociDeclaredIamInstanceProfile";
private final Ec2Service ec2Service;
@@ -88,6 +91,10 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
List<String> securityGroupIds = resolveSecurityGroupIds(props, engine);
String privateIpAddress = ctx.resolveOptional(props, "PrivateIpAddress");
String availabilityZone = ctx.resolveOptional(props, "AvailabilityZone");
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.
String iamInstanceProfileArn = resolveIamInstanceProfileArn(ctx.resolveOptional(props, "IamInstanceProfile"));
// 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
@@ -100,20 +107,19 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
&& !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);
reconcileMutableProperties(region, prior, instanceType, securityGroupIds, userData,
iamInstanceProfileArn, attributesBefore.get(DECLARED_IAM_PROFILE_ATTR));
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(), ctx.resolveTags(props, "Tags"));
ReplacementCleanup.record(r, ctx, attributesBefore);
return;
}
String userData = ctx.resolveOptional(props, "UserData");
String iamInstanceProfile = ctx.resolveOptional(props, "IamInstanceProfile");
List<Tag> tags = new ArrayList<>();
JsonNode tagsNode = props != null ? engine.resolveNode(props.get("Tags")) : null;
if (tagsNode != null && tagsNode.isArray()) {
@@ -139,7 +145,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
}
Reservation reservation = ec2Service.runInstances(region, imageId, instanceType, 1, 1, keyName,
securityGroupIds, subnetId, null, tags, userData, iamInstanceProfile,
securityGroupIds, subnetId, null, tags, userData, iamInstanceProfileArn,
associatePublicIp);
Instance instance = reservation.getInstances().get(0);
r.setPhysicalId(instance.getInstanceId());
@@ -152,6 +158,7 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
Instance launched = findInstance(region, instance.getInstanceId());
publishInstanceAttributes(r, launched != null ? launched : instance);
storeDeclaredCreateOnly(r, privateIpAddress, availabilityZone);
putOrRemove(r, DECLARED_IAM_PROFILE_ATTR, iamInstanceProfileArn);
// 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);
@@ -208,15 +215,18 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
}
/**
* Applies the mutable properties CloudFormation allows to change without replacing the instance:
* a changed InstanceType is resized in place and a changed SecurityGroupIds set is reattached,
* through the same Ec2Service calls the ModifyInstanceAttribute API uses. Only a declared
* SecurityGroupIds is reconciled, so a template that omits it does not strip the groups the
* instance already has. UserData and IamInstanceProfile have no in-place Ec2Service path yet, so
* they stay a follow-up: an instance kept on update still carries their prior values.
* Applies the mutable properties CloudFormation allows to change without replacing the instance,
* 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).
*/
private void reconcileMutableProperties(String region, Instance prior, String instanceType,
List<String> securityGroupIds) {
List<String> securityGroupIds, String userData,
String iamInstanceProfileArn, String priorDeclaredProfileArn) {
if (instanceType != null && !instanceType.isBlank()
&& !instanceType.equals(prior.getInstanceType())) {
ec2Service.modifyInstanceAttribute(region, prior.getInstanceId(), "instanceType", instanceType);
@@ -224,6 +234,51 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
if (!securityGroupIds.isEmpty() && !sameSecurityGroups(prior, securityGroupIds)) {
ec2Service.modifyInstanceGroups(region, prior.getInstanceId(), securityGroupIds);
}
if (userData != null && !userData.equals(prior.getUserData())) {
rewriteUserData(region, prior, userData);
}
reconcileIamInstanceProfile(region, prior, iamInstanceProfileArn, priorDeclaredProfileArn);
}
/**
* User data can only be modified on a stopped instance, so a running one is stopped for the
* rewrite and started again after it, as CloudFormation's "some interruptions" update does; an
* instance that was already stopped is left stopped.
*/
private void rewriteUserData(String region, Instance prior, String userData) {
String instanceId = prior.getInstanceId();
boolean wasStopped = prior.getState() != null && "stopped".equals(prior.getState().getName());
if (!wasStopped) {
ec2Service.stopInstances(region, List.of(instanceId));
}
ec2Service.modifyInstanceUserData(region, instanceId, userData);
if (!wasStopped) {
ec2Service.startInstances(region, List.of(instanceId));
Instance started = findInstance(region, instanceId);
ec2Service.awaitContainerLaunch(started != null ? started : prior);
}
}
private void 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);
} else if (!desiredArn.equals(currentArn)) {
ec2Service.replaceIamInstanceProfileAssociation(region, associationId, desiredArn);
}
} else if (priorDeclaredArn != null && currentArn != null) {
ec2Service.disassociateIamInstanceProfile(region, associationId);
}
}
private String resolveIamInstanceProfileArn(String nameOrArn) {
if (nameOrArn == null || nameOrArn.isBlank()) {
return null;
}
return nameOrArn.startsWith("arn:") ? nameOrArn : ec2Service.resolveIamInstanceProfileName(nameOrArn);
}
private static boolean sameSecurityGroups(Instance prior, List<String> desired) {
@@ -67,6 +67,10 @@ public class Ec2QueryHandler {
case "DescribeInstances" -> handleDescribeInstances(params, region);
case "DescribeIamInstanceProfileAssociations" ->
handleDescribeIamInstanceProfileAssociations(params, region);
case "AssociateIamInstanceProfile" -> handleAssociateIamInstanceProfile(params, region);
case "ReplaceIamInstanceProfileAssociation" ->
handleReplaceIamInstanceProfileAssociation(params, region);
case "DisassociateIamInstanceProfile" -> handleDisassociateIamInstanceProfile(params, region);
case "TerminateInstances" -> handleTerminateInstances(params, region);
case "StartInstances" -> handleStartInstances(params, region);
case "StopInstances" -> handleStopInstances(params, region);
@@ -1131,7 +1135,7 @@ public class Ec2QueryHandler {
if (inst.getIamInstanceProfileArn() == null) {
continue;
}
String assocId = iamInstanceProfileAssociationId(inst.getInstanceId());
String assocId = Ec2Service.iamInstanceProfileAssociationId(inst.getInstanceId());
if (instanceFilter != null && !instanceFilter.contains(inst.getInstanceId())) {
continue;
}
@@ -1143,10 +1147,13 @@ public class Ec2QueryHandler {
.elem("instanceId", inst.getInstanceId())
.start("iamInstanceProfile")
.elem("arn", inst.getIamInstanceProfileArn())
.elem("id", iamInstanceProfileId(inst.getInstanceId()))
.elem("id", Ec2Service.iamInstanceProfileId(inst.getInstanceId()))
.end("iamInstanceProfile")
.elem("state", "associated")
.end("item");
.elem("state", "associated");
if (inst.getIamInstanceProfileAssociationTime() != null) {
xml.elem("timestamp", ISO_FMT.format(inst.getIamInstanceProfileAssociationTime()));
}
xml.end("item");
}
}
xml.end("iamInstanceProfileAssociationSet")
@@ -1154,31 +1161,60 @@ public class Ec2QueryHandler {
return xmlResponse(xml.build());
}
/**
* Deterministic instance-profile id derived from the instance id so repeated describes are stable.
*/
private static String iamInstanceProfileId(String instanceId) {
return "AIPA" + stableSuffix(instanceId, 17).toUpperCase();
}
/**
* Deterministic association id derived from the instance id so repeated describes are stable.
*/
private static String iamInstanceProfileAssociationId(String instanceId) {
return "iip-assoc-" + stableSuffix(instanceId, 17);
}
private static String stableSuffix(String seed, int length) {
StringBuilder sb = new StringBuilder();
int h = seed.hashCode();
String alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
long v = ((long) h) & 0xFFFFFFFFL;
for (int i = 0; i < length; i++) {
sb.append(alphabet.charAt((int) (v % alphabet.length())));
v = v * 1103515245L + 12345L + i;
v &= 0xFFFFFFFFL;
private Response handleAssociateIamInstanceProfile(MultivaluedMap<String, String> p, String region) {
String instanceId = requiredParam(p, "InstanceId");
String profileArn = resolveIamInstanceProfileArn(p);
if (profileArn == null) {
throw new AwsException("MissingParameter",
"The request must contain the parameter IamInstanceProfile", 400);
}
return sb.toString();
return associationResponse("AssociateIamInstanceProfileResponse",
service.associateIamInstanceProfile(region, instanceId, profileArn));
}
private Response handleReplaceIamInstanceProfileAssociation(MultivaluedMap<String, String> p, String region) {
String associationId = requiredParam(p, "AssociationId");
String profileArn = resolveIamInstanceProfileArn(p);
if (profileArn == null) {
throw new AwsException("MissingParameter",
"The request must contain the parameter IamInstanceProfile", 400);
}
return associationResponse("ReplaceIamInstanceProfileAssociationResponse",
service.replaceIamInstanceProfileAssociation(region, associationId, profileArn));
}
private Response handleDisassociateIamInstanceProfile(MultivaluedMap<String, String> p, String region) {
String associationId = requiredParam(p, "AssociationId");
return associationResponse("DisassociateIamInstanceProfileResponse",
service.disassociateIamInstanceProfile(region, associationId));
}
private static String requiredParam(MultivaluedMap<String, String> p, String name) {
String value = p.getFirst(name);
if (value == null || value.isBlank()) {
throw new AwsException("MissingParameter", "The request must contain the parameter " + name, 400);
}
return value;
}
private Response associationResponse(String root, IamInstanceProfileAssociation association) {
XmlBuilder xml = new XmlBuilder()
.start(root, AwsNamespaces.EC2)
.elem("requestId", UUID.randomUUID().toString())
.start("iamInstanceProfileAssociation")
.elem("associationId", association.associationId())
.elem("instanceId", association.instanceId())
.start("iamInstanceProfile")
.elem("arn", association.arn())
.elem("id", association.id())
.end("iamInstanceProfile")
.elem("state", association.state());
if (association.timestamp() != null) {
xml.elem("timestamp", ISO_FMT.format(association.timestamp()));
}
xml.end("iamInstanceProfileAssociation")
.end(root);
return xmlResponse(xml.build());
}
private Response handleDescribeInstances(MultivaluedMap<String, String> p, String region) {
@@ -1390,6 +1426,12 @@ public class Ec2QueryHandler {
private Response handleModifyInstanceAttribute(MultivaluedMap<String, String> p, String region) {
String instanceId = p.getFirst("InstanceId");
// UserData arrives base64-encoded, as on RunInstances; both forms are kept so the attribute
// describes back exactly as sent.
String userDataEncoded = p.getFirst("UserData.Value");
if (userDataEncoded != null) {
service.modifyInstanceUserData(region, instanceId, decodeUserData(userDataEncoded), userDataEncoded);
}
// Find which attribute is being modified
for (String attr : List.of("InstanceType.Value", "SourceDestCheck.Value", "EbsOptimized.Value")) {
String val = p.getFirst(attr);
@@ -4506,7 +4548,7 @@ public class Ec2QueryHandler {
if (inst.getIamInstanceProfileArn() != null) {
xml.start("iamInstanceProfile")
.elem("arn", inst.getIamInstanceProfileArn())
.elem("id", iamInstanceProfileId(inst.getInstanceId()))
.elem("id", Ec2Service.iamInstanceProfileId(inst.getInstanceId()))
.end("iamInstanceProfile");
}
xml.raw(tagSetXml(inst.getTags()));
@@ -50,6 +50,7 @@ import io.github.hectorvent.floci.services.ec2.model.BlockDeviceMapping;
import io.github.hectorvent.floci.services.ec2.model.CapacityReservation;
import io.github.hectorvent.floci.services.ec2.model.EbsBlockDevice;
import io.github.hectorvent.floci.services.ec2.model.GroupIdentifier;
import io.github.hectorvent.floci.services.ec2.model.IamInstanceProfileAssociation;
import io.github.hectorvent.floci.services.ec2.net.VpcNetworkManager;
import io.github.hectorvent.floci.services.ec2.portforward.Ec2PortForwardManager;
import io.github.hectorvent.floci.services.ec2.model.Image;
@@ -2760,6 +2761,9 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
inst.setUserData(userData);
inst.setEncodedUserData(encodedUserData);
inst.setIamInstanceProfileArn(iamInstanceProfileArn);
if (iamInstanceProfileArn != null) {
inst.setIamInstanceProfileAssociationTime(inst.getLaunchTime());
}
inst.setMetadataOptions(LaunchTemplateData.MetadataOptions.merge(launchMetadataOptions, null));
inst.setCreditSpecificationCpuCredits(
acquiredCpuCredits(effectiveInstanceType, creditSpecificationCpuCredits));
@@ -3429,6 +3433,116 @@ public class Ec2Service implements ContainerTeardown, ResourceProvider {
return inst;
}
/**
* ModifyInstanceAttribute with {@code UserData}. The instance must be stopped, as on AWS, so the
* new data is what its next boot reads. Both forms are stored, as RunInstances does, so
* DescribeInstanceAttribute echoes the exact base64 the caller sent.
*/
public void modifyInstanceUserData(String region, String instanceId, String userData) {
modifyInstanceUserData(region, instanceId, userData, userData == null ? null
: Base64.getEncoder().encodeToString(userData.getBytes(StandardCharsets.UTF_8)));
}
public void modifyInstanceUserData(String region, String instanceId, String userData, String encodedUserData) {
ensureDefaultResources(region);
Instance inst = getRequiredInstance(region, instanceId);
String state = inst.getState() != null ? inst.getState().getName() : null;
if (!"stopped".equals(state)) {
throw new AwsException("IncorrectInstanceState",
"The instance '" + instanceId + "' is not in the 'stopped' state.", 400);
}
inst.setUserData(userData);
inst.setEncodedUserData(encodedUserData);
instances.put(key(region, instanceId), inst);
}
/**
* Deterministic instance-profile id derived from the instance id so repeated describes are stable.
*/
public static String iamInstanceProfileId(String instanceId) {
return "AIPA" + stableSuffix(instanceId, 17).toUpperCase();
}
/**
* Deterministic association id derived from the instance id so repeated describes are stable.
*/
public static String iamInstanceProfileAssociationId(String instanceId) {
return "iip-assoc-" + stableSuffix(instanceId, 17);
}
private static String stableSuffix(String seed, int length) {
StringBuilder sb = new StringBuilder();
int h = seed.hashCode();
String alphabet = "0123456789abcdefghijklmnopqrstuvwxyz";
long v = ((long) h) & 0xFFFFFFFFL;
for (int i = 0; i < length; i++) {
sb.append(alphabet.charAt((int) (v % alphabet.length())));
v = v * 1103515245L + 12345L + i;
v &= 0xFFFFFFFFL;
}
return sb.toString();
}
/**
* AssociateIamInstanceProfile. An instance carries at most one profile, so a second association
* is refused with the IncorrectState AWS answers; the profile arrives already resolved to its
* ARN, the way RunInstances takes one.
*/
public IamInstanceProfileAssociation associateIamInstanceProfile(String region, String instanceId,
String profileArn) {
ensureDefaultResources(region);
Instance inst = getRequiredInstance(region, instanceId);
if (inst.getIamInstanceProfileArn() != null) {
throw new AwsException("IncorrectState",
"There is an existing association for instance " + instanceId, 400);
}
inst.setIamInstanceProfileArn(profileArn);
inst.setIamInstanceProfileAssociationTime(Instant.now());
instances.put(key(region, instanceId), inst);
return association(inst, profileArn, "associating");
}
/** ReplaceIamInstanceProfileAssociation: swaps the profile behind an existing association. */
public IamInstanceProfileAssociation replaceIamInstanceProfileAssociation(String region, String associationId,
String profileArn) {
ensureDefaultResources(region);
Instance inst = getRequiredAssociatedInstance(region, associationId);
inst.setIamInstanceProfileArn(profileArn);
inst.setIamInstanceProfileAssociationTime(Instant.now());
instances.put(key(region, inst.getInstanceId()), inst);
return association(inst, profileArn, "associating");
}
/** DisassociateIamInstanceProfile: the answer still names the profile being detached. */
public IamInstanceProfileAssociation disassociateIamInstanceProfile(String region, String associationId) {
ensureDefaultResources(region);
Instance inst = getRequiredAssociatedInstance(region, associationId);
String detached = inst.getIamInstanceProfileArn();
Instant associatedAt = inst.getIamInstanceProfileAssociationTime();
inst.setIamInstanceProfileArn(null);
inst.setIamInstanceProfileAssociationTime(null);
instances.put(key(region, inst.getInstanceId()), inst);
return new IamInstanceProfileAssociation(associationId, inst.getInstanceId(), detached,
iamInstanceProfileId(inst.getInstanceId()), "disassociating", associatedAt);
}
private Instance getRequiredAssociatedInstance(String region, String associationId) {
for (Instance inst : instances.scan(k -> true)) {
if (region.equals(inst.getRegion()) && inst.getIamInstanceProfileArn() != null
&& associationId.equals(iamInstanceProfileAssociationId(inst.getInstanceId()))) {
return inst;
}
}
throw new AwsException("InvalidAssociationID.NotFound",
"An invalid association-id of '" + associationId + "' was given", 400);
}
private static IamInstanceProfileAssociation association(Instance inst, String profileArn, String state) {
return new IamInstanceProfileAssociation(iamInstanceProfileAssociationId(inst.getInstanceId()),
inst.getInstanceId(), profileArn, iamInstanceProfileId(inst.getInstanceId()), state,
inst.getIamInstanceProfileAssociationTime());
}
public void modifyInstanceAttribute(String region, String instanceId, String attribute, String value) {
ensureDefaultResources(region);
Instance inst = getRequiredInstance(region, instanceId);
@@ -0,0 +1,12 @@
package io.github.hectorvent.floci.services.ec2.model;
import java.time.Instant;
/**
* An IAM instance profile association as the association actions report it: the state is the
* transitional one AWS answers with ({@code associating}, {@code disassociating}); the describe
* action reports the settled {@code associated}.
*/
public record IamInstanceProfileAssociation(String associationId, String instanceId, String arn,
String id, String state, Instant timestamp) {
}
@@ -45,6 +45,7 @@ public class Instance {
private boolean ebsOptimized = false;
private boolean enaSupport = true;
private String iamInstanceProfileArn;
private Instant iamInstanceProfileAssociationTime;
private String stateReasonCode;
private String stateReasonMessage;
private String region;
@@ -182,6 +183,8 @@ public class Instance {
public String getIamInstanceProfileArn() { return iamInstanceProfileArn; }
public void setIamInstanceProfileArn(String iamInstanceProfileArn) { this.iamInstanceProfileArn = iamInstanceProfileArn; }
public Instant getIamInstanceProfileAssociationTime() { return iamInstanceProfileAssociationTime; }
public void setIamInstanceProfileAssociationTime(Instant iamInstanceProfileAssociationTime) { this.iamInstanceProfileAssociationTime = iamInstanceProfileAssociationTime; }
public String getStateReasonCode() { return stateReasonCode; }
public void setStateReasonCode(String stateReasonCode) { this.stateReasonCode = stateReasonCode; }