|
| 1 | +""" |
| 2 | +Python script to log in to the Dev Prod ECR registry. |
| 3 | +""" |
| 4 | + |
| 5 | +import base64 |
| 6 | +import os |
| 7 | +import shlex |
| 8 | +import shutil |
| 9 | +import subprocess |
| 10 | + |
| 11 | +import boto3 |
| 12 | + |
| 13 | +registry = os.environ["ECR_REGISTRY"] |
| 14 | +account = registry.split(".")[0] |
| 15 | +if "CI" in os.environ: |
| 16 | + sts_client = boto3.client("sts", region_name=os.environ["AWS_REGION"]) |
| 17 | + resp = sts_client.assume_role( |
| 18 | + RoleArn=os.environ["AWS_ROLE_ARN"], |
| 19 | + RoleSessionName=f"{account}-test", |
| 20 | + ExternalId=os.environ["AWS_EXTERNAL_ID"], |
| 21 | + ) |
| 22 | + creds = resp["Credentials"] |
| 23 | + sts_client.close() |
| 24 | +else: |
| 25 | + creds = dict(AccessKeyId=None, SecretAccessKey=None, SessionToken=None) |
| 26 | + |
| 27 | +ecr_client = boto3.client( |
| 28 | + "ecr", |
| 29 | + aws_access_key_id=creds["AccessKeyId"], |
| 30 | + aws_secret_access_key=creds["SecretAccessKey"], |
| 31 | + aws_session_token=creds["SessionToken"], |
| 32 | + region_name=os.environ["AWS_REGION"], |
| 33 | +) |
| 34 | +resp = ecr_client.get_authorization_token(registryIds=[account]) |
| 35 | +ecr_client.close() |
| 36 | + |
| 37 | +token = resp["authorizationData"][0]["authorizationToken"] |
| 38 | +_, _, token = base64.b64decode(token).partition(b":") |
| 39 | + |
| 40 | +docker = shutil.which("docker") or shutil.which("podman") |
| 41 | +if "podman" in docker: |
| 42 | + docker = f"sudo {docker}" |
| 43 | + |
| 44 | +cmd = f"{docker} login --username AWS --password-stdin {registry}" |
| 45 | +proc = subprocess.Popen( |
| 46 | + shlex.split(cmd), |
| 47 | + stdout=subprocess.PIPE, |
| 48 | + stdin=subprocess.PIPE, |
| 49 | + stderr=subprocess.PIPE, |
| 50 | +) |
| 51 | +stdout, stderr = proc.communicate(token) |
| 52 | +if stdout: |
| 53 | + print(stdout.decode("utf-8").strip()) |
| 54 | +if stderr: |
| 55 | + print(stderr.decode("utf-8").strip()) |
0 commit comments