mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
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:
1 parent
a3a3efec32
commit
e27a307622
8 files changed
+434
-109
No files matched your search
+80
-8
@@ -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) {
|
||||
|
||||
+1
-2
@@ -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"));
|
||||
|
||||
+269
-65
@@ -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;
|
||||
|
||||
Reference in new issue
Block a user