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

@@ -25,6 +25,8 @@ class CloudFormationEc2InstanceIntegrationTest {
"AWS4-HMAC-SHA256 Credential=test/20260205/ap-southeast-2/cloudformation/aws4_request";
private static final String EC2_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/ap-southeast-2/ec2/aws4_request";
private static final String IAM_AUTH =
"AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/iam/aws4_request";
@Test
void createStackProvisionsRealEc2Instance() {
@@ -150,6 +152,96 @@ class CloudFormationEc2InstanceIntegrationTest {
.body(containsString("<instanceType>t3.small</instanceType>"));
}
@Test
void updateStackAppliesUserDataAndIamInstanceProfileInPlace() {
String suffix = Long.toString(System.nanoTime(), 36);
String stackName = "cfn-ec2-inplace-" + suffix;
String firstProfile = "cfn-inplace-" + suffix;
String secondProfile = "cfn-inplace-v2-" + suffix;
String firstArn = createInstanceProfile(firstProfile);
String secondArn = createInstanceProfile(secondProfile);
String template = """
{
"Resources": {
"Server": {
"Type": "AWS::EC2::Instance",
"Properties": {"ImageId": "ami-12345678", "InstanceType": "t3.micro",
"UserData": "%s", "IamInstanceProfile": "%s"}
}
},
"Outputs": {
"InstanceId": {"Value": {"Ref": "Server"}}
}
}
""";
try {
cfn("CreateStack", stackName, template.formatted("first boot", firstProfile));
String instanceId = instanceIdFrom(describeStacks(stackName, "CREATE_COMPLETE"));
assertUserData(instanceId, "Zmlyc3QgYm9vdA==");
assertInstanceProfile(instanceId, firstArn);
cfn("UpdateStack", stackName, template.formatted("second boot", secondProfile));
String updateXml = describeStacks(stackName, "UPDATE_COMPLETE");
// Both properties are mutable: the same instance carries the new values.
assertTrue(updateXml.contains("<OutputValue>" + instanceId + "</OutputValue>"),
"instance id changed on update, so it was replaced not updated in place: " + updateXml);
assertUserData(instanceId, "c2Vjb25kIGJvb3Q=");
assertInstanceProfile(instanceId, secondArn);
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeInstances")
.formParam("InstanceId.1", instanceId)
.when().post("/").then().statusCode(200)
.body(containsString("<name>running</name>"));
} finally {
deleteInstanceProfile(firstProfile);
deleteInstanceProfile(secondProfile);
}
}
private static void assertUserData(String instanceId, String encoded) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", EC2_AUTH)
.formParam("Action", "DescribeInstanceAttribute")
.formParam("InstanceId", instanceId)
.formParam("Attribute", "userData")
.when().post("/").then().statusCode(200)
.body(containsString("<value>" + encoded + "</value>"));
}
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>"));
}
private static String createInstanceProfile(String name) {
return given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "CreateInstanceProfile")
.formParam("InstanceProfileName", name)
.when().post("/").then().statusCode(200)
.extract().path("CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.Arn");
}
private static void deleteInstanceProfile(String name) {
given()
.contentType("application/x-www-form-urlencoded")
.header("Authorization", IAM_AUTH)
.formParam("Action", "DeleteInstanceProfile")
.formParam("InstanceProfileName", name)
.when().post("/").then().statusCode(200);
}
@Test
void changingPrivateIpAddressReplacesTheInstance() {
String suffix = Long.toString(System.nanoTime(), 36);
@@ -15,6 +15,7 @@ import io.github.hectorvent.floci.services.ec2.model.Reservation;
import io.github.hectorvent.floci.services.ec2.model.Tag;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import java.util.ArrayList;
import java.util.HashMap;
@@ -33,6 +34,7 @@ import static org.mockito.ArgumentMatchers.anyList;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.times;
@@ -48,6 +50,8 @@ import static org.mockito.Mockito.when;
class Ec2InstanceCfnProvisionerTest {
private static final String TYPE = "AWS::EC2::Instance";
private static final String PROFILE_A = "arn:aws:iam::000000000000:instance-profile/web";
private static final String PROFILE_B = "arn:aws:iam::000000000000:instance-profile/web-v2";
private final Ec2Service ec2 = mock(Ec2Service.class);
private final Ec2InstanceCfnProvisioner provisioner = new Ec2InstanceCfnProvisioner(ec2);
@@ -223,6 +227,127 @@ class Ec2InstanceCfnProvisionerTest {
anyList(), any(), any(), anyList(), any(), any(), any());
}
@Test
void changedUserDataIsRewrittenAcrossAStopAndAStart() throws Exception {
Instance i1 = reusable("i-1");
i1.setUserData("old");
i1.setState(InstanceState.running());
StackResource r = resource("Server");
provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"UserData\": \"new\"}"), ctx("i-1"));
assertEquals("i-1", r.getPhysicalId());
InOrder order = inOrder(ec2);
order.verify(ec2).stopInstances("us-east-1", List.of("i-1"));
order.verify(ec2).modifyInstanceUserData("us-east-1", "i-1", "new");
order.verify(ec2).startInstances("us-east-1", List.of("i-1"));
order.verify(ec2).awaitContainerLaunch(i1);
}
@Test
void unchangedUserDataLeavesTheInstanceRunning() throws Exception {
Instance i1 = reusable("i-1");
i1.setUserData("same");
i1.setState(InstanceState.running());
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\", \"UserData\": \"same\"}"),
ctx("i-1"));
verify(ec2, never()).stopInstances(anyString(), anyList());
verify(ec2, never()).modifyInstanceUserData(anyString(), anyString(), any());
}
@Test
void aStoppedInstanceGetsItsUserDataRewrittenWithoutARestart() throws Exception {
Instance i1 = reusable("i-1");
i1.setUserData("old");
i1.setState(InstanceState.stopped());
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\", \"UserData\": \"new\"}"),
ctx("i-1"));
verify(ec2).modifyInstanceUserData("us-east-1", "i-1", "new");
verify(ec2, never()).stopInstances(anyString(), anyList());
verify(ec2, never()).startInstances(anyString(), anyList());
}
@Test
void declaringAnIamInstanceProfileAssociatesItByResolvedArn() throws Exception {
reusable("i-1");
when(ec2.resolveIamInstanceProfileName("web")).thenReturn(PROFILE_A);
StackResource r = resource("Server");
provisioner.provision(r, props("{\"ImageId\": \"ami-1\", \"IamInstanceProfile\": \"web\"}"), ctx("i-1"));
verify(ec2).associateIamInstanceProfile("us-east-1", "i-1", 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);
provisioner.provision(resource("Server"),
props("{\"ImageId\": \"ami-1\", \"IamInstanceProfile\": \"" + PROFILE_B + "\"}"), ctx("i-1"));
verify(ec2).replaceIamInstanceProfileAssociation("us-east-1",
Ec2Service.iamInstanceProfileAssociationId("i-1"), PROFILE_B);
verify(ec2, never()).associateIamInstanceProfile(anyString(), anyString(), anyString());
}
@Test
void droppingADeclaredIamInstanceProfileDisassociatesIt() throws Exception {
Instance i1 = reusable("i-1");
i1.setIamInstanceProfileArn(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"));
assertFalse(r.getAttributes().containsKey("__FlociDeclaredIamInstanceProfile"));
}
@Test
void aProfileTheTemplateNeverDeclaredIsKeptWhenItStaysUndeclared() throws Exception {
Instance i1 = reusable("i-1");
i1.setIamInstanceProfileArn(PROFILE_A);
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\"}"), ctx("i-1"));
verify(ec2, never()).disassociateIamInstanceProfile(anyString(), anyString());
verify(ec2, never()).replaceIamInstanceProfileAssociation(anyString(), anyString(), anyString());
}
@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());
ArgumentCaptor<String> profile = ArgumentCaptor.forClass(String.class);
verify(ec2).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(), anyList(),
any(), any(), anyList(), any(), profile.capture(), any());
assertEquals(PROFILE_A, profile.getValue());
assertEquals(PROFILE_A, r.getAttributes().get("__FlociDeclaredIamInstanceProfile"));
}
/** An instance the update finds and keeps: same image as the template, no createOnly change. */
private Instance reusable(String instanceId) {
Instance instance = new Instance();
instance.setInstanceId(instanceId);
instance.setImageId("ami-1");
when(ec2.describeInstances("us-east-1", List.of(instanceId), null))
.thenReturn(List.of(reservationOf(instance)));
return instance;
}
@Test
void changingImageIdReplacesTheInstanceAndRecordsTheCleanup() throws Exception {
Instance i1 = new Instance();
@@ -0,0 +1,133 @@
package io.github.hectorvent.floci.services.ec2;
import io.quarkus.test.junit.QuarkusTest;
import org.junit.jupiter.api.Test;
import static io.restassured.RestAssured.given;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.matchesPattern;
import static org.hamcrest.Matchers.startsWith;
/**
* The IAM instance profile association actions: associate by name or ARN, replace behind the
* association id, disassociate, and the errors AWS answers for a second association and an unknown
* association id. The profile a request names by {@code Name} must exist in IAM, as on AWS.
*/
@QuarkusTest
class Ec2IamInstanceProfileAssociationIntegrationTest {
private static final String EC2_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/ec2/aws4_request";
private static final String IAM_AUTH = "AWS4-HMAC-SHA256 Credential=test/20260205/us-east-1/iam/aws4_request";
private static final String ASSOCIATIONS =
"DescribeIamInstanceProfileAssociationsResponse.iamInstanceProfileAssociationSet";
@Test
void associateReplaceAndDisassociateAProfile() {
String suffix = Long.toString(System.nanoTime(), 36);
String first = "assoc-" + suffix;
String second = "assoc-v2-" + suffix;
String firstArn = createProfile(first);
String secondArn = createProfile(second);
String instanceId = given().header("Authorization", EC2_AUTH).formParam("Action", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
try {
String associationId = given().header("Authorization", EC2_AUTH)
.formParam("Action", "AssociateIamInstanceProfile")
.formParam("InstanceId", instanceId)
.formParam("IamInstanceProfile.Name", first)
.post("/").then().statusCode(200)
.body("AssociateIamInstanceProfileResponse.iamInstanceProfileAssociation.instanceId",
equalTo(instanceId))
.body("AssociateIamInstanceProfileResponse.iamInstanceProfileAssociation.iamInstanceProfile.arn",
equalTo(firstArn))
.body("AssociateIamInstanceProfileResponse.iamInstanceProfileAssociation.iamInstanceProfile.id",
startsWith("AIPA"))
.body("AssociateIamInstanceProfileResponse.iamInstanceProfileAssociation.state",
equalTo("associating"))
.body("AssociateIamInstanceProfileResponse.iamInstanceProfileAssociation.timestamp",
matchesPattern("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"))
.extract().path("AssociateIamInstanceProfileResponse.iamInstanceProfileAssociation.associationId");
// One profile per instance: a second association is refused, not stacked.
given().header("Authorization", EC2_AUTH).formParam("Action", "AssociateIamInstanceProfile")
.formParam("InstanceId", instanceId).formParam("IamInstanceProfile.Arn", secondArn)
.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("IncorrectState"));
assertAssociated(instanceId, associationId, firstArn);
given().header("Authorization", EC2_AUTH).formParam("Action", "ReplaceIamInstanceProfileAssociation")
.formParam("AssociationId", associationId).formParam("IamInstanceProfile.Arn", secondArn)
.post("/").then().statusCode(200)
.body("ReplaceIamInstanceProfileAssociationResponse.iamInstanceProfileAssociation.associationId",
equalTo(associationId))
.body("ReplaceIamInstanceProfileAssociationResponse.iamInstanceProfileAssociation.iamInstanceProfile.arn",
equalTo(secondArn))
.body("ReplaceIamInstanceProfileAssociationResponse.iamInstanceProfileAssociation.state",
equalTo("associating"));
assertAssociated(instanceId, associationId, secondArn);
given().header("Authorization", EC2_AUTH).formParam("Action", "DisassociateIamInstanceProfile")
.formParam("AssociationId", associationId)
.post("/").then().statusCode(200)
.body("DisassociateIamInstanceProfileResponse.iamInstanceProfileAssociation.iamInstanceProfile.arn",
equalTo(secondArn))
.body("DisassociateIamInstanceProfileResponse.iamInstanceProfileAssociation.state",
equalTo("disassociating"));
given().header("Authorization", EC2_AUTH).formParam("Action", "DescribeIamInstanceProfileAssociations")
.formParam("Filter.1.Name", "instance-id").formParam("Filter.1.Value.1", instanceId)
.post("/").then().statusCode(200)
.body(ASSOCIATIONS + ".item.size()", equalTo(0));
given().header("Authorization", EC2_AUTH).formParam("Action", "DisassociateIamInstanceProfile")
.formParam("AssociationId", associationId)
.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidAssociationID.NotFound"));
} finally {
given().header("Authorization", EC2_AUTH).formParam("Action", "TerminateInstances")
.formParam("InstanceId.1", instanceId).post("/").then().statusCode(200);
deleteProfile(first);
deleteProfile(second);
}
}
@Test
void associatingAnUnknownProfileNameIsRefused() {
String instanceId = given().header("Authorization", EC2_AUTH).formParam("Action", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
try {
given().header("Authorization", EC2_AUTH).formParam("Action", "AssociateIamInstanceProfile")
.formParam("InstanceId", instanceId).formParam("IamInstanceProfile.Name", "no-such-profile")
.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("InvalidParameterValue"));
} finally {
given().header("Authorization", EC2_AUTH).formParam("Action", "TerminateInstances")
.formParam("InstanceId.1", instanceId).post("/").then().statusCode(200);
}
}
private static void assertAssociated(String instanceId, String associationId, String arn) {
given().header("Authorization", EC2_AUTH).formParam("Action", "DescribeIamInstanceProfileAssociations")
.formParam("Filter.1.Name", "instance-id").formParam("Filter.1.Value.1", instanceId)
.post("/").then().statusCode(200)
.body(ASSOCIATIONS + ".item.associationId", equalTo(associationId))
.body(ASSOCIATIONS + ".item.iamInstanceProfile.arn", equalTo(arn))
.body(ASSOCIATIONS + ".item.state", equalTo("associated"))
.body(ASSOCIATIONS + ".item.timestamp",
matchesPattern("\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z"));
}
private static String createProfile(String name) {
return given().header("Authorization", IAM_AUTH).formParam("Action", "CreateInstanceProfile")
.formParam("InstanceProfileName", name)
.post("/").then().statusCode(200)
.extract().path("CreateInstanceProfileResponse.CreateInstanceProfileResult.InstanceProfile.Arn");
}
private static void deleteProfile(String name) {
given().header("Authorization", IAM_AUTH).formParam("Action", "DeleteInstanceProfile")
.formParam("InstanceProfileName", name).post("/").then().statusCode(200);
}
}
@@ -48,6 +48,34 @@ class Ec2UserDataAttributeIntegrationTest {
}
}
@Test
void modifyingUserDataNeedsAStoppedInstanceAndIsDescribedBack() {
String id = given().header("Authorization", AUTH).formParam("Action", "RunInstances")
.formParam("ImageId", "ami-0abcdef1234567890").formParam("InstanceType", "t3.micro")
.formParam("UserData", "b2xk").post("/").then().statusCode(200)
.extract().path("RunInstancesResponse.instancesSet.item.instanceId");
try {
// A running instance refuses the change, as on AWS.
given().header("Authorization", AUTH).formParam("Action", "ModifyInstanceAttribute")
.formParam("InstanceId", id).formParam("UserData.Value", "bmV3")
.post("/").then().statusCode(400)
.body("Response.Errors.Error.Code", equalTo("IncorrectInstanceState"));
given().header("Authorization", AUTH).formParam("Action", "StopInstances")
.formParam("InstanceId.1", id).post("/").then().statusCode(200);
given().header("Authorization", AUTH).formParam("Action", "ModifyInstanceAttribute")
.formParam("InstanceId", id).formParam("UserData.Value", "bmV3")
.post("/").then().statusCode(200)
.body("ModifyInstanceAttributeResponse.return", equalTo("true"));
given().header("Authorization", AUTH).formParam("Action", "DescribeInstanceAttribute")
.formParam("InstanceId", id).formParam("Attribute", "userData")
.post("/").then().statusCode(200)
.body("DescribeInstanceAttributeResponse.userData.value.text()", equalTo("bmV3"));
} finally {
terminate(id);
}
}
private void terminate(String id) {
given().header("Authorization", AUTH).formParam("Action", "TerminateInstances")
.formParam("InstanceId.1", id).post("/").then().statusCode(200);