Created
April 14, 2023 17:37
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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