Skip to content

Commit d84d4b4

Browse files
committed
update ecr push to accept sha
1 parent 5f12766 commit d84d4b4

1 file changed

Lines changed: 23 additions & 11 deletions

File tree

terraform/tig_ecr.tf

Lines changed: 23 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,44 @@
11
data "aws_ecr_authorization_token" "token" {}
22

33
locals {
4-
lambda_container_image_uri_split = split("/", var.lambda_container_image_uri)
5-
ecr_image_name_and_tag = split(":", element(local.lambda_container_image_uri_split, length(local.lambda_container_image_uri_split) - 1))
6-
ecr_image_name = "${local.environment}-${element(local.ecr_image_name_and_tag, 0)}"
7-
ecr_image_tag = element(local.ecr_image_name_and_tag, 1)
4+
# This regex splits the URI into: [0] registry/path, [1] name, [2] separator (: or @), and [3] tag or sha
5+
# Example: 123.dkr.ecr.url/my-image@sha256:12345...
6+
uri_parts = regex("^(.*)/(.*)([:@])(.*)$", var.lambda_container_image_uri)
7+
8+
raw_image_name = local.uri_parts[1]
9+
separator = local.uri_parts[2]
10+
image_version = local.uri_parts[3]
11+
12+
ecr_image_name = "${local.environment}-${local.raw_image_name}"
13+
14+
# For ECR, we usually want to push as a tag even if the source was a SHA.
15+
# If the source was a SHA, we'll strip 'sha256:' to use a clean string as a tag.
16+
safe_tag = replace(local.image_version, "sha256:", "")
817
}
918

10-
resource aws_ecr_repository "lambda-image-repo" {
19+
resource "aws_ecr_repository" "lambda-image-repo" {
1120
name = local.ecr_image_name
1221
tags = var.tags
1322
}
1423

1524
resource "null_resource" "upload_ecr_image" {
16-
1725
triggers = {
18-
always_run = timestamp()
26+
# It's better to trigger on the URI change rather than every single run
27+
image_uri = var.lambda_container_image_uri
1928
}
2029

2130
provisioner "local-exec" {
2231
interpreter = ["/bin/bash", "-e", "-c"]
2332
command = <<EOF
2433
# Docker login
25-
echo ${data.aws_ecr_authorization_token.token.password} | docker login -u AWS --password-stdin ${data.aws_ecr_authorization_token.token.proxy_endpoint} | true
26-
# Docker image upload
34+
echo ${data.aws_ecr_authorization_token.token.password} | docker login -u AWS --password-stdin ${data.aws_ecr_authorization_token.token.proxy_endpoint}
35+
36+
# Pull the source (works for both tags and SHAs)
2737
docker pull --platform=linux/arm64 ${var.lambda_container_image_uri}
28-
docker tag ${var.lambda_container_image_uri} ${aws_ecr_repository.lambda-image-repo.repository_url}:${local.ecr_image_tag}
29-
docker push ${aws_ecr_repository.lambda-image-repo.repository_url}:${local.ecr_image_tag}
38+
39+
# Tag and Push to the new repo
40+
docker tag ${var.lambda_container_image_uri} ${aws_ecr_repository.lambda-image-repo.repository_url}:${local.safe_tag}
41+
docker push ${aws_ecr_repository.lambda-image-repo.repository_url}:${local.safe_tag}
3042
EOF
3143
}
3244
}

0 commit comments

Comments
 (0)