Shashank S
Shashank S

Reputation: 61

AWS lambda: how can I run aws cli commands in lambda

I want to run aws cli commands from lambda

I have a Pull request event that triggers when the approval state changes and whenever it's changed I need to run an aws CLI command from lambda but the lambda function says aws not found! how do I get the status on PR's in my lambda function?

Upvotes: 2

Views: 4586

Answers (2)

pbsladek
pbsladek

Reputation: 716

Create a lambda function, build an image to ecr, have the lambda function reference the image, and then test the image with an event. This is a good way to run things like aws s3 sync.

Testing local:

docker run -p 9000:8080 repo/lambda:latest
curl -XPOST "http://localhost:9000/2015-03-31/functions/function/invocations" -d '{}'

app.py

import subprocess
import logging

logger = logging.getLogger()
logger.setLevel(logging.INFO)


def run_command(command):
    try:
        logger.info('Running shell command: "{}"'.format(command))
        result = subprocess.run(command, stdout=subprocess.PIPE, shell=True)
        logger.info(
            "Command output:\n---\n{}\n---".format(result.stdout.decode("UTF-8"))
        )
    except Exception as e:
        logger.error("Exception: {}".format(e))
        return False

    return True


def handler(event, context):
    run_command('aws s3 ls')

Dockerfile (awscliv2, can make requirements file if needed)

FROM public.ecr.aws/lambda/python:3.9

RUN yum -y install unzip

RUN curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64-2.0.30.zip" -o "awscliv2.zip" && \
  unzip awscliv2.zip && \
  ./aws/install

COPY app.py ${LAMBDA_TASK_ROOT}

COPY requirements.txt  .
RUN  pip3 install -r requirements.txt --target "${LAMBDA_TASK_ROOT}"

CMD [ "app.handler" ]

Makefile (make all - login,build,tag,push to ecr repo)

ROOT:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
IMAGE_NAME:=repo/lambda

ECR_TAG:="latest"
AWS_REGION:="us-east-1"
AWS_ACCOUNT_ID:="xxxxxxxxx"
REGISTRY_URI=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${IMAGE_NAME}
REGISTRY_URI_WITH_TAG=${AWS_ACCOUNT_ID}.dkr.ecr.${AWS_REGION}.amazonaws.com/${IMAGE_NAME}:${ECR_TAG}

# Login to AWS ECR registry (must have docker running)
login:
    aws ecr get-login-password --region ${AWS_REGION} | docker login --username AWS --password-stdin ${REGISTRY_URI}

build:
    docker build --no-cache -t ${IMAGE_NAME}:${ECR_TAG} .

# Tag docker image
tag:
    docker tag ${IMAGE_NAME}:${ECR_TAG} ${REGISTRY_URI_WITH_TAG}

# Push to ECR registry
push:
    docker push ${REGISTRY_URI_WITH_TAG}

# Pull version from ECR registry
pull:
    docker pull ${REGISTRY_URI_WITH_TAG}

# Build docker image and push to AWS ECR registry
all: login build tag push

Upvotes: 4

theherk
theherk

Reputation: 7576

The default lambda environment doesn't provide the awscli. In fact, the idea of using it there is quite awkward. You can call any command the aws cli can via an sdk like boto3 for example, which is provided in that environment.

You can however include binaries in your lambda, if you please, then execute them.

You also consider using a container image for your lambda. You can find information here: https://docs.aws.amazon.com/lambda/latest/dg/images-create.html.

Upvotes: 1

Related Questions