mirror of
https://github.com/floci-io/floci.git
synced 2026-11-22 21:50:46 -05:00
fix(cloudformation): clear dropped stage variables and instance user data (#7736)
This commit is contained in:
1 parent
413f490d8c
commit
3c66249375
9 files changed
+567
-9
No files matched your search
@@ -730,12 +730,18 @@ closing a gap deletes its row. A new type needs a row in that file: `make cfn-sc
|
||||
regenerates it from AWS's published schemas, and `cfn-schema-drift.yml` compares it weekly.
|
||||
|
||||
A property the previous template declared and the new template drops is cleared on `UpdateStack`,
|
||||
goes back to its create default, or is kept, on the AppSync resources and the EC2 networking types
|
||||
(`Subnet`, `InternetGateway`, `RouteTable`, `NatGateway`, `EIP`, `PrefixList`). Kept: required members
|
||||
goes back to its create default, or is kept, on the AppSync resources, the EC2 networking types
|
||||
(`Subnet`, `InternetGateway`, `RouteTable`, `NatGateway`, `EIP`, `PrefixList`), an
|
||||
`AWS::ApiGatewayV2::Stage` and an `AWS::EC2::Instance`. Kept: required members
|
||||
(`AuthenticationType`, `Type`, a function's `DataSourceName`), a data source's and a function's `Name`,
|
||||
an API key's `Expires`, a GraphQL API's `ApiType` and `Visibility`, a UNIT resolver's `DataSourceName`,
|
||||
a `NatGateway`'s `PrivateIpAddress` and a `PrefixList`'s `MaxEntries`. An update that drops a
|
||||
`PrefixList`'s `AddressFamily` or `PrefixListName` fails. Create-only members are not cleared either.
|
||||
a `NatGateway`'s `PrivateIpAddress`, a `PrefixList`'s `MaxEntries`, a `Stage`'s `StageName` and an
|
||||
`Instance`'s `SecurityGroupIds`, `NetworkInterfaces` and `LaunchTemplate`. A dropped `LaunchTemplate` keeps
|
||||
the instance, but the instance type and the `MetadataOptions` members the template supplied go back to
|
||||
their defaults. A `Stage`'s dropped `StageVariables` become empty. An `Instance`'s dropped `UserData` is
|
||||
cleared: a running instance is stopped for the rewrite and started again, and a stopped one stays stopped.
|
||||
An update that drops a `PrefixList`'s `AddressFamily` or `PrefixListName` fails. Create-only members are
|
||||
not cleared either.
|
||||
A property the stack never declared keeps the value set outside it, with one exception: a GraphQL API's
|
||||
`Tags` and `EnvironmentVariables`, which every update drives to the template. The table says so on
|
||||
those rows. The three `NatGateway` `Secondary*` properties count as one
|
||||
|
||||
+4
@@ -1031,6 +1031,10 @@ public class ApiGatewayV2CfnProvisioner implements CfnResourceProvisioner {
|
||||
req.put("stageName", stageName);
|
||||
req.put("autoDeploy", ctx.resolveOrDefault(props, "AutoDeploy", "false"));
|
||||
Map<String, String> stageVariables = parseStageVariables(props, engine);
|
||||
if (stageVariables == null && ctx.droppedProperties(props).contains("StageVariables")) {
|
||||
// The service replaces the variables on a non-null map, so an empty one clears them.
|
||||
stageVariables = new LinkedHashMap<>();
|
||||
}
|
||||
if (stageVariables != null) {
|
||||
req.put("stageVariables", stageVariables);
|
||||
}
|
||||
|
||||
+9
-3
@@ -157,7 +157,8 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
boolean metadataOptionsChange = metadataOptionsToApply != null
|
||||
&& Ec2CfnMetadataOptions.changes(optionsBefore, metadataOptionsToApply);
|
||||
boolean otherChange = reconcileMutableProperties(region, prior, instanceType, securityGroupIds,
|
||||
userData, iamInstanceProfileArn, attributesBefore.get(DECLARED_IAM_PROFILE_ATTR));
|
||||
userData, ctx.droppedProperties(props).contains("UserData"), iamInstanceProfileArn,
|
||||
attributesBefore.get(DECLARED_IAM_PROFILE_ATTR));
|
||||
boolean tagsChanged = Ec2Tags.reconcileOwned(ec2Service, region, prior.getInstanceId(),
|
||||
Ec2Tags.ownedKeys(r, DECLARED_TAG_KEYS_ATTR, ctx), desiredTags);
|
||||
// Saved on every update that keeps the instance, also one that changes no EC2 setting but
|
||||
@@ -285,14 +286,16 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
* "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). Returns
|
||||
* does not strip what the instance already has (a launch template may have set it); UserData the
|
||||
* previous template declared and this one drops is cleared. Returns
|
||||
* whether it changed anything, which a stack rollback has no way to put back here. MetadataOptions
|
||||
* is applied after it, as the property's "No interruption" update allows, by the caller, which
|
||||
* keeps what it replaces for {@link #rollbackUpdate}.
|
||||
*/
|
||||
private boolean reconcileMutableProperties(String region, Instance prior, String instanceType,
|
||||
List<String> securityGroupIds, String userData,
|
||||
String iamInstanceProfileArn, String priorDeclaredProfileArn) {
|
||||
boolean userDataDropped, String iamInstanceProfileArn,
|
||||
String priorDeclaredProfileArn) {
|
||||
boolean changed = false;
|
||||
if (instanceType != null && !instanceType.isBlank()
|
||||
&& !instanceType.equals(prior.getInstanceType())) {
|
||||
@@ -306,6 +309,9 @@ public class Ec2InstanceCfnProvisioner implements CfnResourceProvisioner {
|
||||
if (userData != null && !userData.equals(prior.getUserData())) {
|
||||
rewriteUserData(region, prior, userData);
|
||||
changed = true;
|
||||
} else if (userData == null && userDataDropped && prior.getUserData() != null) {
|
||||
rewriteUserData(region, prior, null);
|
||||
changed = true;
|
||||
}
|
||||
return reconcileIamInstanceProfile(region, prior, iamInstanceProfileArn, priorDeclaredProfileArn) || changed;
|
||||
}
|
||||
|
||||
+82
@@ -19,6 +19,7 @@ import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.ValueSource;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InOrder;
|
||||
|
||||
import java.util.HashMap;
|
||||
@@ -1034,6 +1035,71 @@ class ApiGatewayV2CfnProvisionerTest {
|
||||
null, null);
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageVariablesDroppedFromTheTemplateAreClearedOnUpdate() throws Exception {
|
||||
provisionStageUpdate("""
|
||||
{"ApiId":"api-123","StageName":"prod","StageVariables":{"color":"blue"}}
|
||||
""", """
|
||||
{"ApiId":"api-123","StageName":"prod"}
|
||||
""");
|
||||
|
||||
assertEquals(Map.of(), updatedStageRequest().get("stageVariables"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyStageVariablesInTheTemplateStayEmpty() throws Exception {
|
||||
provisionStageUpdate("""
|
||||
{"ApiId":"api-123","StageName":"prod","StageVariables":{"color":"blue"}}
|
||||
""", """
|
||||
{"ApiId":"api-123","StageName":"prod","StageVariables":{}}
|
||||
""");
|
||||
|
||||
assertEquals(Map.of(), updatedStageRequest().get("stageVariables"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void changedStageVariablesStillApply() throws Exception {
|
||||
provisionStageUpdate("""
|
||||
{"ApiId":"api-123","StageName":"prod","StageVariables":{"color":"blue"}}
|
||||
""", """
|
||||
{"ApiId":"api-123","StageName":"prod","StageVariables":{"color":"green","size":"2"}}
|
||||
""");
|
||||
|
||||
assertEquals(Map.of("color", "green", "size", "2"), updatedStageRequest().get("stageVariables"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageVariablesSetOutsideTheStackSurviveAnUpdateThatNeverDeclaredThem() throws Exception {
|
||||
provisionStageUpdate("""
|
||||
{"ApiId":"api-123","StageName":"prod"}
|
||||
""", """
|
||||
{"ApiId":"api-123","StageName":"prod","AutoDeploy":true}
|
||||
""");
|
||||
|
||||
assertNull(updatedStageRequest().get("stageVariables"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void createStageSendsTheDeclaredStageVariables() throws Exception {
|
||||
provisioner.provision("Stage", "AWS::ApiGatewayV2::Stage", mapper.readTree("""
|
||||
{"ApiId":"api-123","StageName":"prod","StageVariables":{"color":"blue"}}
|
||||
"""), engine(), REGION, "000000000000", "test-stack", null, Map.of());
|
||||
|
||||
ArgumentCaptor<Map<String, Object>> request = requestCaptor();
|
||||
verify(apiGatewayV2Service).createStage(eq(REGION), eq(API_ID), request.capture());
|
||||
assertEquals(Map.of("color", "blue"), request.getValue().get("stageVariables"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppingAutoDeployGoesBackToFalseAndDroppingStageNameKeepsTheStage() throws Exception {
|
||||
provisionStageUpdate("{\"ApiId\": \"api-123\", \"StageName\": \"prod\", \"AutoDeploy\": true}",
|
||||
"{\"ApiId\": \"api-123\"}");
|
||||
|
||||
Map<String, Object> request = updatedStageRequest();
|
||||
assertEquals("false", request.get("autoDeploy"));
|
||||
assertNull(request.get("stageName"));
|
||||
}
|
||||
|
||||
private static final String INTEGRATION_PROPERTIES = """
|
||||
{"ApiId":"api-123","IntegrationType":"HTTP_PROXY","IntegrationUri":"http://backend",
|
||||
"IntegrationMethod":"ANY","PayloadFormatVersion":"1.0","TimeoutInMillis":"15000",
|
||||
@@ -1070,6 +1136,22 @@ class ApiGatewayV2CfnProvisionerTest {
|
||||
.thenReturn(prior);
|
||||
}
|
||||
|
||||
private void provisionStageUpdate(String previous, String current) throws Exception {
|
||||
provisioner.provision("Stage", "AWS::ApiGatewayV2::Stage", mapper.readTree(current), engine(), REGION,
|
||||
"000000000000", "test-stack", "prod", Map.of(), event -> {}, mapper.readTree(previous));
|
||||
}
|
||||
|
||||
private Map<String, Object> updatedStageRequest() {
|
||||
ArgumentCaptor<Map<String, Object>> request = requestCaptor();
|
||||
verify(apiGatewayV2Service).updateStage(eq(REGION), eq(API_ID), eq("prod"), request.capture());
|
||||
return request.getValue();
|
||||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private static ArgumentCaptor<Map<String, Object>> requestCaptor() {
|
||||
return ArgumentCaptor.forClass((Class<Map<String, Object>>) (Class<?>) Map.class);
|
||||
}
|
||||
|
||||
private StackResource provisionIntegration(String properties) throws Exception {
|
||||
return provisioner.provision("Integration", "AWS::ApiGatewayV2::Integration", mapper.readTree(properties),
|
||||
engine(), REGION, "000000000000", "test-stack", "int-1", Map.of("IntegrationId", "int-1"));
|
||||
|
||||
@@ -2,6 +2,7 @@ package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.floci.aws.services.apigatewayv2.model.Integration;
|
||||
import io.floci.aws.services.apigatewayv2.model.Stage;
|
||||
import io.floci.aws.services.cloudformation.model.Stack;
|
||||
import io.floci.aws.services.cloudformation.model.StackResource;
|
||||
import io.restassured.specification.RequestSpecification;
|
||||
@@ -30,6 +31,12 @@ final class ApiGatewayV2StackTestSupport {
|
||||
return apiGatewayV2Service.getIntegration(REGION, api.getPhysicalId(), integration.getPhysicalId());
|
||||
}
|
||||
|
||||
static Stage stage(ApiGatewayV2Service apiGatewayV2Service, Stack stack) {
|
||||
StackResource api = stack.getResources().get("HttpApi");
|
||||
StackResource stage = stack.getResources().get("Stage");
|
||||
return apiGatewayV2Service.getStage(REGION, api.getPhysicalId(), stage.getPhysicalId());
|
||||
}
|
||||
|
||||
static Stack stack(CloudFormationService cloudFormationService, String stackName) {
|
||||
return cloudFormationService.describeStacks(stackName, REGION).getFirst();
|
||||
}
|
||||
|
||||
+97
-1
@@ -2,6 +2,7 @@ package io.floci.aws.services.cloudformation;
|
||||
|
||||
import io.floci.aws.services.apigatewayv2.ApiGatewayV2Service;
|
||||
import io.floci.aws.services.apigatewayv2.model.Integration;
|
||||
import io.floci.aws.services.apigatewayv2.model.Stage;
|
||||
import io.floci.aws.services.cloudformation.model.Stack;
|
||||
import io.floci.aws.testing.CfnStackWaits;
|
||||
import io.floci.aws.testing.RestAssuredJsonUtils;
|
||||
@@ -18,16 +19,21 @@ import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.
|
||||
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.integration;
|
||||
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stack;
|
||||
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stackAction;
|
||||
import static io.floci.aws.services.cloudformation.ApiGatewayV2StackTestSupport.stage;
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.hamcrest.Matchers.anEmptyMap;
|
||||
import static org.hamcrest.Matchers.anyOf;
|
||||
import static org.hamcrest.Matchers.equalTo;
|
||||
import static org.hamcrest.Matchers.nullValue;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
* The settings of an AWS::ApiGatewayV2::Integration through a real stack: a setting the template
|
||||
* drops on update is removed from the stored integration and from GetIntegration, and a failed
|
||||
* update puts the earlier settings back.
|
||||
* update puts the earlier settings back. The stage variables of an AWS::ApiGatewayV2::Stage follow the
|
||||
* same rule: dropped on update, they are cleared from the stage.
|
||||
*/
|
||||
@QuarkusTest
|
||||
class CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest {
|
||||
@@ -108,6 +114,96 @@ class CloudFormationApiGatewayV2IntegrationSettingsIntegrationTest {
|
||||
.body("requestParameters.'overwrite:header.x-example'", equalTo("original"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageVariablesTheTemplateDropsAreClearedFromTheStage() {
|
||||
String stackName = "stage-variables-drop-stack";
|
||||
stackAction("CreateStack", stackName, stageTemplate(",\"StageVariables\":{\"color\":\"blue\"}"));
|
||||
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
|
||||
Stack created = stack(cloudFormationService, stackName);
|
||||
assertEquals(Map.of("color", "blue"), stage(apiGatewayV2Service, created).getStageVariables());
|
||||
getStageResponse(created).body("stageVariables.color", equalTo("blue"));
|
||||
|
||||
stackAction("UpdateStack", stackName,
|
||||
stageTemplate(",\"StageVariables\":{\"color\":\"green\",\"size\":\"2\"}"));
|
||||
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
|
||||
assertEquals(Map.of("color", "green", "size", "2"),
|
||||
stage(apiGatewayV2Service, stack(cloudFormationService, stackName)).getStageVariables());
|
||||
|
||||
stackAction("UpdateStack", stackName, stageTemplate(""));
|
||||
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
|
||||
Stack dropped = stack(cloudFormationService, stackName);
|
||||
assertNoStageVariables(stage(apiGatewayV2Service, dropped));
|
||||
getStageResponse(dropped).body("stageVariables", anyOf(nullValue(), anEmptyMap()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageVariablesMadeNoValueByAConditionAreClearedFromTheStage() {
|
||||
String stackName = "stage-variables-novalue-stack";
|
||||
stackAction("CreateStack", stackName, stageTemplate(",\"StageVariables\":{\"color\":\"red\"}"));
|
||||
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
|
||||
assertEquals(Map.of("color", "red"),
|
||||
stage(apiGatewayV2Service, stack(cloudFormationService, stackName)).getStageVariables());
|
||||
|
||||
stackAction("UpdateStack", stackName, stageTemplate(
|
||||
",\"StageVariables\":{\"Fn::If\":[\"Off\",{\"Ref\":\"AWS::NoValue\"},{\"color\":\"red\"}]}"));
|
||||
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
|
||||
assertNoStageVariables(stage(apiGatewayV2Service, stack(cloudFormationService, stackName)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyStageVariablesDeclaredByTheTemplateStayEmpty() {
|
||||
String stackName = "stage-variables-empty-stack";
|
||||
stackAction("CreateStack", stackName, stageTemplate(",\"StageVariables\":{\"color\":\"blue\"}"));
|
||||
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
|
||||
|
||||
stackAction("UpdateStack", stackName, stageTemplate(",\"StageVariables\":{}"));
|
||||
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
|
||||
|
||||
assertNoStageVariables(stage(apiGatewayV2Service, stack(cloudFormationService, stackName)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void stageVariablesSetOutsideTheStackSurviveAnUpdateThatNeverDeclaredThem() {
|
||||
String stackName = "stage-variables-outside-stack";
|
||||
stackAction("CreateStack", stackName, stageTemplate(""));
|
||||
CfnStackWaits.awaitStatus(stackName, "CREATE_COMPLETE");
|
||||
Stack created = stack(cloudFormationService, stackName);
|
||||
apiGatewayV2Service.updateStage(REGION, created.getResources().get("HttpApi").getPhysicalId(),
|
||||
created.getResources().get("Stage").getPhysicalId(),
|
||||
Map.of("stageVariables", Map.of("outside", "kept")));
|
||||
|
||||
stackAction("UpdateStack", stackName, stageTemplate("").replace("\"AutoDeploy\":false", "\"AutoDeploy\":true"));
|
||||
CfnStackWaits.awaitStatus(stackName, "UPDATE_COMPLETE");
|
||||
|
||||
Stage stage = stage(apiGatewayV2Service, stack(cloudFormationService, stackName));
|
||||
assertTrue(stage.isAutoDeploy());
|
||||
assertEquals(Map.of("outside", "kept"), stage.getStageVariables());
|
||||
}
|
||||
|
||||
private static void assertNoStageVariables(Stage stage) {
|
||||
assertTrue(stage.getStageVariables() == null || stage.getStageVariables().isEmpty(),
|
||||
"expected no stage variables, got " + stage.getStageVariables());
|
||||
}
|
||||
|
||||
private ValidatableResponse getStageResponse(Stack stack) {
|
||||
String apiId = stack.getResources().get("HttpApi").getPhysicalId();
|
||||
String stageName = stack.getResources().get("Stage").getPhysicalId();
|
||||
return given().when().get("/v2/apis/" + apiId + "/stages/" + stageName)
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
/** An HTTP API and one stage; {@code stageSettings} adds stage properties, starting with a comma. */
|
||||
private static String stageTemplate(String stageSettings) {
|
||||
return """
|
||||
{"Conditions":{"Off":{"Fn::Equals":["a","a"]}},
|
||||
"Resources":{
|
||||
"HttpApi":{"Type":"AWS::ApiGatewayV2::Api","Properties":{
|
||||
"Name":"stage-variables-api","ProtocolType":"HTTP"}},
|
||||
"Stage":{"Type":"AWS::ApiGatewayV2::Stage","Properties":{
|
||||
"ApiId":{"Ref":"HttpApi"},"StageName":"prod","AutoDeploy":false%s}}}}
|
||||
""".formatted(stageSettings);
|
||||
}
|
||||
|
||||
private ValidatableResponse getIntegrationResponse(Stack stack) {
|
||||
String apiId = stack.getResources().get("HttpApi").getPhysicalId();
|
||||
String integrationId = stack.getResources().get("Integration").getPhysicalId();
|
||||
|
||||
+90
@@ -1,6 +1,7 @@
|
||||
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.CfnStackWaits;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
@@ -19,6 +20,7 @@ import static org.hamcrest.Matchers.containsString;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
@@ -35,6 +37,7 @@ class CloudFormationEc2InstanceIntegrationTest {
|
||||
|
||||
private static final String CFN_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/ap-southeast-2/cloudformation/aws4_request";
|
||||
private static final String REGION = "ap-southeast-2";
|
||||
private static final String EC2_AUTH =
|
||||
"AWS4-HMAC-SHA256 Credential=test/20260205/ap-southeast-2/ec2/aws4_request";
|
||||
private static final String IAM_AUTH =
|
||||
@@ -282,6 +285,93 @@ class CloudFormationEc2InstanceIntegrationTest {
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateStackThatDropsUserDataClearsItAndLeavesTheInstanceRunning() {
|
||||
String stackName = "cfn-ec2-userdata-drop-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
{
|
||||
"Conditions": {"Off": {"Fn::Equals": ["a", "a"]}},
|
||||
"Resources": {
|
||||
"Server": {
|
||||
"Type": "AWS::EC2::Instance",
|
||||
"Properties": {"ImageId": "ami-12345678", "InstanceType": "t3.micro"%s}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"InstanceId": {"Value": {"Ref": "Server"}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
String withUserData = ", \"UserData\": \"first boot\"";
|
||||
String noValue = ", \"UserData\": {\"Fn::If\": [\"Off\", {\"Ref\": \"AWS::NoValue\"}, \"first boot\"]}";
|
||||
try {
|
||||
cfn("CreateStack", stackName, template.formatted(withUserData));
|
||||
String instanceId = instanceIdFrom(describeStacks(stackName, "CREATE_COMPLETE"));
|
||||
assertUserData(instanceId, "Zmlyc3QgYm9vdA==");
|
||||
|
||||
cfn("UpdateStack", stackName, template.formatted(""));
|
||||
String dropped = describeStacks(stackName, "UPDATE_COMPLETE");
|
||||
assertEquals(instanceId, instanceIdFrom(dropped));
|
||||
assertNoUserData(instanceId);
|
||||
assertInstanceRunning(instanceId);
|
||||
|
||||
cfn("UpdateStack", stackName, template.formatted(withUserData));
|
||||
describeStacks(stackName, "UPDATE_COMPLETE");
|
||||
assertUserData(instanceId, "Zmlyc3QgYm9vdA==");
|
||||
|
||||
cfn("UpdateStack", stackName, template.formatted(noValue));
|
||||
describeStacks(stackName, "UPDATE_COMPLETE");
|
||||
assertNoUserData(instanceId);
|
||||
assertInstanceRunning(instanceId);
|
||||
} finally {
|
||||
deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void userDataSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() {
|
||||
String stackName = "cfn-ec2-userdata-outside-" + Long.toString(System.nanoTime(), 36);
|
||||
String template = """
|
||||
{
|
||||
"Resources": {
|
||||
"Server": {
|
||||
"Type": "AWS::EC2::Instance",
|
||||
"Properties": {"ImageId": "ami-12345678", "InstanceType": "%s"}
|
||||
}
|
||||
},
|
||||
"Outputs": {
|
||||
"InstanceId": {"Value": {"Ref": "Server"}}
|
||||
}
|
||||
}
|
||||
""";
|
||||
try {
|
||||
cfn("CreateStack", stackName, template.formatted("t3.micro"));
|
||||
String instanceId = instanceIdFrom(describeStacks(stackName, "CREATE_COMPLETE"));
|
||||
ec2.stopInstances(REGION, List.of(instanceId));
|
||||
ec2.modifyInstanceUserData(REGION, instanceId, "outside");
|
||||
ec2.startInstances(REGION, List.of(instanceId));
|
||||
assertUserData(instanceId, "b3V0c2lkZQ==");
|
||||
|
||||
cfn("UpdateStack", stackName, template.formatted("t3.small"));
|
||||
assertEquals(instanceId, instanceIdFrom(describeStacks(stackName, "UPDATE_COMPLETE")));
|
||||
|
||||
assertUserData(instanceId, "b3V0c2lkZQ==");
|
||||
} finally {
|
||||
deleteStack(stackName);
|
||||
}
|
||||
}
|
||||
|
||||
private void assertNoUserData(String instanceId) {
|
||||
Instance instance = ec2.describeInstances(REGION, List.of(instanceId), null).get(0).getInstances().get(0);
|
||||
assertNull(instance.getUserData(), "expected no user data");
|
||||
assertNull(instance.getEncodedUserData(), "expected no encoded user data");
|
||||
}
|
||||
|
||||
private void assertInstanceRunning(String instanceId) {
|
||||
Instance instance = ec2.describeInstances(REGION, List.of(instanceId), null).get(0).getInstances().get(0);
|
||||
assertEquals("running", instance.getState().getName());
|
||||
}
|
||||
|
||||
private static void assertUserData(String instanceId, String encoded) {
|
||||
given()
|
||||
.contentType("application/x-www-form-urlencoded")
|
||||
|
||||
+251
-1
@@ -344,6 +344,251 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
verify(ec2, never()).modifyInstanceUserData(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppedUserDataIsClearedAcrossAStopAndAStart() 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\"}"),
|
||||
ctx("i-1", props("{\"ImageId\": \"ami-1\", \"UserData\": \"old\"}")));
|
||||
|
||||
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", (String) null);
|
||||
order.verify(ec2).startInstances("us-east-1", List.of("i-1"));
|
||||
order.verify(ec2).awaitContainerLaunch(i1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppedUserDataOnAStoppedInstanceIsClearedWithoutARestart() throws Exception {
|
||||
Instance i1 = reusable("i-1");
|
||||
i1.setUserData("old");
|
||||
i1.setState(InstanceState.stopped());
|
||||
|
||||
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\"}"),
|
||||
ctx("i-1", props("{\"ImageId\": \"ami-1\", \"UserData\": \"old\"}")));
|
||||
|
||||
verify(ec2).modifyInstanceUserData("us-east-1", "i-1", (String) null);
|
||||
verify(ec2, never()).stopInstances(anyString(), anyList());
|
||||
verify(ec2, never()).startInstances(anyString(), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void userDataSetOutsideTheStackSurvivesAnUpdateThatNeverDeclaredIt() throws Exception {
|
||||
Instance i1 = reusable("i-1");
|
||||
i1.setUserData("set outside the stack");
|
||||
i1.setState(InstanceState.running());
|
||||
|
||||
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\"}"),
|
||||
ctx("i-1", props("{\"ImageId\": \"ami-1\"}")));
|
||||
|
||||
verify(ec2, never()).stopInstances(anyString(), anyList());
|
||||
verify(ec2, never()).modifyInstanceUserData(anyString(), anyString(), any());
|
||||
verify(ec2, never()).startInstances(anyString(), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void anInstanceWithoutUserDataAndWithoutADeclarationIsLeftAlone() throws Exception {
|
||||
Instance i1 = reusable("i-1");
|
||||
i1.setState(InstanceState.running());
|
||||
|
||||
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\"}"),
|
||||
ctx("i-1", props("{\"ImageId\": \"ami-1\"}")));
|
||||
|
||||
verify(ec2, never()).stopInstances(anyString(), anyList());
|
||||
verify(ec2, never()).modifyInstanceUserData(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppedUserDataOnAnInstanceThatHasNoneStopsNothing() throws Exception {
|
||||
Instance i1 = reusable("i-1");
|
||||
i1.setState(InstanceState.running());
|
||||
|
||||
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\"}"),
|
||||
ctx("i-1", props("{\"ImageId\": \"ami-1\", \"UserData\": \"old\"}")));
|
||||
|
||||
verify(ec2, never()).stopInstances(anyString(), anyList());
|
||||
verify(ec2, never()).modifyInstanceUserData(anyString(), anyString(), any());
|
||||
}
|
||||
|
||||
// The tests down to droppingMetadataOptionsWhileTheLaunchTemplateSupplies... pin the
|
||||
// drop-policy.tsv rows of the properties they drop: what an update that drops each one does.
|
||||
@Test
|
||||
void droppingInstanceTypeGoesBackToTheDefaultAndSecurityGroupsAreKept() throws Exception {
|
||||
Instance i1 = reusable("i-1");
|
||||
i1.setInstanceType("m5.large");
|
||||
String previous = "{\"ImageId\": \"ami-1\", \"InstanceType\": \"m5.large\", "
|
||||
+ "\"SecurityGroupIds\": [\"sg-1\"]}";
|
||||
|
||||
provisioner.provision(resource("Server"), props("{\"ImageId\": \"ami-1\"}"), ctx("i-1", props(previous)));
|
||||
|
||||
verify(ec2).modifyInstanceAttribute("us-east-1", "i-1", "instanceType", "t3.micro");
|
||||
verify(ec2, never()).modifyInstanceGroups(anyString(), anyString(), anyList());
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppingTheLaunchTemplateKeepsTheInstanceAndResizesItToTheDefaultType() throws Exception {
|
||||
Instance i1 = reusable("i-1");
|
||||
i1.setInstanceType("m5.large");
|
||||
StackResource r = resource("Server");
|
||||
|
||||
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"),
|
||||
ctx("i-1", props("{\"ImageId\": \"ami-1\", \"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}")));
|
||||
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
verify(ec2).modifyInstanceAttribute("us-east-1", "i-1", "instanceType", "t3.micro");
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppingCreateOnlyAndLaunchOnlyPropertiesKeepsTheInstance() throws Exception {
|
||||
Instance i1 = reusable("i-1");
|
||||
i1.setKeyName("key");
|
||||
i1.setSubnetId("subnet-1");
|
||||
String previous = "{\"ImageId\": \"ami-1\", \"KeyName\": \"key\", \"SubnetId\": \"subnet-1\", "
|
||||
+ "\"NetworkInterfaces\": [{\"AssociatePublicIpAddress\": true}]}";
|
||||
StackResource r = resource("Server");
|
||||
|
||||
provisioner.provision(r, props("{}"), ctx("i-1", props(previous)));
|
||||
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
verify(ec2, never()).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void droppingADeclaredPrivateIpAddressOrAvailabilityZoneReplacesTheInstance() throws Exception {
|
||||
for (String declared : List.of("\"PrivateIpAddress\": \"10.0.0.5\"", "\"AvailabilityZone\": \"us-east-1a\"")) {
|
||||
Instance first = stubLaunches("i-1", "i-2").get(0);
|
||||
StackResource r = resource("Server");
|
||||
provisioner.provision(r, props("{\"ImageId\": \"ami-1\", " + declared + "}"), ctx(null));
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
when(ec2.describeInstances("us-east-1", List.of("i-1"), null))
|
||||
.thenReturn(List.of(reservationOf(first)));
|
||||
|
||||
provisioner.provision(r, props("{\"ImageId\": \"ami-1\"}"),
|
||||
ctx("i-1", props("{\"ImageId\": \"ami-1\", " + declared + "}")));
|
||||
|
||||
assertEquals("i-2", r.getPhysicalId(), declared);
|
||||
assertTrue(provisioner.hasReplacementUpdate(r), declared);
|
||||
}
|
||||
}
|
||||
|
||||
@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);
|
||||
stubLaunches("i-1", "i-2");
|
||||
StackResource r = resource("Server");
|
||||
String previous = "{\"ImageId\": \"ami-1\", \"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}";
|
||||
provisioner.provision(r, props(previous), ctx(null));
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
|
||||
provisioner.provision(r, props("{\"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}"),
|
||||
ctx("i-1", props(previous)));
|
||||
|
||||
assertEquals("i-2", r.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
verify(ec2, times(1)).runInstances(anyString(), eq("ami-2"), anyString(), anyInt(), anyInt(), any(),
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@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);
|
||||
reusable("i-1");
|
||||
StackResource r = resource("Server");
|
||||
|
||||
provisioner.provision(r, props("{\"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}"),
|
||||
ctx("i-1", props("{\"ImageId\": \"ami-1\", \"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}")));
|
||||
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
verify(ec2, never()).runInstances(anyString(), any(), anyString(), anyInt(), anyInt(), any(),
|
||||
anyList(), any(), any(), anyList(), any(), any(), any(),
|
||||
any(), anyInt(), any(), any(), any(), any(), anyBoolean(), any(), any(), any(), anyBoolean(), any());
|
||||
}
|
||||
|
||||
@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);
|
||||
List<Instance> instances = stubLaunches("i-1", "i-2");
|
||||
instances.get(0).setKeyName("key-1");
|
||||
StackResource r = resource("Server");
|
||||
String previous = "{\"ImageId\": \"ami-1\", \"KeyName\": \"key-1\", "
|
||||
+ "\"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}";
|
||||
provisioner.provision(r, props(previous), ctx(null));
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
|
||||
provisioner.provision(r, props("{\"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}"),
|
||||
ctx("i-1", props(previous)));
|
||||
|
||||
assertEquals("i-2", r.getPhysicalId());
|
||||
assertTrue(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@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);
|
||||
Instance i1 = reusable("i-1");
|
||||
i1.setKeyName("key-1");
|
||||
StackResource r = resource("Server");
|
||||
|
||||
provisioner.provision(r, props("{\"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}"),
|
||||
ctx("i-1", props("{\"ImageId\": \"ami-1\", \"KeyName\": \"key-1\", "
|
||||
+ "\"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}")));
|
||||
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
}
|
||||
|
||||
@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);
|
||||
Instance i1 = stubLaunches("i-1", "i-2").get(0);
|
||||
StackResource r = resource("Server");
|
||||
String previous = "{\"ImageId\": \"ami-1\", "
|
||||
+ "\"MetadataOptions\": {\"HttpTokens\": \"optional\", \"HttpPutResponseHopLimit\": 3}, "
|
||||
+ "\"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}";
|
||||
provisioner.provision(r, props(previous), ctx(null));
|
||||
LaunchTemplateData.MetadataOptions applied = LaunchTemplateData.MetadataOptions.launchDefaults();
|
||||
applied.setHttpTokens("optional");
|
||||
applied.setHttpPutResponseHopLimit(3);
|
||||
i1.setMetadataOptions(applied);
|
||||
|
||||
provisioner.provision(r, props("{\"LaunchTemplate\": {\"LaunchTemplateId\": \"lt-1\"}}"),
|
||||
ctx("i-1", props(previous)));
|
||||
|
||||
assertEquals("i-1", r.getPhysicalId());
|
||||
assertFalse(provisioner.hasReplacementUpdate(r));
|
||||
ArgumentCaptor<LaunchTemplateData.MetadataOptions> modified =
|
||||
ArgumentCaptor.forClass(LaunchTemplateData.MetadataOptions.class);
|
||||
verify(ec2).modifyInstanceMetadataOptions(eq("us-east-1"), eq("i-1"), modified.capture());
|
||||
assertEquals("required", modified.getValue().getHttpTokens());
|
||||
assertEquals(1, modified.getValue().getHttpPutResponseHopLimit());
|
||||
}
|
||||
|
||||
@Test
|
||||
void aStoppedInstanceGetsItsUserDataRewrittenWithoutARestart() throws Exception {
|
||||
Instance i1 = reusable("i-1");
|
||||
@@ -1302,6 +1547,10 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
}
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId) {
|
||||
return ctx(priorPhysicalId, null);
|
||||
}
|
||||
|
||||
private ProvisionContext ctx(String priorPhysicalId, JsonNode priorProperties) {
|
||||
CloudFormationTemplateEngine engine = mock(CloudFormationTemplateEngine.class);
|
||||
when(engine.resolve(any())).thenAnswer(inv -> {
|
||||
JsonNode node = inv.getArgument(0);
|
||||
@@ -1309,7 +1558,8 @@ class Ec2InstanceCfnProvisionerTest {
|
||||
});
|
||||
when(engine.resolveNode(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
when(engine.omitNoValue(any())).thenAnswer(inv -> inv.getArgument(0));
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId);
|
||||
return new ProvisionContext(engine, "us-east-1", "000000000000", "my-stack", priorPhysicalId,
|
||||
event -> {}, priorProperties);
|
||||
}
|
||||
|
||||
private JsonNode props(String json) throws Exception {
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
AWS::ApiGatewayV2::Stage ApiId create-only a drop fails: the stage is not found
|
||||
AWS::ApiGatewayV2::Stage AutoDeploy default:false
|
||||
AWS::ApiGatewayV2::Stage StageName keep:the stage is found by its physical id
|
||||
AWS::ApiGatewayV2::Stage StageVariables clear an empty map replaces them
|
||||
AWS::AppSync::ApiKey ApiId create-only
|
||||
AWS::AppSync::ApiKey Description clear
|
||||
AWS::AppSync::ApiKey Expires keep:the update parses a date, null is refused
|
||||
@@ -63,6 +67,19 @@ AWS::AppSync::Resolver Runtime clear
|
||||
AWS::AppSync::Resolver SyncConfig clear
|
||||
AWS::AppSync::Resolver TypeName create-only
|
||||
AWS::EC2::EIP Tags clear
|
||||
AWS::EC2::Instance AvailabilityZone create-only a drop differs from the declared value, so the instance is replaced
|
||||
AWS::EC2::Instance IamInstanceProfile clear the profile is disassociated
|
||||
AWS::EC2::Instance ImageId create-only a drop is read as no preference and the instance is kept, unless a launch template still supplies a different image, which replaces it
|
||||
AWS::EC2::Instance InstanceType default:t3.micro when no launch template supplies a type
|
||||
AWS::EC2::Instance KeyName create-only a drop is read as no preference and the instance is kept, unless a launch template still supplies a different key, which replaces it
|
||||
AWS::EC2::Instance LaunchTemplate keep:the instance is kept, and the instance type and the MetadataOptions members the template supplied go back to their defaults
|
||||
AWS::EC2::Instance MetadataOptions default:launch defaults, member by member a member the launch template still supplies takes the template's value
|
||||
AWS::EC2::Instance NetworkInterfaces keep:read only when an instance launches
|
||||
AWS::EC2::Instance PrivateIpAddress create-only a drop differs from the declared value, so the instance is replaced
|
||||
AWS::EC2::Instance SecurityGroupIds keep:only a declared set is applied
|
||||
AWS::EC2::Instance SubnetId create-only a drop is read as no preference and the instance is kept
|
||||
AWS::EC2::Instance Tags clear only the keys the stack wrote
|
||||
AWS::EC2::Instance UserData clear a running instance is stopped for the rewrite and started again
|
||||
AWS::EC2::InternetGateway Tags clear
|
||||
AWS::EC2::NatGateway AllocationId create-only a drop is refused for a public gateway
|
||||
AWS::EC2::NatGateway AvailabilityMode create-only a drop is accepted and skipped
|
||||
|
||||
|
Reference in new issue
Block a user