AWS CLI Lambda Commands: Create, Invoke and Update Functions
We run code without servers: an execution role, a function from a zip, invoke, update, environment variables, versions, aliases and logs.
What you'll learn in this chapter
- Create an execution role
- Create and invoke a function
- Update code and configuration
- Versions and aliases
- Read logs and delete
1. The big picture: code on call
Why do we need this?
An electrician on call: you pay only when he comes and works. Lambda runs your code only when an event comes and bills by milliseconds.
What is it?
Commands are in aws lambda: create-function, invoke, update-function-code, update-function-configuration, publish-version, create-alias, add-permission.
How to do it (step by step)
2. Execution role
Why do we need this?
The function needs permission to write logs and call other services.
What is it?
A role that lambda.amazonaws.com can assume, with AWSLambdaBasicExecutionRole for CloudWatch Logs.
How to do it (step by step)
- Create the role.
ROLE=$(aws iam create-role --role-name cli-lambda-role --assume-role-policy-document '{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Service":"lambda.amazonaws.com"},"Action":"sts:AssumeRole"}]}' --query Role.Arn --output text)
aws iam attach-role-policy --role-name cli-lambda-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
echo $ROLE
Expected output:
arn:aws:iam::111122223333:role/cli-lambda-role
3. Create and invoke
Why do we need this?
You want to test small code in seconds, not set up a server.
What is it?
create-function uploads a zip with runtime, handler and role. invoke runs it and writes the response to a file.
How to do it (step by step)
- Write and zip the code.
cat > app.py <<'P'
def handler(event, context):
return {"msg": "hello " + event.get("name", "world")}
P
zip fn.zip app.py
Expected output:
adding: app.py (deflated 12%)
- Create the function.
aws lambda create-function --function-name cli-hello --runtime python3.12 --handler app.handler --role $ROLE --zip-file fileb://fn.zip --query State --output text
aws lambda wait function-active-v2 --function-name cli-hello
Expected output:
Pending
- Invoke it.
aws lambda invoke --function-name cli-hello --cli-binary-format raw-in-base64-out --payload '{"name":"Pune"}' out.json --query StatusCode
cat out.json
Expected output:
200
{"msg": "hello Pune"}
4. Update code and configuration
Why do we need this?
You fixed a bug and need a setting like a table name without changing code.
What is it?
update-function-code uploads a new zip. update-function-configuration changes memory, timeout and environment variables.
How to do it (step by step)
- Upload new code.
zip fn.zip app.py
aws lambda update-function-code --function-name cli-hello --zip-file fileb://fn.zip --query LastUpdateStatus --output text
aws lambda wait function-updated-v2 --function-name cli-hello
Expected output:
InProgress
- Set memory, timeout and an env var.
aws lambda update-function-configuration --function-name cli-hello --memory-size 256 --timeout 10 --environment "Variables={STAGE=dev}" --query "[MemorySize,Timeout]" --output text
Expected output:
256 10
5. Versions, aliases and logs
Why do we need this?
Production must not change when you test. When it fails you need the logs.
What is it?
publish-version freezes the code as 1, 2, 3. An alias like prod points to a version. Logs go to /aws/lambda/NAME.
How to do it (step by step)
- Publish and alias.
V=$(aws lambda publish-version --function-name cli-hello --query Version --output text)
aws lambda create-alias --function-name cli-hello --name prod --function-version $V --query AliasArn --output text
Expected output:
arn:aws:lambda:ap-south-1:111122223333:function:cli-hello:prod
- Tail logs live.
aws logs tail /aws/lambda/cli-hello --since 10m --follow
Expected output:
START RequestId: 3f2a... Version: 1
END RequestId: 3f2a...
REPORT ... Duration: 1.52 ms Billed Duration: 2 ms
- Let S3 call the function.
aws lambda add-permission --function-name cli-hello --statement-id s3invoke --action lambda:InvokeFunction --principal s3.amazonaws.com --source-arn arn:aws:s3:::my-bucket --query Statement --output text
Expected output:
{"Sid":"s3invoke","Effect":"Allow",...}
6. Same action in Python, Node.js, Java, Go, .NET and PHP
Why do we need this?
Scripts start in the CLI. Apps call the same API through an SDK. Knowing both helps you move a tested command into real code.
What is it?
Each CLI command maps to one API call. For example aws lambda invoke --function-name cli-hello out.json maps to the Invoke API.
How to do it (step by step)
Same action (Invoke) from code. Every SDK reads the same profile, region and credentials as the CLI.
| Stack | Code |
|---|---|
| Python (boto3) | boto3.client("lambda").invoke(FunctionName="cli-hello",Payload=b'{"name":"Pune"}')["Payload"].read() |
| Node.js (v3) | await lambda.send(new InvokeCommand({FunctionName:"cli-hello",Payload:Buffer.from('{"name":"Pune"}')})); |
| Java (v2) | lambda.invoke(r -> r.functionName("cli-hello").payload(SdkBytes.fromUtf8String("{}"))); |
| Go (v2) | c.Invoke(ctx, &lambda.InvokeInput{FunctionName: aws.String("cli-hello"), Payload: []byte(`{}`)}) |
| .NET | await lambda.InvokeAsync(new InvokeRequest{FunctionName="cli-hello",Payload="{}"}); |
| PHP | $lambda->invoke(["FunctionName"=>"cli-hello","Payload"=>"{}"]); |
7. Clean up so nothing keeps costing
Why do we need this?
Lab resources left running cost money and can be a security risk.
What is it?
Delete in reverse order: children first, then parents.
How to do it (step by step)
- Delete the function (versions and aliases go too).
aws lambda delete-function --function-name cli-hello
Expected output:
(no output means success)
- Delete the log group.
aws logs delete-log-group --log-group-name /aws/lambda/cli-hello
Expected output:
(no output means success)
- Delete the role.
aws iam detach-role-policy --role-name cli-lambda-role --policy-arn arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
aws iam delete-role --role-name cli-lambda-role
Expected output:
(no output means success)
- Verify.
aws lambda get-function --function-name cli-hello
Expected output:
An error occurred (ResourceNotFoundException) ...
Ravindra Bagale's Tip
In AWS CLI v2, --payload is base64 by default. Add --cli-binary-format raw-in-base64-out or you get an Invalid base64 error.
8. Interview questions and answers
Q. What is an execution role?
The IAM role Lambda assumes to run your code and call AWS.
Q. Version vs alias?
A version is frozen code. An alias is a movable name pointing to a version.
Q. Sync vs async invoke?
RequestResponse waits for the result. Event returns 202 and runs in the background.
Q. Why add-permission?
It is a resource policy letting another service (S3, API Gateway) invoke the function.
Q. Where are logs?
CloudWatch Logs group /aws/lambda/FUNCTION.
Try at home
- Create a function that returns the STAGE env var, change it and invoke again.
- Publish two versions and switch the prod alias between them.
In short
- Role first.
- create-function with a zip.
- Use raw-in-base64-out.
- publish-version + alias.
- aws logs tail.
Practice Tasks
Nashik Vineyards is a wine and farming business in Nashik. Meera Joshi looks after its IT and cloud work. They count money in INR and run their AWS resources in the ap-south-1 Region. In the tasks below you do real jobs for them using what this lesson teaches. All names, account IDs, IP addresses and numbers are made up for practice.
0 / 12
Easy List functions
Why: See which functions exist in this Region.
What to do: List the Lambda functions in ap-south-1.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Invoke a function
Why: Invoke runs the function now and saves its answer in a file.
What to do: Invoke nashikvine-orders-fn and save the response to out.json.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Trust policy for a Lambda role
Why: The trust policy says WHO may take the role.
What to do: Write a trust policy that lets lambda.amazonaws.com assume the role.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Medium Change timeout and memory
Why: More memory also gives more CPU; timeout stops runaway runs.
What to do: Set nashikvine-orders-fn to timeout 30 seconds and memory 512 MB.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Medium Let a function write logs
Why: Without these actions, Lambda logs never appear in CloudWatch.
What to do: Allow logs:CreateLogGroup, logs:CreateLogStream, logs:PutLogEvents on arn:aws:logs:*:*:* only.
- Start with { "Version": "2012-10-17", "Statement": [ ... ] }.
- In each statement write Effect, Action and Resource.
- Give only what the task needs (least privilege).
- Use double quotes and commas correctly. Click Check answer.
Medium Follow logs live
Why: aws logs tail --follow is like tail -f for CloudWatch Logs.
What to do: Follow the log group /aws/lambda/nashikvine-orders-fn live.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Create a Lambda function
Why: Lambda needs the code zip, a runtime, a handler name and an execution role.
What to do: Create function nashikvine-orders-fn: runtime python3.12, handler app.handler, role arn:aws:iam::107079156755:role/lambda-basic, code in function.zip.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Set environment variables
Why: Keep settings like table names out of the code.
What to do: Set the environment variable TABLE=nashikvine-orders on nashikvine-orders-fn.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Invoke with a JSON payload
Why: In CLI v2, raw JSON needs --cli-binary-format raw-in-base64-out.
What to do: Invoke nashikvine-orders-fn with payload {"orderId":"o-101"} (raw JSON) and save the reply in out.json.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Lambda GB-seconds
Why: Lambda bills memory × time.
What to do: 1,000,000 invocations, 512 MB memory, 200 ms each. How many GB-seconds?
- Write down the numbers the task gives you.
- Work it out step by step on paper.
- Type only the final answer in the box.
- Click Check answer.
Hard Connect an SQS queue to Lambda
Why: An event source mapping makes Lambda poll the queue and process messages in batches.
What to do: Create an event source mapping from queue arn:aws:sqs:ap-south-1:107079156755:nashikvine-orders to nashikvine-orders-fn with batch size 10.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Hard Let S3 call your function
Why: A resource-based permission is needed before S3 can invoke the function.
What to do: Add permission statement s3invoke to nashikvine-orders-fn so s3.amazonaws.com can call lambda:InvokeFunction from bucket arn:aws:s3:::nashikvine-uploads.
- Read the task and decide which AWS service it is about.
- Write aws, then the service name, then the operation (the action word).
- Add each needed flag (--name) followed by its value from the task.
- Flags can be in any order. Click Check answer.
Revision, comparison and interview cards
Revise this lesson in a few minutes. Save the cards on your phone or download them as PNG files. The QR code on each card opens this lesson.




More cards: Ravi Sir's Cards.