AWS CLI v2 by Examples: Master Lambda Versioning, Aliases, and Deployment Strategies
This article leverages AWS CLI v2 to demonstrate Lambda function versioning, alias management (including prod, dev, and staging)…
AWS CLI v2 by Examples: Master Lambda Versioning, Aliases, and Deployment Strategies
This article leverages AWS CLI v2 to demonstrate Lambda function versioning, alias management (including prod, dev, and staging), blue/green deployment strategies with traffic shifting, rollback mechanisms, and provisioned concurrency management. Each section explores real-world examples vital for production-grade deployments and smooth update transitions.

We begin by explaining how to publish multiple Lambda versions and create environment-specific aliases. Next, we detail blue/green deployment techniques to gradually shift traffic between versions while ensuring minimal downtime. Finally, we showcase how to manage provisioned concurrency settings for consistent performance using AWS CLI v2. These practices underscore best strategies for reliable AWS Lambda management.
Lambda Function Versioning & Aliases Management
In this section, we explore numerous methods to publish multiple Lambda function versions, create environment aliases that point directly to the required versions, and perform rollbacks when issues emerge. Each of these processes serves as a critical building block in achieving and maintaining a robust production environment. Ensuring quick recovery from potential release issues is paramount, and these actions lay the groundwork for scalable and safe deployments.
Use Case: Publishing Multiple Versions of a Lambda Function
This use case illustrates the process of uploading updated code and creating a clear version history for your Lambda function. It ensures that every deployment is captured as an immutable, versioned copy, allowing for easy tracking and retrieval. Establishing a managed workflow for version control is crucial for safely rolling out updates and diagnosing issues when they arise.
# Update the function code with your latest package
aws lambda update-function-code --function-name MyLambdaFunction --zip-file fileb://function.zip
# Wait for code update completion (simulate a delay if necessary)
sleep 2
# Publish the new version of the Lambda function
PUBLISHED_VERSION=$(aws lambda publish-version --function-name MyLambdaFunction --query 'Version' --output text)
echo "New version published: $PUBLISHED_VERSION"
# Verify the function configuration for the new version
aws lambda get-function-configuration --function-name MyLambdaFunction --qualifier $PUBLISHED_VERSION
# List all available versions to confirm publication
aws lambda list-versions-by-function --function-name MyLambdaFunction
# Store the version information in a log file
echo "Version $PUBLISHED_VERSION published at $(date)" >> lambda_publish.log
# Optional: Notify stakeholders via SNS (simulate notification)
aws sns publish --topic-arn arn:aws:sns:region:account-id:MyTopic --message "Lambda version $PUBLISHED_VERSION published"
# End of version publishing sample
This sample showcases how to safely update a Lambda function by incorporating a versioning strategy. It details the code update process, the publication of a new version, the verification of version details, and the logging of actions for audit purposes. Additionally, the sample includes a simulated mechanism to notify stakeholders, reinforcing communication during deployments.
Use Case: Creating Aliases (prod, dev, staging)
Aliases provide a way to abstract the underlying version numbers and enable seamless switching between versions or environments. This sample covers the process of creating aliases that point to specific Lambda function versions, easing future updates and allowing logical separation. By leveraging aliases, you decouple the logical reference of your function from its physical version, streamlining upgrades and rollbacks.
# Define variables for function name and target version
FUNCTION_NAME="MyLambdaFunction"
TARGET_VERSION="2"
# Create alias named 'prod' pointing to version 2
aws lambda create-alias --name prod --function-name $FUNCTION_NAME --function-version $TARGET_VERSION --description "Production alias"
# Create alias named 'dev' for development environment pointing to version 1
aws lambda create-alias --name dev --function-name $FUNCTION_NAME --function-version "1" --description "Development alias"
# Create alias named 'staging' for staging environment pointing to version 2
aws lambda create-alias --name staging --function-name $FUNCTION_NAME --function-version $TARGET_VERSION --description "Staging alias"
# Verify that the aliases are created correctly
aws lambda list-aliases --function-name $FUNCTION_NAME
# Output alias details for 'prod'
aws lambda get-alias --function-name $FUNCTION_NAME --name prod
# Log alias creation details to a file
echo "Aliases for $FUNCTION_NAME created at $(date)" >> alias_creation.log
# End of alias creation sample
This sample outlines the process of alias creation for different environments such as production, development, and staging. It provides clear instructions that help users maintain proper version control and separation across environments. Furthermore, the process includes logging activities to facilitate auditing and troubleshooting of alias configurations.
Use Case: Rollback to a Previous Version
Rollbacks are essential for maintaining production stability when unexpected issues occur. This code demonstrates how to update an alias so that it points back to a previously known, stable version. Employing such a rollback mechanism allows teams to quickly reinstate a reliable version, keeping service disruptions to a minimum.
# Define variables and previous stable version
FUNCTION_NAME="MyLambdaFunction"
STABLE_VERSION="1"
ALIAS_NAME="prod"
# Display current alias configuration before rollback
aws lambda get-alias --function-name $FUNCTION_NAME --name $ALIAS_NAME
# Update the alias to rollback to the stable version
aws lambda update-alias --function-name $FUNCTION_NAME --name $ALIAS_NAME --function-version $STABLE_VERSION
# Verify the rollback by retrieving updated alias configuration
aws lambda get-alias --function-name $FUNCTION_NAME --name $ALIAS_NAME
# Log rollback action
echo "Alias $ALIAS_NAME rolled back to version $STABLE_VERSION at $(date)" >> rollback.log
# Optional: Send notification of rollback completion
aws sns publish --topic-arn arn:aws:sns:region:account-id:RollbackTopic --message "Rollback of alias $ALIAS_NAME to version $STABLE_VERSION complete"
# End of rollback sample
This sample code provides a fail-safe mechanism by demonstrating how to fetch the current alias configuration, implement a rollback to a stable version, and verify the updated settings. It emphasizes the importance of logging the change to maintain an audit trail. Such a rollback strategy is vital for mitigating risks associated with new deployments and ensuring swift recovery.
Use Case: Advanced Alias Traffic Splitting for Canary Testing
This use case illustrates how to leverage advanced alias routing to split traffic among multiple versions for canary testing. It enables you to assign weighted percentages to experimental versions while keeping the majority of traffic on the stable release. By monitoring the performance of these experimental versions, teams can collect critical data to make informed decisions on future rollouts.
# Define variables for function name and versions
FUNCTION_NAME="MyLambdaFunction"
BASE_VERSION="2"
EXPERIMENTAL_VERSION_1="3"
EXPERIMENTAL_VERSION_2="4"
ALIAS_NAME="staging"
# Set up traffic splitting: base version gets 84.5%, experimental version 1 gets 10%, and experimental version 2 gets 5%
aws lambda update-alias --function-name $FUNCTION_NAME --name $ALIAS_NAME --function-version $BASE_VERSION --routing-config '{"AdditionalVersionWeights": {"'$EXPERIMENTAL_VERSION_1'": 0.1, "'$EXPERIMENTAL_VERSION_2'": 0.05}}'
# Pause briefly to allow configuration to propagate
sleep 5
# Verify the updated alias configuration with weighted traffic splits
aws lambda get-alias --function-name $FUNCTION_NAME --name $ALIAS_NAME
# Log the traffic splitting configuration for auditing purposes
echo "Alias $ALIAS_NAME configured for traffic splitting: base version $BASE_VERSION (84.5%), experimental versions $EXPERIMENTAL_VERSION_1 (10%) and $EXPERIMENTAL_VERSION_2 (5%) at $(date)" >> alias_canary.log
# End of advanced alias traffic splitting sample
This sample demonstrates how to configure weighted aliases for canary testing by assigning different traffic percentages to various Lambda versions. It highlights the process of evaluating experimental versions while maintaining overall system stability. The sample also logs the configuration details so that traffic distribution can be audited and adjusted as needed.
Deployment Strategies (Blue/Green Deployment)
This section outlines the blue/green deployment strategy using aliases and traffic shifting to manage releases with minimal disruption. The method involves deploying a new version (green) while keeping the existing version (blue) live, ensuring continuity of service. This deployment approach significantly reduces downtime and risk by enabling controlled testing phases and facilitating immediate corrective actions if necessary.
Use Case: Implementing Blue/Green Deployment with Traffic Shifting
By employing alias routing configurations, you can partition incoming traffic between the current stable version and a newly deployed version. This strategy allows you to monitor the performance of the new release while minimizing impact on end users. It offers a gradual transition process that not only reduces risk but also provides real-time performance insights during the rollout.
# Define variables for function name, old version (blue), and new version (green)
FUNCTION_NAME="MyLambdaFunction"
OLD_VERSION="1"
NEW_VERSION="2"
ALIAS_NAME="prod"
# Initial deployment: update alias to both versions with 100% traffic to old version
aws lambda update-alias --function-name $FUNCTION_NAME --name $ALIAS_NAME --function-version $OLD_VERSION --routing-config '{"AdditionalVersionWeights": {"'$NEW_VERSION'": 0.0}}'
# Pause before starting traffic shift
sleep 5
# Shift 20% traffic to new version using update-alias with a routing configuration
aws lambda update-alias --function-name $FUNCTION_NAME --name $ALIAS_NAME --routing-config '{"AdditionalVersionWeights": {"'$NEW_VERSION'": 0.2}}'
# Log the progress of traffic shifting
echo "Traffic shifted: 20% to version $NEW_VERSION, 80% remains on version $OLD_VERSION" >> deployment.log
# Incrementally shift traffic to 50%
sleep 5
aws lambda update-alias --function-name $FUNCTION_NAME --name $ALIAS_NAME --routing-config '{"AdditionalVersionWeights": {"'$NEW_VERSION'": 0.5}}'
# Log the change
echo "Traffic shifted: 50% to version $NEW_VERSION" >> deployment.log
# Final step: shift all traffic to the new version and remove routing weights
sleep 5
aws lambda update-alias --function-name $FUNCTION_NAME --name $ALIAS_NAME --function-version $NEW_VERSION
echo "Deployment complete. All traffic is now routed to version $NEW_VERSION" >> deployment.log
# End of blue/green deployment sample
This code demonstrates a step-by-step blue/green deployment where traffic is gradually shifted from the blue version to the green version. Each modification is logged to provide a clear deployment trail, thereby facilitating rapid troubleshooting if needed. The sample illustrates a systematic reduction in risk by employing controlled traffic shifting throughout the rollout.
Provisioned Concurrency Management
In this section, we address the configuration of provisioned concurrency using AWS CLI v2 to ensure consistent performance under fluctuating load conditions. By pre-configuring a set number of concurrent executions, Lambda functions can avoid cold start delays and deliver fast responses. This proactive approach to capacity management is essential for maintaining dependable operation during peak usage and sudden traffic spikes.
Use Case: Managing Provisioned Concurrency via AWS CLI
This example shows how to set up and update provisioned concurrency for a Lambda function alias to maintain optimal performance during variable load conditions. In this scenario, you will learn how to enforce performance consistency by pre-configuring capacity and then dynamically adjusting it in response to changing demands. Such proactive configuration minimizes latency and ensures that user experiences are not compromised during periods of high activity.
# Define variables for Lambda function, alias, and concurrency value
FUNCTION_NAME="MyLambdaFunction"
ALIAS_NAME="prod"
CONCURRENCY_VALUE=5
# Configure provisioned concurrency for the production alias
aws lambda put-provisioned-concurrency-config --function-name $FUNCTION_NAME --qualifier $ALIAS_NAME --provisioned-concurrent-executions $CONCURRENCY_VALUE
# Retrieve and display the provisioned concurrency configuration
aws lambda get-provisioned-concurrency-config --function-name $FUNCTION_NAME --qualifier $ALIAS_NAME
# Pause to allow changes to propagate
sleep 2
# Update provisioned concurrency to a new value based on load changes
NEW_CONCURRENCY=10
aws lambda put-provisioned-concurrency-config --function-name $FUNCTION_NAME --qualifier $ALIAS_NAME --provisioned-concurrent-executions $NEW_CONCURRENCY
# Verify the updated configuration
aws lambda get-provisioned-concurrency-config --function-name $FUNCTION_NAME --qualifier $ALIAS_NAME
# Log the concurrency configuration change
echo "Provisioned concurrency updated from $CONCURRENCY_VALUE to $NEW_CONCURRENCY at $(date)" >> concurrency.log
# Optional: Further monitor concurrency usage with a CloudWatch Insights query (simulation)
aws logs filter-log-events --log-group-name "/aws/lambda/$FUNCTION_NAME" --filter-pattern "ProvisionedConcurrency"
# End of provisioned concurrency sample
Here, we configure and update provisioned concurrency for a Lambda function alias, then verify the changes and log the operations for future reference. This demonstration provides a straightforward walkthrough of how to dynamically adjust concurrency settings in response to performance demands. The sample underscores best practices for proactive cloud performance tuning and capacity management.
Use Case: Monitoring Lambda Function Performance and Error Metrics
Monitoring AWS Lambda performance is key to diagnosing issues and enhancing overall function behavior insight. This sample demonstrates how to retrieve and summarize error metrics using AWS CloudWatch over a defined time period. By analyzing these metrics, operators can decide on scaling strategies and quickly resolve anomalies, thereby ensuring better system reliability.
# Define function name and time range for CloudWatch
FUNCTION_NAME="MyLambdaFunction"
START_TIME=$(date -u -d '1 hour ago' +%Y-%m-%dT%H:%M:%SZ)
END_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ)
# Retrieve Lambda function's metrics from CloudWatch
aws cloudwatch get-metric-statistics --metric-name Errors \
--start-time $START_TIME --end-time $END_TIME \
--period 300 --namespace AWS/Lambda \
--statistics Sum --dimensions Name=FunctionName,Value=$FUNCTION_NAME \
--output json > error_metrics.json
# Parse and summarize the errors from JSON output
ERROR_COUNT=$(jq '.Datapoints | map(.Sum) | add' error_metrics.json)
echo "Total Errors in the last hour for $FUNCTION_NAME: $ERROR_COUNT" >> monitoring.log
# Optionally trigger an alarm if error count exceeds a threshold
THRESHOLD=10
if [ "$ERROR_COUNT" -gt "$THRESHOLD" ]; then
aws sns publish --topic-arn arn:aws:sns:region:account-id:ErrorTopic --message "Alert: $FUNCTION_NAME has exceeded error threshold with $ERROR_COUNT errors in the last hour!"
fi
# End of monitoring sample
This sample retrieves error metrics for a specified Lambda function from AWS CloudWatch over the past hour and then summarizes the total error count. It provides clear instructions to collect and review performance data in near real-time, ensuring that any anomalies are promptly identified. The sample also includes an optional alert mechanism to notify administrators if error counts exceed a predetermined threshold.
Conclusion
Throughout this article, we have demonstrated how AWS CLI v2 can be effectively used to manage Lambda function versions, create and update aliases, execute blue/green deployments with traffic shifting, and adjust provisioned concurrency. We also explored monitoring methodologies and error handling techniques that contribute to operational excellence. These examples emphasize not only the power of the AWS CLI but also its practicality for real-world production and development scenarios.
By mastering these techniques, developers and operations teams can ensure smooth updates, rapid rollbacks, and consistent performance under load. The practices covered here provide a foundation for robust AWS Lambda management, making production deployments more reliable and resilient in today’s dynamic cloud environment. Embracing these best practices empowers teams to respond swiftly to changes, optimize resource usage, and drive innovation in modern cloud architectures.
메타데이터
- post_id
- 7035216f0595
- slug
- aws-cli-v2-by-examples-master-lambda-versioning-aliases-and-deployment-strategies-7035216f0595
- url
- https://medium.com/@mb20261/aws-cli-v2-by-examples-master-lambda-versioning-aliases-and-deployment-strategies-7035216f0595
- canonical_url
- https://medium.com/@mb20261/aws-cli-v2-by-examples-master-lambda-versioning-aliases-and-deployment-strategies-7035216f0595
- author_url
- https://medium.com/@mb20261
- status
- ok
- fetched_at
- 2026-06-29 01:02:39