I'm posting an answer here because your question is recent and highly ranked on Google Search at the moment.
First, you need an actual git
binary installed in your runtime. This is mentioned in the GitPython docs:
GitPython needs the git executable to be installed on the system and available in your PATH for most operations. If it is not in your PATH, you can help GitPython find it by setting the GIT_PYTHON_GIT_EXECUTABLE=<path/to/git> environment variable.
Unfortunately, the Python Lambda runtime does not include git
by default. We fix this by using a docker image, then building that during a cdk deploy
.
Dockerfile
FROM public.ecr.aws/lambda/python:3.12
RUN dnf -y install git
COPY requirements.txt .
RUN pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"
WORKDIR ${LAMBDA_TASK_ROOT}
COPY *.py .
CMD [ "index.handler" ]
Your lambda code will be called index.py
import shutil
from git import Repo
from aws_lambda_powertools import Logger
logger = Logger()
REPOSITORY_URL = "https://github.com/gitpython-developers/QuickStartTutorialFiles.git"
LOCAL_CODE_DIRECTORY = "/tmp/repo"
@logger.inject_lambda_context(log_event=True)
def handler(event, context):
logger.info("Cloning repository...")
repo = Repo.clone_from(
url=REPOSITORY_URL,
to_path=LOCAL_CODE_DIRECTORY,
allow_unsafe_protocols=True,
allow_unsafe_options=True,
)
logger.info("Repository cloned!")
# Get the last 10 commits and print them.
commits = repo.iter_commits("main", max_count=10)
for commit in commits:
logger.info(
f"{commit.message} - {commit.author} - {commit.authored_date}"
)
tree = repo.head.commit.tree
# Print files to confirm it works and we have the right repo.
files_and_dirs = [(entry, entry.name, entry.type) for entry in tree]
logger.info(files_and_dirs)
# Docs here: https://gitpython.readthedocs.io/en/stable/quickstart.html#git-repo
shutil.rmtree(LOCAL_CODE_DIRECTORY)
Deploy all this with CDK code:
from aws_cdk.aws_lambda import (
Architecture,
DockerImageFunction,
DockerImageCode
)
from aws_cdk import Duration
_lambda = DockerImageFunction(
self,
"SourceCodeThingy",
description="Updates the source code repository with some cool changes.",
code=DockerImageCode.from_image_asset(
directory='path/to/your/function/code'
),
memory_size=128,
architecture=Architecture.X86_64,
retry_attempts=1,
timeout=Duration.seconds(15)
)