Light, fluffy, and always free - The AWS Local Emulator alternative
fix(cloudformation): apply EC2 Instance UserData and IamInstanceProfile in place (#4206)
Hector Ventura6fadba8d572a
diff --git a/docs/services/ec2.md b/docs/services/ec2.mdindex 86b9a245ab..f362aa1b92 100644--- a/docs/services/ec2.md+++ b/docs/services/ec2.md@@ -186,7 +186,7 @@ Floci seeds the following resources on first use in each region so Terraform, th| DescribeInstanceStatus | Returns status records for stored instances. || DescribeInstanceCreditSpecifications | Returns the CPU credit option of burstable performance instances. A named instance id reports the option the instance acquired at launch, either the explicit `CreditSpecification.CpuCredits` or the family default, `standard` for t2 and `unlimited` for t3, t3a and t4g. An id that is not a burstable performance instance reports `standard`, and only an unknown id is an error. Naming no id returns the instances on the unlimited option, including one that kept `unlimited` after a resize onto a non-burstable type. `Filter.N` supports the modeled `instance-id` and narrows whichever set the request selected. `MaxResults` accepts 5 through 1000 and cannot be combined with instance ids. `DryRun=true` returns `DryRunOperation`. || DescribeInstanceAttribute | Returns a supported attribute for an instance. |-| ModifyInstanceAttribute | Updates supported mutable attributes for an instance. |+| ModifyInstanceAttribute | Updates supported mutable attributes for an instance. `UserData.Value` (base64) needs the instance stopped, as on AWS, and answers `IncorrectInstanceState` otherwise. || ModifyInstanceMetadataOptions | Updates an instance's IMDS options, changing only the fields the request names. |### VPCs@@ -649,6 +649,9 @@ prefix lists, `EnaSrdSpecification`, `PrimaryIpv6` and `EnaQueueCount` are likew| Action | Description ||--------|-------------|| DescribeIamInstanceProfileAssociations | Lists IAM instance profile associations known to the local EC2 service. |+| AssociateIamInstanceProfile | Attaches a profile, named by `IamInstanceProfile.Arn` or `IamInstanceProfile.Name`, to an instance that has none; a second association answers `IncorrectState`. |+| ReplaceIamInstanceProfileAssociation | Swaps the profile behind an existing association id; an unknown id answers `InvalidAssociationID.NotFound`. |+| DisassociateIamInstanceProfile | Detaches the profile behind an association id. |### Network Interfacesdiff --git a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.javaindex 92111a52c2..661503f97c 100644--- a/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java+++ b/src/main/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisioner.java@@ -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) {diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.javaindex 7c8e0689fa..22ef5306df 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2QueryHandler.java@@ -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();+ 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 associationResponse("AssociateIamInstanceProfileResponse",+ service.associateIamInstanceProfile(region, instanceId, profileArn));}- /**- * 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 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 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 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 sb.toString();+ 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 modifiedfor (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()));diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.javaindex acd45a57af..db669c9012 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/Ec2Service.java@@ -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);diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/IamInstanceProfileAssociation.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IamInstanceProfileAssociation.javanew file mode 100644index 0000000000..2a4ce28bc4--- /dev/null+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/IamInstanceProfileAssociation.java@@ -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) {+}diff --git a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.javaindex e0efab17e3..14d9821b82 100644--- a/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java+++ b/src/main/java/io/github/hectorvent/floci/services/ec2/model/Instance.java@@ -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; }diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.javaindex 7fd1ff276b..937dafaa65 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/CloudFormationEc2InstanceIntegrationTest.java@@ -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";@Testvoid 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);+ }+@Testvoid changingPrivateIpAddressReplacesTheInstance() {String suffix = Long.toString(System.nanoTime(), 36);diff --git a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.javaindex b08ebca737..494505d8bf 100644--- a/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/cloudformation/provisioners/Ec2InstanceCfnProvisionerTest.java@@ -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;+ }+@Testvoid changingImageIdReplacesTheInstanceAndRecordsTheCleanup() throws Exception {Instance i1 = new Instance();diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IamInstanceProfileAssociationIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IamInstanceProfileAssociationIntegrationTest.javanew file mode 100644index 0000000000..9186889f14--- /dev/null+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2IamInstanceProfileAssociationIntegrationTest.java@@ -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);+ }+}diff --git a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2UserDataAttributeIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2UserDataAttributeIntegrationTest.javaindex c710e28ee4..a2da4a7833 100644--- a/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2UserDataAttributeIntegrationTest.java+++ b/src/test/java/io/github/hectorvent/floci/services/ec2/Ec2UserDataAttributeIntegrationTest.java@@ -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);