mirror of
https://github.com/floci-io/floci.git
synced 2026-11-28 16:11:48 -05:00
fix(cloudformation): evaluate conditions with intrinsics, require parameter values (#5737)
* fix(cloudformation): require a value for every declared parameter CreateStack, UpdateStack and CreateChangeSet accepted a template that declares a parameter with no Default when the request gave it no value. The stack deployed with the parameter unset: a condition compared it as an empty string, and a Ref resolved to the parameter's own name. Such a request now fails with ValidationError "Parameters: [Env] must have values", naming every such parameter in declaration order, before the SAM transform and the dependency preflight run and before any stack state changes. An empty value counts as a value. An update does not carry values over, so it needs a value or UsePreviousValue, which keeps the deployed one, for each parameter without a Default. UsePreviousValue on a parameter with no deployed value passes none, rather than an empty string. A request its stack refuses outright, an update of a stack that is missing or cannot be updated or a create over a name in use, still gets that refusal. A parameter that an AWS::Include defines, which only execution merges, is not checked up front. The same check refuses CreateStackSet and UpdateStackSet, before the stack set changes or an operation is recorded. UpdateStackSet resolves UsePreviousValue against the previous template's Defaults too, since a stack set keeps only the values it was given. A nested stack resource whose Parameters leave a child parameter without a value fails, before the child is created or changed. Those Parameters now resolve as a property value: an Fn::If may choose the whole map, and an AWS::NoValue value passes nothing. A CreateStackInstances whose targets cannot be resolved, or whose change set is refused, now ends its operation FAILED. Left RUNNING, it refused every later operation on the stack set. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): evaluate conditions through the template engine Conditions resolved only a bare Ref, and only to a parameter, the account or the region. Every function other than that Ref compared as an empty string inside Fn::Equals: Fn::FindInMap, a Ref to AWS::StackName or AWS::StackId, Fn::Join. A condition on a mapped value or on the stack's own name was decided wrongly, so the wrong resources, or none, were created. The operands now resolve through the template engine, with the template's Mappings and the stack's name and id. The change-set preview and the dependency preflight evaluate against the stack too: the live one an update targets, or the name a create takes, whose id does not exist yet. An operand the engine cannot resolve compares as an empty string, as every function did before, so a template that evaluated then still does. A declared parameter that a stack stored by an older Floci lacks still compares as an empty string, and AWS::NotificationARNs is the empty list, now in properties and outputs too. CloudFormation does not allow Fn::ImportValue in a condition, so a template being deployed with one there is refused with "Template error: Cannot use Fn::ImportValue in Conditions.", also in an operand that evaluation never reaches. A SAM template's change set, or its stack, fails with that reason instead. A stored template compares the import as an empty string, so it never blocks an update that supplies a new template; UsePreviousTemplate checks the stored one as it would a new one. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * fix(cloudformation): check a create's dependencies with its stack id A create's dependency preflight evaluated AWS::StackId as an empty string while the execution used the stack's id, so a dependency on a resource whose condition reads the stack id could pass the preflight and then fail the deploy, or the other way round. A create over a name in use was checked against the stack holding the name instead, and could get a dependency error rather than AlreadyExistsException. createChangeSet now allocates the new stack's id before the preflight and creates the stack with it, so the preflight, the change-set preview and the execution evaluate the same id. An update, or a create that attaches to a REVIEW_IN_PROGRESS placeholder, is checked against that stack as before, and a create over a name in use is checked as the new stack it asks for. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(cloudformation): place the parameter check before dependency checks The parameter section said template errors such as a dependency cycle come first, but createChangeSet checks the parameter values before the dependency checks, which evaluate conditions that read those values. Say so, and keep the stack's own refusal ahead of both. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(cloudformation): order the stack's refusal after dependency errors The previous commit said the stack's own refusal comes ahead of both the parameter check and the dependency checks. It comes ahead of the parameter check only: a request its stack refuses still gets a template's dependency error first, as on main. Say so, and re-wrap the conditions paragraph. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * docs(cloudformation): say parameter values are checked before dependency errors The parameter section still read as if a template's dependency errors came first. createChangeSet checks the parameter values before the dependency checks, which evaluate conditions that read the values, so a template with a cycle and a missing value gets the parameter error. Say that, and that a stack's own refusal replaces the parameter error but still follows a dependency error. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * test(cloudformation): pin a missing value ahead of a dependency cycle A template with both a DependsOn cycle and a parameter without a value gets "Parameters: [Env] must have values" and creates no stack. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(cloudformation): name the tolerated parse failures ignored requireParameterValues and parametersWithDefaults return when the template does not parse, as intended: there is nothing to check or to add, and the preflight and the execution report the parse error. Name the caught exception ignored and say why, as AGENTS.md asks. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> * refactor(cloudformation): say only execution reports a parse failure The comment on the ignored parse failure in requireParameterValues said the preflight reports it too. The dependency preflight skips a template that does not parse; only executing the change set reports the error. Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com> --------- Signed-off-by: Jackson Price <59149601+jprice8@users.noreply.github.com>
This commit is contained in:
1 parent
8eddae4ed6
commit
ad8fba7f45
12 files changed
+1880
-92
No files matched your search
+130
@@ -0,0 +1,130 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.s3.S3Client;
|
||||
import software.amazon.awssdk.services.s3.model.NoSuchBucketException;
|
||||
import software.amazon.awssdk.services.sqs.SqsClient;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@DisplayName("CloudFormation conditions with intrinsic operands")
|
||||
class CloudFormationConditionsTest {
|
||||
|
||||
private static CloudFormationClient cfn;
|
||||
private static S3Client s3;
|
||||
private static SqsClient sqs;
|
||||
private String stackName;
|
||||
|
||||
@BeforeAll
|
||||
static void clients() {
|
||||
cfn = TestFixtures.cloudFormationClient();
|
||||
s3 = TestFixtures.s3Client();
|
||||
sqs = TestFixtures.sqsClient();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
stackName = TestFixtures.uniqueName("compat-cfn-cond");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() throws InterruptedException {
|
||||
// Also when the stack was refused: DeleteStack of a name with no stack does nothing.
|
||||
cfn.deleteStack(r -> r.stackName(stackName));
|
||||
TestFixtures.await(() -> {
|
||||
try {
|
||||
List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks();
|
||||
return stacks.isEmpty() || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString());
|
||||
} catch (CloudFormationException e) {
|
||||
return e.getMessage().contains("does not exist");
|
||||
}
|
||||
}, stackName, "deleted", TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L,
|
||||
TestFixtures.isRealAws() ? 5_000 : 100);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void closeClients() {
|
||||
cfn.close();
|
||||
s3.close();
|
||||
sqs.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Fn::FindInMap inside Fn::Equals compares the mapped value")
|
||||
void mappedConditionSelectsTheBucketName() throws InterruptedException {
|
||||
String region = TestFixtures.region().id();
|
||||
String prefix = stackName + "-";
|
||||
createStack("""
|
||||
{
|
||||
"Mappings": {"Locations": {"%1$s": {"Code": "false"}}},
|
||||
"Conditions": {"UseCode": {"Fn::Not": [{"Fn::Equals": [
|
||||
{"Fn::FindInMap": ["Locations", {"Ref": "AWS::Region"}, "Code"]}, "false"]}]}},
|
||||
"Resources": {"Bucket": {"Type": "AWS::S3::Bucket", "Properties": {"BucketName":
|
||||
{"Fn::Join": ["", ["%2$s", {"Fn::If": ["UseCode",
|
||||
{"Fn::FindInMap": ["Locations", {"Ref": "AWS::Region"}, "Code"]},
|
||||
{"Ref": "AWS::Region"}]}]]}}}}
|
||||
}
|
||||
""".formatted(region, prefix));
|
||||
|
||||
s3.headBucket(r -> r.bucket(prefix + region));
|
||||
assertThatThrownBy(() -> s3.headBucket(r -> r.bucket(prefix + "false")))
|
||||
.isInstanceOf(NoSuchBucketException.class);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Ref AWS::StackName inside Fn::Equals is the stack's own name")
|
||||
void stackNameConditionCreatesTheResource() throws InterruptedException {
|
||||
createStack("""
|
||||
{
|
||||
"Conditions": {"IsThisStack": {"Fn::Equals": [{"Ref": "AWS::StackName"}, "%1$s"]}},
|
||||
"Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsThisStack",
|
||||
"Properties": {"QueueName": "%1$s"}}}
|
||||
}
|
||||
""".formatted(stackName));
|
||||
|
||||
assertThat(sqs.getQueueUrl(r -> r.queueName(stackName)).queueUrl()).endsWith("/" + stackName);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Fn::ImportValue inside a condition is a template error")
|
||||
void importValueInAConditionIsRefused() {
|
||||
assertThatThrownBy(() -> cfn.createStack(r -> r.stackName(stackName).templateBody("""
|
||||
{
|
||||
"Conditions": {"IsOn": {"Fn::Equals": [{"Fn::ImportValue": "%s-export"}, "on"]}},
|
||||
"Resources": {"Queue": {"Type": "AWS::SQS::Queue", "Condition": "IsOn"}}
|
||||
}
|
||||
""".formatted(stackName))))
|
||||
.isInstanceOfSatisfying(CloudFormationException.class, e -> {
|
||||
assertThat(e.statusCode()).isEqualTo(400);
|
||||
assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError");
|
||||
assertThat(e.awsErrorDetails().errorMessage()).contains("Fn::ImportValue");
|
||||
});
|
||||
assertThatThrownBy(() -> cfn.describeStacks(r -> r.stackName(stackName)))
|
||||
.isInstanceOf(CloudFormationException.class)
|
||||
.hasMessageContaining("does not exist");
|
||||
}
|
||||
|
||||
private void createStack(String template) throws InterruptedException {
|
||||
cfn.createStack(r -> r.stackName(stackName).templateBody(template));
|
||||
TestFixtures.await(() -> {
|
||||
Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);
|
||||
String status = stack.stackStatusAsString();
|
||||
if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {
|
||||
throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());
|
||||
}
|
||||
return "CREATE_COMPLETE".equals(status);
|
||||
}, stackName, "CREATE_COMPLETE", TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L,
|
||||
TestFixtures.isRealAws() ? 5_000 : 100);
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package com.floci.test;
|
||||
|
||||
import org.junit.jupiter.api.AfterAll;
|
||||
import org.junit.jupiter.api.AfterEach;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.CloudFormationException;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Parameter;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Stack;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@DisplayName("CloudFormation parameters without a value")
|
||||
class CloudFormationParameterValuesTest {
|
||||
|
||||
private static final String TEMPLATE = """
|
||||
{
|
||||
"Parameters": {"Env": {"Type": "String"}},
|
||||
"Resources": {
|
||||
"Param": {
|
||||
"Type": "AWS::SSM::Parameter",
|
||||
"Properties": {"Name": {"Fn::Sub": "/${AWS::StackName}"}, "Type": "String",
|
||||
"Value": {"Ref": "Env"}, "Description": "%s"}
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
private static CloudFormationClient cfn;
|
||||
private static SsmClient ssm;
|
||||
private String stackName;
|
||||
|
||||
@BeforeAll
|
||||
static void clients() {
|
||||
cfn = TestFixtures.cloudFormationClient();
|
||||
ssm = TestFixtures.ssmClient();
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void setup() {
|
||||
stackName = TestFixtures.uniqueName("compat-cfn-param-values");
|
||||
}
|
||||
|
||||
@AfterEach
|
||||
void cleanup() throws InterruptedException {
|
||||
// Also when the stack was refused: DeleteStack of a name with no stack does nothing.
|
||||
cfn.deleteStack(r -> r.stackName(stackName));
|
||||
TestFixtures.await(() -> {
|
||||
try {
|
||||
List<Stack> stacks = cfn.describeStacks(r -> r.stackName(stackName)).stacks();
|
||||
return stacks.isEmpty() || "DELETE_COMPLETE".equals(stacks.get(0).stackStatusAsString());
|
||||
} catch (CloudFormationException e) {
|
||||
return e.getMessage().contains("does not exist");
|
||||
}
|
||||
}, stackName, "deleted", TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L,
|
||||
TestFixtures.isRealAws() ? 5_000 : 100);
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void closeClients() {
|
||||
cfn.close();
|
||||
ssm.close();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("CreateStack refuses a parameter with no value and no Default, and creates nothing")
|
||||
void createStackRefusesAParameterWithoutAValue() {
|
||||
assertThatThrownBy(() -> cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE.formatted("one"))))
|
||||
.isInstanceOfSatisfying(CloudFormationException.class, e -> {
|
||||
assertThat(e.statusCode()).isEqualTo(400);
|
||||
assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError");
|
||||
assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("Parameters: [Env] must have values");
|
||||
});
|
||||
assertThatThrownBy(() -> cfn.describeStacks(r -> r.stackName(stackName)))
|
||||
.isInstanceOf(CloudFormationException.class)
|
||||
.hasMessageContaining("does not exist");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("UpdateStack needs the value again, or UsePreviousValue to keep the deployed one")
|
||||
void updateStackNeedsAValueOrUsePreviousValue() throws InterruptedException {
|
||||
cfn.createStack(r -> r.stackName(stackName).templateBody(TEMPLATE.formatted("one"))
|
||||
.parameters(Parameter.builder().parameterKey("Env").parameterValue("first").build()));
|
||||
awaitStatus("CREATE_COMPLETE");
|
||||
|
||||
assertThatThrownBy(() -> cfn.updateStack(r -> r.stackName(stackName).templateBody(TEMPLATE.formatted("two"))))
|
||||
.isInstanceOfSatisfying(CloudFormationException.class, e -> {
|
||||
assertThat(e.awsErrorDetails().errorCode()).isEqualTo("ValidationError");
|
||||
assertThat(e.awsErrorDetails().errorMessage()).isEqualTo("Parameters: [Env] must have values");
|
||||
});
|
||||
assertThat(cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0).stackStatusAsString())
|
||||
.isEqualTo("CREATE_COMPLETE");
|
||||
|
||||
cfn.updateStack(r -> r.stackName(stackName).templateBody(TEMPLATE.formatted("two"))
|
||||
.parameters(Parameter.builder().parameterKey("Env").usePreviousValue(true).build()));
|
||||
awaitStatus("UPDATE_COMPLETE");
|
||||
assertThat(ssm.getParameter(r -> r.name("/" + stackName)).parameter().value()).isEqualTo("first");
|
||||
}
|
||||
|
||||
private void awaitStatus(String expected) throws InterruptedException {
|
||||
TestFixtures.await(() -> {
|
||||
Stack stack = cfn.describeStacks(r -> r.stackName(stackName)).stacks().get(0);
|
||||
String status = stack.stackStatusAsString();
|
||||
if (status.endsWith("_FAILED") || status.contains("ROLLBACK")) {
|
||||
throw new AssertionError(stackName + " reached " + status + ": " + stack.stackStatusReason());
|
||||
}
|
||||
return expected.equals(status);
|
||||
}, stackName, expected, TestFixtures.isRealAws() ? 600_000_000_000L : 60_000_000_000L,
|
||||
TestFixtures.isRealAws() ? 5_000 : 100);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user