mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
fix(cloudformation): replace an ECR repository when the engine says its create-only properties changed (#8461)
This commit is contained in:
1 parent
f930634fa8
commit
c1bc65060d
3 files changed
+166
-24
No files matched your search
+88
-23
@@ -24,6 +24,7 @@ import java.util.Set;
|
||||
@ApplicationScoped
|
||||
public class EcrCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
private static final String REPOSITORY = "AWS::ECR::Repository";
|
||||
private static final int REPOSITORY_NAME_MAX_LENGTH = 256;
|
||||
/** What CreateRepository applies when ImageTagMutability is omitted. */
|
||||
private static final String DEFAULT_IMAGE_TAG_MUTABILITY = "MUTABLE";
|
||||
@@ -36,7 +37,7 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner {
|
||||
|
||||
@Override
|
||||
public Set<String> resourceTypes() {
|
||||
return Set.of("AWS::ECR::Repository");
|
||||
return Set.of(REPOSITORY);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -49,12 +50,57 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner {
|
||||
return "floci.services.ecr.enabled";
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean hasReplacementUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.hasReplacement(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String updateCleanupPhysicalId(StackResource resource) {
|
||||
return ReplacementCleanup.cleanupPhysicalId(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UpdateCleanupResult completeUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.complete(resource, (type, id, region) ->
|
||||
CfnDeletes.safeDelete("ECR repository", id,
|
||||
() -> ecrService.deleteRepository(id, null, false, region),
|
||||
"RepositoryNotFoundException"));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void clearUpdate(StackResource resource) {
|
||||
ReplacementCleanup.clear(resource);
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean rollbackUpdate(StackResource resource) {
|
||||
return ReplacementCleanup.rollback(resource, this::delete);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void provision(StackResource r, JsonNode props, ProvisionContext ctx) {
|
||||
if (ctx.isUpdate()) {
|
||||
// Rolling this update back undoes it alone; only ContinueUpdateRollback retries the
|
||||
// delete the last rollback could not make.
|
||||
ReplacementCleanup.endRollbackRetry(r);
|
||||
}
|
||||
Map<String, String> attributesBefore = new HashMap<>(r.getAttributes());
|
||||
// The engine's change decides whether the update replaces the repository: RepositoryName and
|
||||
// EncryptionConfiguration are create-only in the registry. A named repository cannot be
|
||||
// replaced under the same name.
|
||||
boolean replaces = ctx.isUpdate() && ctx.changes(REPOSITORY, props).requiresReplacement();
|
||||
String explicitName = ctx.resolveOptional(props, "RepositoryName");
|
||||
// CDK bootstrap requires lower-case repository names; CFN-generated suffixes can include
|
||||
// upper-case characters. Normalize to satisfy the AWS ECR repository name pattern.
|
||||
String repoName = ctx.stablePhysicalName(ctx.resolveOptional(props, "RepositoryName"),
|
||||
r.getLogicalId(), REPOSITORY_NAME_MAX_LENGTH, true).toLowerCase();
|
||||
// upper-case characters. Normalize to satisfy the AWS ECR repository name pattern. A
|
||||
// replacing update that names nothing gets a fresh generated name, not the prior one.
|
||||
String repoName = (replaces && (explicitName == null || explicitName.isBlank())
|
||||
? ctx.generatePhysicalName(r.getLogicalId(), REPOSITORY_NAME_MAX_LENGTH, true)
|
||||
: ctx.stablePhysicalName(explicitName, r.getLogicalId(), REPOSITORY_NAME_MAX_LENGTH, true))
|
||||
.toLowerCase();
|
||||
if (replaces && ctx.reusesPriorEntity(repoName)) {
|
||||
throw CfnExceptions.customNamedReplacement(repoName);
|
||||
}
|
||||
|
||||
String mutability = ctx.resolveOptional(props, "ImageTagMutability");
|
||||
Map<String, String> tags = parseCfnTags(props != null ? props.get("Tags") : null, ctx);
|
||||
@@ -68,36 +114,55 @@ public class EcrCfnProvisioner implements CfnResourceProvisioner {
|
||||
// reconciled in place; a replacing update derives a different name and creates, and a name
|
||||
// that already belongs to another repository fails the create as on CloudFormation.
|
||||
boolean reusing = ctx.reusesPriorEntity(repoName);
|
||||
// EncryptionConfiguration is create-only, so it is read only when the repository is created.
|
||||
JsonNode encryption = props != null ? props.get("EncryptionConfiguration") : null;
|
||||
Repository repo = reusing
|
||||
? reconcileExisting(repoName, mutability, tags, region)
|
||||
: ecrService.createRepository(repoName, null, mutability, null, null, null, tags, region);
|
||||
: ecrService.createRepository(repoName, null, mutability, null,
|
||||
ctx.resolveOptional(encryption, "EncryptionType"), ctx.resolveOptional(encryption, "KmsKey"),
|
||||
tags, region);
|
||||
if (!reusing) {
|
||||
r.setPhysicalId(repoName);
|
||||
}
|
||||
|
||||
// Both policies are updatable: a template that declares one sets it, and on the update
|
||||
// path a template that no longer declares one deletes it, tolerating "none set".
|
||||
if (lifecyclePolicy != null) {
|
||||
ecrService.putLifecyclePolicy(repoName, null, lifecyclePolicy, region);
|
||||
} else if (reusing) {
|
||||
CfnDeletes.safeDelete("ECR lifecycle policy", repoName,
|
||||
() -> ecrService.deleteLifecyclePolicy(repoName, null, region),
|
||||
"LifecyclePolicyNotFoundException");
|
||||
}
|
||||
String repositoryPolicy = repositoryPolicyText(props, ctx);
|
||||
if (repositoryPolicy != null) {
|
||||
ecrService.setRepositoryPolicy(repoName, null, repositoryPolicy, region);
|
||||
} else if (reusing) {
|
||||
CfnDeletes.safeDelete("ECR repository policy", repoName,
|
||||
() -> ecrService.deleteRepositoryPolicy(repoName, null, region),
|
||||
"RepositoryPolicyNotFoundException");
|
||||
}
|
||||
// A repository this provision created and could not finish setting up is removed, or left
|
||||
// to the create rollback or the next cleanup when that fails too.
|
||||
CfnRollback.guarded(r, ctx, !reusing, () -> ecrService.deleteRepository(repoName, null, true, region),
|
||||
() -> { }, () -> {
|
||||
// Both policies are updatable: a template that declares one sets it, and on the update
|
||||
// path a template that no longer declares one deletes it, tolerating "none set".
|
||||
if (lifecyclePolicy != null) {
|
||||
ecrService.putLifecyclePolicy(repoName, null, lifecyclePolicy, region);
|
||||
} else if (reusing) {
|
||||
CfnDeletes.safeDelete("ECR lifecycle policy", repoName,
|
||||
() -> ecrService.deleteLifecyclePolicy(repoName, null, region),
|
||||
"LifecyclePolicyNotFoundException");
|
||||
}
|
||||
String repositoryPolicy = repositoryPolicyText(props, ctx);
|
||||
if (repositoryPolicy != null) {
|
||||
ecrService.setRepositoryPolicy(repoName, null, repositoryPolicy, region);
|
||||
} else if (reusing) {
|
||||
CfnDeletes.safeDelete("ECR repository policy", repoName,
|
||||
() -> ecrService.deleteRepositoryPolicy(repoName, null, region),
|
||||
"RepositoryPolicyNotFoundException");
|
||||
}
|
||||
});
|
||||
|
||||
r.setPhysicalId(repoName);
|
||||
r.getAttributes().put("Arn", repo.getRepositoryArn());
|
||||
r.getAttributes().put("RepositoryUri", repo.getRepositoryUri());
|
||||
// The repository the prior physical id named is deleted once the update commits, but only
|
||||
// when it is empty: EmptyOnDelete is not read, and an empty-only delete is what AWS does
|
||||
// by default. A create under an existing name fails, so a replacement here is always one
|
||||
// this update created.
|
||||
ReplacementCleanup.record(r, ctx, attributesBefore, replaces && !reusing);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void delete(String resourceType, String physicalId, String region) {
|
||||
ecrService.deleteRepository(physicalId, null, true, region);
|
||||
CfnDeletes.safeDelete("ECR repository", physicalId,
|
||||
() -> ecrService.deleteRepository(physicalId, null, true, region),
|
||||
"RepositoryNotFoundException");
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -11,13 +11,19 @@ import org.junit.jupiter.api.Assumptions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.MethodSource;
|
||||
import software.amazon.awssdk.core.SdkBytes;
|
||||
import software.amazon.awssdk.regions.Region;
|
||||
import software.amazon.awssdk.services.cloudformation.CloudFormationClient;
|
||||
import software.amazon.awssdk.services.cloudformation.model.Parameter;
|
||||
import software.amazon.awssdk.services.ecr.EcrClient;
|
||||
import software.amazon.awssdk.services.ecr.model.RepositoryNotFoundException;
|
||||
import software.amazon.awssdk.services.elasticache.ElastiCacheClient;
|
||||
import software.amazon.awssdk.services.ssm.SsmClient;
|
||||
import software.amazon.awssdk.services.ssm.model.ParameterType;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.HexFormat;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -43,6 +49,7 @@ import static org.junit.jupiter.api.Assertions.assertAll;
|
||||
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.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
/**
|
||||
@@ -164,6 +171,8 @@ class CfnReplacementIntegrationTest {
|
||||
+ " \"Properties\": {\"LogGroupName\": \"repl-dropped-properties\"}}}}",
|
||||
"{\"Resources\": {\"Subject\": {\"Type\": \"AWS::Logs::LogGroup\"}}}",
|
||||
"Subject", "True", true, null),
|
||||
createOnlyRow("ECR repository RepositoryName removed", "", "", "AWS::ECR::Repository",
|
||||
"\"RepositoryName\": \"repl-ecr-named\"", "", "True", false, null),
|
||||
new Row("deployed parameter renamed, same value",
|
||||
locationStack(stringParameter("NameA", HOSTED), "", REF_A, "d"),
|
||||
locationStack(stringParameter("NameB", HOSTED), "", REF_B, "e"),
|
||||
@@ -537,4 +546,73 @@ class CfnReplacementIntegrationTest {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRenamedEcrRepositoryLeavesNoRepositoryUnderTheOldName() throws Exception {
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stack = "repl-ecr-" + suffix;
|
||||
String first = "repl-ecr-a-" + suffix;
|
||||
String second = "repl-ecr-b-" + suffix;
|
||||
try (CloudFormationClient client = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
EcrClient ecr = AwsTestClients.create(EcrClient.builder(), "test", Region.US_EAST_1)) {
|
||||
CfnStackWaits.createStack(client, stack,
|
||||
subjectStack("", "", "AWS::ECR::Repository", "\"RepositoryName\": \"" + first + "\""),
|
||||
"CREATE_COMPLETE");
|
||||
assertEquals(first, ecr.describeRepositories(request -> request.repositoryNames(first))
|
||||
.repositories().getFirst().repositoryName());
|
||||
|
||||
createUpdateChangeSet(client, stack, "rename",
|
||||
subjectStack("", "", "AWS::ECR::Repository", "\"RepositoryName\": \"" + second + "\""));
|
||||
assertEquals(List.of("True"), replacement(client, stack, "rename", "Subject"));
|
||||
executeAndAwaitUpdate(client, stack, "rename");
|
||||
|
||||
assertEquals(second, physicalId(client, stack, "Subject"));
|
||||
assertEquals(second, ecr.describeRepositories(request -> request.repositoryNames(second))
|
||||
.repositories().getFirst().repositoryName());
|
||||
assertThrows(RepositoryNotFoundException.class,
|
||||
() -> ecr.describeRepositories(request -> request.repositoryNames(first)),
|
||||
"the old repository is deleted once the update completes");
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
void aRenamedEcrRepositoryThatStillHoldsAnImageIsKept() throws Exception {
|
||||
Assumptions.assumeTrue(DockerAvailability.isAvailable(), "Docker is required for the registry data plane");
|
||||
String suffix = Long.toString(System.nanoTime(), 36);
|
||||
String stack = "repl-ecr-full-" + suffix;
|
||||
String first = "repl-ecr-full-a-" + suffix;
|
||||
String second = "repl-ecr-full-b-" + suffix;
|
||||
byte[] config = "{\"architecture\":\"amd64\",\"os\":\"linux\"}".getBytes(StandardCharsets.UTF_8);
|
||||
String configDigest = "sha256:" + HexFormat.of().formatHex(
|
||||
MessageDigest.getInstance("SHA-256").digest(config));
|
||||
String manifest = "{\"schemaVersion\": 2, \"mediaType\": \"application/vnd.docker.distribution.manifest.v2+json\","
|
||||
+ " \"config\": {\"mediaType\": \"application/vnd.docker.container.image.v1+json\", \"size\": "
|
||||
+ config.length + ", \"digest\": \"" + configDigest + "\"}, \"layers\": []}";
|
||||
try (CloudFormationClient client = AwsTestClients.create(
|
||||
CloudFormationClient.builder(), "test", Region.US_EAST_1);
|
||||
EcrClient ecr = AwsTestClients.create(EcrClient.builder(), "test", Region.US_EAST_1)) {
|
||||
CfnStackWaits.createStack(client, stack,
|
||||
subjectStack("", "", "AWS::ECR::Repository", "\"RepositoryName\": \"" + first + "\""),
|
||||
"CREATE_COMPLETE");
|
||||
String upload = ecr.initiateLayerUpload(request -> request.repositoryName(first)).uploadId();
|
||||
ecr.uploadLayerPart(request -> request.repositoryName(first).uploadId(upload)
|
||||
.partFirstByte(0L).partLastByte((long) config.length - 1).layerPartBlob(SdkBytes.fromByteArray(config)));
|
||||
ecr.completeLayerUpload(request -> request.repositoryName(first).uploadId(upload)
|
||||
.layerDigests(configDigest));
|
||||
ecr.putImage(request -> request.repositoryName(first).imageManifest(manifest).imageTag("v1"));
|
||||
|
||||
createUpdateChangeSet(client, stack, "rename",
|
||||
subjectStack("", "", "AWS::ECR::Repository", "\"RepositoryName\": \"" + second + "\""));
|
||||
executeAndAwaitUpdate(client, stack, "rename");
|
||||
|
||||
assertEquals(second, physicalId(client, stack, "Subject"));
|
||||
assertEquals(1, ecr.listImages(request -> request.repositoryName(first)).imageIds().size(),
|
||||
"the old repository still holds its image: ECR refuses to delete a non-empty repository");
|
||||
} finally {
|
||||
CfnStackWaits.deleteStack(stack);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -253,7 +253,6 @@ AWS::EC2::VPCEndpoint ServiceNetworkArn accepted and ignored
|
||||
AWS::EC2::VPCEndpoint ServiceRegion accepted and ignored
|
||||
AWS::EC2::VPCEndpoint Tags accepted and ignored
|
||||
AWS::ECR::Repository EmptyOnDelete accepted and ignored
|
||||
AWS::ECR::Repository EncryptionConfiguration accepted and ignored
|
||||
AWS::ECR::Repository ImageScanningConfiguration accepted and ignored
|
||||
AWS::ECR::Repository ImageTagMutabilityExclusionFilters accepted and ignored
|
||||
AWS::ECS::CapacityProvider ClusterName accepted and ignored
|
||||
|
||||
|
Reference in new issue
Block a user