AWS Lamda
AWS Lamda
AWS Lamda
In today’s cloud-driven world, automation is crucial, and AWS Lambda simplifies serverless computing.
One key feature to manage deployments and updates is Lambda versioning and aliases. In this article, I
will walk through how to create Lambda versions, publish them, and manage aliases using the AWS
Command Line Interface (CLI). This hands-on walk you through the creation of lambda function and
creating versions and aliases for your lambda function in CLI from EC2 instance.
WHAT IS LAMBDA?
AWS Lambda allows you to execute code without the need to set up or handle specific servers. In simpler
terms, Lambda is also known as Serverless Computing. With lambda, you only pay for the time your
code runs, and no charges apply during inactive periods. AWS Lambda functions make it possible to
execute code for various applications without the need for any administration. Simply upload your code
to Lambda, and it will handle all the necessary tasks for running and scaling your code with optimal
availability. You have the ability to establish events that will trigger your lambda function to run or be
activated. Lambda offers support for multiple languages like Java, Python, Node.js, and c for writing
lambda functions.
Versioning helps track different stages of your Lambda function’s lifecycle. Every time you modify your
function, you can create a version to capture that specific state. Lambda allows us to change the function
code and settings only on the unpublished version of a function. Each version of your Lambda function
has its own ARN. Once the function is published, the code and most of the settings are locked to ensure
a consistent experience for users of that version, and you cannot edit or modify the code of that version.
Aliases allow you to manage which version of the Lambda function is live in production (or in
development environments). A Lambda alias acts as a pointer to a specific Lambda function version.
AWS allows us to create one or more aliases for a particular lambda function. Each Alias has its own
unique ARN like versions and pointing to a specific version and can't point one alias to others. You can
update an alias to point to a new version of the function that is pointing to some other function.
LAB OUTLINE
1. Sign in to AWS Management Console
2. Creating an IAM Role
3. Create an Environment in CloudShell.
4. Creating a Lambda function in CLI
5. Updating and Invoking the lambda function
6. Publishing Lambda version in CLI
7. Publishing Lambda version 2 in CLI
8. Creation and Deletion of Lambda Alias
9. Validation of the Lab
10. Deleting Lambda Function
TASK 1: LOG IN TO THE AWS MANAGEMENT CONSOLE
It is always advisable to Sign in with an IAM credential rather than as a root user. Using the IAM
Credential instead of the root user enhances security by limiting access, enabling better control and
monitoring, and reducing the risk of accidental or malicious actions in your AWS account.
3. Select Region: Once logged in, the default region is US East (N. Virginia), which is represented by
us-east-1. You can set your preferred region in the top right corner of the console as shown by the
arrow in the diagram.
TASK 2: CREATE AN IAM ROLE
1. Go to the AWS Management Console.
2. In the top-left menu go to Services, > Security, Identity & Compliance, and Select IAM.
7. In the add permission page select AWSLambdaRole policy by typing it in the search bar and click
next.
8. In the Name, Review and Create page type the name of the role and click on create role.
9. You have successful created the Lambda Role. Make sure to copy the ARN of the role created
and save it in a notepad or any text editor.
1. In the AWS Management Console, locate the CloudShell icon in the top navigation bar. It looks like a
terminal/console icon.
2. Click on the CloudShell icon to launch the CloudShell environment.
3. A new tab in your browser opens, and you willl see a welcome message to cloud shell, click on the
Close button in that message.
4. You will see a creating environment message on the screen. Wait for a few minutes to complete the
environment creation. Once the environment is created. You are ready to use the terminal.
NB: With AWS CloudShell, you can use up to 1 GB of persistent storage in each AWS Region
at no additional cost. Persistent storage is located in your home directory ($HOME) and is
private to you. Unlike ephemeral environment resources that are recycled after each shell
session ends, data in your home directory persists between sessions.
import boto3
from botocore.exceptions import ClientError, NoCredentialsError, ParamValidationError
def handler(event, context):
s3 = boto3.resource('s3', region_name='us-east-2')
bucket_name = 'lambdabucket990'
try:
# Create the S3 bucket
s3.create_bucket(Bucket=lambdabucket990)
print(f"Bucket '{lambdabucket990}' created successfully.")
# Upload the file to the bucket
content = "File uploaded by version 1"
s3.Object(lambdabucket990, 'version1.txt').put(Body=content)
print("File uploaded successfully.")
return {
"statusCode": 200,
"body": "File uploaded and bucket created sucessfully!"
}
except ClientError as e:
# Catch errors from AWS service responses
print(f"ClientError: {e}")
return {
"statusCode": 500,
"body": f"ClientError: {e.response['Error']['Message']}"
}
except NoCredentialsError as e:
# Catch missing AWS credentials error
print(f"NoCredentialsError: {e}")
return {
"statusCode": 403,
"body": "Error: No AWS credentials found."
}
except ParamValidationError as e:
# Catch parameter validation errors (like invalid bucket name)
print(f"ParamValidationError: {e}")
return {
"statusCode": 400,
"body": f"ParamValidationError: {e}"
}
except Exception as e:
# Catch any other exception
print(f"Unexpected error: {e}")
return {
"statusCode": 500,
"body": f"Unexpected error: {e}"
}
2. Navigate to the cloudshell and create a file named s3bucket.py using the below command.
nano s3bucket.py.
3. Copy the python script above and paste it into the editor and save it using Ctrl + O and hint enter,
and Ctrl + X to exit from the editor. You can use your preferred editor for writing the python script.
4. Create a Zip file of the s3bucket.py file, which is used to create lambda function in CLI using below
command.
zip s3bucket.zip s3bucket.py
5. Create a lambda function from CLI using the following command.
aws lambda create-function --function-name lambdaclidemo --runtime python3.12 --zip-file
fileb://s3bucket.zip --handler s3bucket.handler --role arn:aws:iam::533267168161:role/LambdaRoleVersion
6. The lambda function has been created successfully as shown below.
In this task, we are going to update the previously created Lambda function's configuration to
increase the timeout period and then invoke the function using the CLI.
1. By default, the lambda function created will have a timeout period of 3 seconds, you can update your
Lambda function using the below command.
aws lambda update-function-configuration --function-name lambdaclidemo --timeout 30
2. To invoke the lambda function in the command line you can run the below command. You can
see that it will create the lambda with $LATEST version as shown in the diagram below.
aws lambda invoke --function-name lambdaclidemo --invocation-type RequestResponse outputfile.txt
3.
This command freezes the current state of the function and assigns it a version number.
2. Now navigate to Lambda dashboard in AWS console to view the current versions of the function,
choose a function, -->Versions tab and the Versions panel will display the list of versions for the
selected function.
Let us change the content of the file and the name of the file and upload it to s3.
3. First, navigate to CloudShell and open the file using nano editor using below command.
Nano s3bucket.py
4. Change the content to File uploaded by version 2 and file name as version2.txt as shown below.
1. After creating the Lambda function, it's time to publish the new version. Every time you make
changes to the Lambda function, you'll want to publish a new version. To publish the version run the
below command
2. Now navigate to Lambda dashboard in AWS console to view the current versions of the function,
choose a function, -->Versions tab. You can find that version 1 with the filename version1.txt and
the latest version with version2.txt as shown below.
TASK 8: CREATING AN ALIAS
An alias is a pointer to a specific version of a Lambda function. This is useful when you have multiple environments
(like Dev or Prod) and want to easily switch between them.
1. To create an Alias for the Lambda function run the below command, here we are creating Alias
for lambdaclidemo version 1 in the name of Dev. NOTE : Update the version number if you
have different version number.
aws lambda create-alias --function-name lambdaclidemo --description "sample alias for lambda" --function-version 1 --name DEV
2. To check the Alias created, Navigate to Lambda dashboard and choose a function -->Alias
and you can see the alias created for version 1.
3. You can create another alias for the PROD team using the command above by changing the
version to 2 and the name to PROD.
aws lambda create-alias --function-name lambdaclidemo --description "sample alias for lambda" --function-version 2 --name PROD
TASK 8: MANAGING AND DELETING FUNCTIONS AND ALIASES
If you ever need to delete an alias or function, here are the commands:
1. To delete an alias:
WRAPPING UP
By following these steps, you've successfully created a Lambda function, managed its versions, and used aliases
to simplify deployment. AWS Lambda versioning and aliasing are crucial for maintaining serverless applications
efficiently, and using the CLI makes it easy to automate. If you're just starting with AWS Lambda, don’t be afraid
to experiment. Check out the official AWS documentation for more in-depth details. Happy coding!