Skip to content

Instantly share code, notes, and snippets.

@malcolmgreaves
Created April 14, 2023 17:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malcolmgreaves/1c65e0101f4a365d528475c134b61067 to your computer and use it in GitHub Desktop.
Save malcolmgreaves/1c65e0101f4a365d528475c134b61067 to your computer and use it in GitHub Desktop.
Get the image tags for an AWS ECR repo that exist within a branch. Prints them to STDOUT in descending order of pushed date.
"""
Use as:
REPO='ecr-repo-name' BRANCH='main' python git_branch_commits_in_ecr_repo.py
You can pipe this to `cut -f1 -s` to get the commits only. Or `-f2` to get the pushed by date only.
These values are separated by a tab (`"\t"`).
"""
import json
import os
import subprocess
import tempfile
from datetime import datetime
from typing import List, NamedTuple
class DatedTag(NamedTuple):
image_tag: str
pushed_at: datetime
def ecr_tags_in_branch(repo: str, branch: str) -> List[DatedTag]:
# get commits
with tempfile.NamedTemporaryFile("wt") as tf:
tf.write("#!/usr/bin/env bash\n")
tf.write(
"git log %s | grep --color=auto --exclude-dir={.bzr,CVS,.git,.hg,.svn,.idea,.tox} '^commit ' | cut -f2 -d' '\n"
% branch
)
tf.flush()
os.system(f"chmod +x {tf.name}")
commits_b = subprocess.check_output([tf.name])
commits: List[str] = [
c.strip() for c in commits_b.decode("utf8").split("\n") if len(c.strip()) > 0
]
# describe the ECR repository
json_ecr_images = subprocess.check_output(
(
"aws",
"ecr",
"describe-images",
f"--repository-name={repo}",
)
).decode("utf8")
# get the image tags that appear in the branch & get their push dates
ecr_tag_in_master: List[DatedTag] = []
image_details = json.loads(json_ecr_images)["imageDetails"]
for imgd in image_details:
pushed_date = datetime.fromisoformat(imgd["imagePushedAt"])
for image_tag in imgd["imageTags"]:
for c in commits:
if c in image_tag:
ecr_tag_in_master.append(DatedTag(image_tag, pushed_date))
# most recent pushed tags first
ecr_tag_in_master.sort(key=lambda x: x[1], reverse=True)
return ecr_tag_in_master
if __name__ == "__main__":
try:
repo = os.environ["REPO"]
except KeyError:
print("ERROR: need 'REPO' env var for ECR repository name")
os.exit(1)
branch = os.environ.get("BRANCH", "master")
for c, d in ecr_tags_in_branch(repo, branch):
print(f"{c}\t{d}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment