Certainly! Below is a comprehensive documentation of the provided AWS CDK (Cloud Development Kit) Python code. This documentation covers the AWS concepts involved, detailed explanations of each part of the code, and the rationale behind various implementations.
Table of Contents
- Overview
- Imports and Dependencies
- Constants and Environment Variables
- Classes and Functions
- AWS Concepts Explained
- Line-by-Line Explanation
- Conclusion
Overview
The provided code utilizes AWS CDK to define infrastructure as code (IaC) for deploying AWS Lambda functions within a specific architecture. The main focus is on creating a customizable and reusable Lambda function construct (PythonLambdaFunction) that integrates with various AWS services like IAM, VPC, Secrets Manager, and more. Additionally, helper functions and constructs are provided to manage permissions and environment configurations.
Imports and Dependencies
External Libraries and Modules
import os
from typing import Optional, Union
import aws_cdk.aws_iam as iam
from aws_cdk import DockerImage, Duration, Stack
from aws_cdk import aws_ec2 as ec2
from aws_cdk import aws_lambda
from aws_cdk.aws_logs import RetentionDays
from constructs import Construct
from cdk_resources import role
from cdk_resources.construct import CDKConstruct
from cdk_resources.legacy_bridge import LEGACY_BRIDGE_SECRETS
from cdk_resources.secret_identifier import SecretIdentifier
Explanation
Constants and Environment Variables
# Set the runtime for the code bundling
RUNTIME = aws_lambda.Runtime.PYTHON_3_9
LAMBDA_BUNDLING_RUNTIME = DockerImage.from_registry("public.ecr.aws/sam/build-python3.9:latest-x86_64")
CODE_BUNDLE_PATH = os.environ.get("CODE_ZIP_PATH") or "/bundles/bundle.zip"
Explanation
-
RUNTIME: Specifies the Python runtime version (3.9) for the Lambda function.
-
LAMBDA_BUNDLING_RUNTIME: Defines the Docker image used to bundle the Lambda function code. This is essential for building Lambda deployment packages in a consistent environment.
-
CODE_BUNDLE_PATH: Determines the path to the Lambda function's deployment package (ZIP file). It first checks for an environment variable CODE_ZIP_PATH; if not found, it defaults to /bundles/bundle.zip.
Classes and Functions
CDKConstruct Class
class CDKConstruct(Construct):
def __init__(self, *args, **kwargs):
# Initialize the construct base class
super().__init__(*args, **kwargs)
def stack(self):
"""The stack object in which a construct has been placed"""
return Stack.of(self)
@property
def account(self) -> str:
"""The AWS account of the stack"""
return self.stack().account
@property
def region(self) -> str:
"""The AWS region of the stack"""
return self.stack().region
@property
def tenant(self) -> str:
"""The name of the tenant for a stack"""
return "-".join(self.stack().tenant.split()).lower()
@property
def environment_type(self) -> EnvironmentType:
"""The environment type of the stack"""
return self.stack().environment_type
@property
def ff_tenant_provisioning(self) -> bool:
return self.stack().ff_tenant_provisioning
@property
def storage_tenant(self) -> str:
"""The storage tenant of the stack"""
return self.stack().storage_tenant
@property
def stack_name(self) -> str:
"""The name of the stack"""
return self.stack().stack_name
def prefix(self) -> str:
"""A prefix naming conventions used in externally managed resources"""
return f"{self.tenant}-{self.environment_type}".lower()
Explanation
The CDKConstruct class extends the base Construct class from CDK and provides additional properties and methods to access stack-level information easily. This abstraction helps in managing stack-specific configurations and naming conventions.
-
Properties
account: Retrieves the AWS account ID where the stack is deployed.
region: Retrieves the AWS region of the stack.
tenant: Processes the tenant name by removing spaces and converting it to lowercase.
environment_type: Retrieves the environment type (e.g., dev, test, prod).
ff_tenant_provisioning: A feature flag indicating if tenant provisioning is enabled.
storage_tenant: Retrieves the storage tenant name.
stack_name: Retrieves the name of the stack.
-
Methods
stack(): Returns the stack object associated with the construct.
prefix(): Generates a prefix using the tenant name and environment type for resource naming.
Note: There's a TODO comment indicating that the EnvironmentType datatype is considered dangerous and should be removed, suggesting potential architectural or security concerns.
PythonLambdaFunction Class
class PythonLambdaFunction(CDKConstruct):
_BUNDLE_CACHE: dict[str, aws_lambda.Code] = {}
def __init__(
self,
scope: Construct,
construct_id: str,
*,
handler: str,
timeout_seconds: int = 30,
memory_size_mb: int = 256,
log_retention: RetentionDays = RetentionDays.THREE_MONTHS,
environment: Optional[dict[str, str]] = None,
vpc=None,
module_name=None,
grants=None,
security_groups: Optional[list[ec2.SecurityGroup]] = None,
secrets: Optional[list[SecretIdentifier]] = None,
reserved_concurrent_executions: Optional[Union[int, float]] = None,
ff_tenant_provisioning=False,
):
# Initialize the construct base class
super().__init__(scope, construct_id)
# TODO: remove once we've resolved the vpc to have an private subnet
allow_public_subnet = ff_tenant_provisioning
# Store the specified handler as a property so it is available
# for inspection
self.handler = handler
# Add the elastic secrets into the lambda
environment = environment or {}
# Replace grants with an empty list if None
grants = grants or []
# Default secrets to an empty list
secrets = secrets or []
# Add in environment variables from the secrets parameter
secrets_environment = self._environment_variables_from_secrets(secrets)
if secrets_environment:
# Copy the environment dict before mutating it
environment = environment.copy()
environment.update(secrets_environment)
# Add in permission grants from the secrets parameter
secrets_grants = self._grants_from_secrets(secrets)
if secrets_grants:
# Copy the grants list before mutating it
grants = grants.copy()
grants.extend(secrets_grants)
# Select the default VPC based on the secrets passed
vpc = vpc or self._vpc_from_secrets(secrets)
# Set the security groups for this lambda
security_groups = security_groups or []
# Make / retrieve the code bundle
bundle = self.code_bundle()
# Create the lambda primitive
self.fn = aws_lambda.Function(
self,
id=construct_id if ff_tenant_provisioning else "Fn",
# Specify the runtime for executing the lambda
runtime=RUNTIME,
# The bundled code which ultimately provides a zip
code=bundle,
# The entry point of the lambda
handler=handler,
# The environment variables for the lambda
environment=environment,
# The maximum runtime of the lambda after which it is cancelled
timeout=Duration.seconds(timeout_seconds),
# The memory size and indirectly the amount of CPU resources
# available to the lambda at runtime
memory_size=memory_size_mb,
# Retain logs from the lambda executions
log_retention=log_retention,
# The VPC (AWS EC2 Network) which the lambda is connected to at runtime
vpc=vpc,
# The security groups attached to this lambda
security_groups=security_groups,
architecture=aws_lambda.Architecture.X86_64,
# The number of simultaneous executions to reserve for the function
reserved_concurrent_executions=reserved_concurrent_executions,
allow_public_subnet=allow_public_subnet,
)
# Set the function_arn property directly so that it is
# convenient to access
self.function_arn = self.fn.function_arn
# Grant permissions as requested by the caller
for grant_target in grants:
grant_target(role.get_asserted_role(self.fn.role))
Explanation
The PythonLambdaFunction class extends CDKConstruct and encapsulates the logic for creating and configuring an AWS Lambda function with various customizable parameters. It also manages code bundling and integrates with other AWS services like VPC and Secrets Manager.
Attributes
_BUNDLE_CACHE: A class-level dictionary to cache Lambda code bundles per stack, preventing redundant bundling.
Constructor Parameters
Initialization Steps
-
Base Class Initialization
- Initializes the base
CDKConstruct with the provided scope and construct_id.
-
Handler Property
- Stores the
handler string for future reference.
-
Environment and Grants Initialization
- Initializes
environment, grants, and secrets if they are not provided (None).
-
Inject Secrets into Environment Variables
- Calls
_environment_variables_from_secrets to generate environment variables from the provided secrets.
- Merges these with existing environment variables.
-
Manage IAM Grants from Secrets
- Calls
_grants_from_secrets to generate necessary IAM grants based on the secrets.
- Extends the existing grants list with these additional grants.
-
VPC Configuration
- Determines the VPC to associate with the Lambda based on the secrets by calling
_vpc_from_secrets.
-
Security Groups
- Initializes security groups if not provided.
-
Code Bundling
- Retrieves the Lambda code bundle by calling
code_bundle.
-
Lambda Function Creation
- Creates the AWS Lambda function with the specified configuration:
- Runtime: Python 3.9.
- Code: The bundled code.
- Handler: Entry point.
- Environment Variables: Combined environment variables.
- Timeout & Memory: As specified.
- Log Retention: Configured retention period.
- VPC & Security Groups: Network configuration.
- Architecture: X86_64.
- Reserved Concurrency: As specified.
- Public Subnet Access: Based on
ff_tenant_provisioning.
Methods
-
code_bundle
- Manages and caches the Lambda code bundle to prevent redundant bundling across stacks.
- Retrieves the code asset from the specified
CODE_BUNDLE_PATH.
-
Helper Methods
_environment_variables_from_secrets: Generates environment variables containing the ARNs of the specified secrets.
_grants_from_secrets: Generates IAM grants to allow the Lambda to read the specified secrets.
_vpc_from_secrets: Determines the appropriate VPC based on the provided secrets, especially if legacy bridge secrets are used.
Helper Functions
allow_lambda_assume_role
def allow_lambda_assume_role(fn: aws_lambda.Function):
assume_statement = iam.PolicyStatement(
actions=["sts:AssumeRole"],
effect=iam.Effect.ALLOW,
resources=["*"]
)
role.get_asserted_role(fn.role).add_to_principal_policy(assume_statement)
Explanation
This function grants the Lambda function permission to assume any IAM role by adding an IAM policy statement that allows the sts:AssumeRole action on all resources.
-
Parameters
fn: The AWS Lambda function to which the permission is granted.
-
Actions
- Adds a policy statement to the Lambda's execution role, allowing it to assume any IAM role (
resources=["*"]).
Security Note: Granting sts:AssumeRole on all resources ("*" ARN) is highly permissive and should be restricted to specific roles to follow the principle of least privilege.
allow_cross_account_invoke
def allow_cross_account_invoke(fn: aws_lambda.Function, account_id: str):
fn.grant_invoke(iam.AccountPrincipal(account_id))
Explanation
This function allows a specified AWS account (account_id) to invoke the given Lambda function.
-
Parameters
fn: The AWS Lambda function to be invoked.
account_id: The AWS account ID that is granted invoke permissions.
-
Actions
- Grants the
InvokeFunction permission to the specified AWS account using grant_invoke method.
allow_lambda_get_bucket_policy
def allow_lambda_get_bucket_policy(fn: aws_lambda.Function, bucket_name_contains: str) -> None:
fn.add_to_role_policy(
iam.PolicyStatement(
actions=["s3:GetObject"],
effect=iam.Effect.ALLOW,
resources=[f"arn:aws:s3:::*{bucket_name_contains}*/*"],
)
)
Explanation
This function grants the Lambda function permission to perform s3:GetObject actions on S3 buckets whose names contain a specific substring.
-
Parameters
fn: The AWS Lambda function.
bucket_name_contains: A substring to match bucket names.
-
Actions
- Adds a policy statement to the Lambda's role, allowing it to get objects from any S3 bucket that matches the pattern.
Security Note: Granting permissions based on partial bucket name matching can lead to unintended access. It's safer to specify exact bucket ARNs.
AWS Concepts Explained
Understanding the provided code requires familiarity with several AWS services and concepts:
-
AWS Lambda
- Serverless compute service running code in response to events.
- Configured with handlers, runtime environments, memory, timeout, and environment variables.
-
AWS CDK (Cloud Development Kit)
- An open-source software development framework for defining cloud infrastructure in code.
- Supports multiple languages, including Python.
-
IAM (Identity and Access Management)
- Manages access to AWS resources.
- Roles and policies define permissions.
-
VPC (Virtual Private Cloud)
- Isolated network within AWS.
- Lambda functions can be connected to a VPC for access to private resources.
-
SECURITY GROUPS
- Stateful firewalls controlling inbound and outbound traffic for AWS resources within a VPC.
-
Secrets Manager
- Securely stores and manages secrets like database credentials, API keys, etc.
- Integrates with Lambda for accessing secrets securely.
-
CloudWatch Logs
- Logging service for monitoring and troubleshooting AWS resources like Lambda functions.
-
Concurrency
- Reserved Concurrency: Allocating a set number of concurrent executions to a Lambda function.
- Helps in throttling and ensuring resources aren't exhausted.
-
Docker Images
- Used for consistent build environments, especially for bundling code dependencies.
-
Constructs
- The basic building blocks of AWS CDK apps.
- Represent AWS resources and higher-level abstractions.
Line-by-Line Explanation
Given the length and complexity of the code, here's a detailed explanation of key sections and lines.
Lambda Function Configuration
RUNTIME = aws_lambda.Runtime.PYTHON_3_9
- Runtime Specification
- Sets Python 3.9 as the runtime environment for Lambda functions.
LAMBDA_BUNDLING_RUNTIME = DockerImage.from_registry("public.ecr.aws/sam/build-python3.9:latest-x86_64")
- Code Bundling Environment
- Defines a Docker image from AWS's public ECR registry used to bundle Lambda code. This ensures that dependencies are built in an environment consistent with Lambda's execution environment.
CODE_BUNDLE_PATH = os.environ.get("CODE_ZIP_PATH") or "/bundles/bundle.zip"
- Lambda Code Path
- Determines the path to the Lambda deployment package. It checks for the
CODE_ZIP_PATH environment variable; if not set, defaults to /bundles/bundle.zip.
PythonLambdaFunction Class Constructor
class PythonLambdaFunction(CDKConstruct):
_BUNDLE_CACHE: dict[str, aws_lambda.Code] = {}
- Class Definition and Bundle Cache
- Defines a custom construct for Lambda functions, with a class-level cache to store code bundles per stack to optimize deployments.
def __init__(..., ff_tenant_provisioning=False):
super().__init__(scope, construct_id)
allow_public_subnet = ff_tenant_provisioning
self.handler = handler
- Initialization and Feature Flag
- Initializes the base construct.
- Uses
ff_tenant_provisioning as a feature flag to determine if the Lambda should be allowed in a public subnet (temporary workaround as indicated by the TODO comment).
environment = environment or {}
grants = grants or []
secrets = secrets or []
- Default Parameter Handling
- Ensures that
environment, grants, and secrets are initialized as empty structures if not provided.
secrets_environment = self._environment_variables_from_secrets(secrets)
if secrets_environment:
environment = environment.copy()
environment.update(secrets_environment)
- Injecting Secrets into Environment Variables
- Merges environment variables generated from secrets into the existing environment variables.
secrets_grants = self._grants_from_secrets(secrets)
if secrets_grants:
grants = grants.copy()
grants.extend(secrets_grants)
- Injecting IAM Grants from Secrets
- Extends the existing grants with additional permissions derived from the secrets.
vpc = vpc or self._vpc_from_secrets(secrets)
security_groups = security_groups or []
- VPC and Security Groups Configuration
- Determines the VPC to associate with the Lambda based on secrets.
- Initializes security groups if not provided.
bundle = self.code_bundle()
- Code Bundling
- Retrieves the code bundle, using caching to avoid redundant bundling.
self.fn = aws_lambda.Function(
self,
id=construct_id if ff_tenant_provisioning else "Fn",
runtime=RUNTIME,
code=bundle,
handler=handler,
environment=environment,
timeout=Duration.seconds(timeout_seconds),
memory_size=memory_size_mb,
log_retention=log_retention,
vpc=vpc,
security_groups=security_groups,
architecture=aws_lambda.Architecture.X86_64,
reserved_concurrent_executions=reserved_concurrent_executions,
allow_public_subnet=allow_public_subnet,
)
- Lambda Function Creation
- Configures and instantiates the AWS Lambda function with all specified parameters, including runtime, code, handler, environment variables, timeout, memory size, log retention, VPC settings, security groups, architecture, concurrency settings, and subnet access.
self.function_arn = self.fn.function_arn
- Function ARN Storage
- Stores the Lambda function's ARN for easy access.
for grant_target in grants:
grant_target(role.get_asserted_role(self.fn.role))
- Applying IAM Grants
- Iterates over the provided grants and applies them to the Lambda's execution role using a utility function to fetch the asserted role.
Helper Methods in PythonLambdaFunction
code_bundle
def code_bundle(self) -> aws_lambda.Code:
stack_name = Stack.of(self).stack_name
if stack_name in self._BUNDLE_CACHE:
return self._BUNDLE_CACHE[stack_name]
bundle = aws_lambda.Code.from_asset(CODE_BUNDLE_PATH)
self._BUNDLE_CACHE[stack_name] = bundle
return bundle
-
Purpose
- Manages the Lambda code bundle by caching it per stack to avoid redundant bundling.
-
Process
- Checks if a bundle already exists in the cache for the current stack.
- If not, creates a new code asset from the specified path and caches it.
_environment_variables_from_secrets
def _environment_variables_from_secrets(self, secrets: list):
environment = {}
for identifier, secret in self.stack().secrets.items():
if identifier not in secrets:
continue
environment.update(
{
f"{identifier.name.upper()}_SECRET_ARN": secret.secret_arn,
}
)
return environment
-
Purpose
- Creates environment variables that store the ARNs of the specified secrets.
-
Process
- Iterates over the stack's secrets, and for each secret in the provided
secrets list, adds an environment variable with the secret's ARN.
_grants_from_secrets
def _grants_from_secrets(self, secrets: list):
grants = []
for identifier, secret in self.stack().secrets.items():
if identifier not in secrets:
continue
grants.append(secret.grant_read)
return grants
-
Purpose
- Generates IAM grants to allow the Lambda function to read the specified secrets.
-
Process
- Iterates over the stack's secrets, and for each secret in the
secrets list, appends the grant_read method to the grants list.
_vpc_from_secrets
def _vpc_from_secrets(self, secrets: list):
for identifier in LEGACY_BRIDGE_SECRETS:
if identifier in secrets:
return self.stack().legacy_bridge_vpc
return None
-
Purpose
- Determines the VPC configuration based on the provided secrets, especially if legacy bridge secrets are involved.
-
Process
- Checks if any secrets require the use of the
legacy_bridge_vpc.
- If so, returns that VPC; otherwise, no VPC is associated.
Helper Function Explanations
allow_lambda_assume_role
- Security Implication:
- Allows the Lambda function to assume any role across the AWS account, which can lead to privilege escalation if misused. It should be restricted to specific roles.
allow_cross_account_invoke
- Use Case:
- Useful when you have services or applications in another AWS account that need to invoke this Lambda function.
allow_lambda_get_bucket_policy
- Use Case:
- Grants the Lambda function the ability to read objects from S3 buckets matching a specific naming pattern, facilitating data access for processing or analysis.
Conclusion
The provided AWS CDK code defines a sophisticated and reusable construct for deploying Python-based AWS Lambda functions. It incorporates best practices such as environment variable management, secret handling, IAM role configuration, and code bundling optimization. Additionally, it includes helper functions to manage permissions and cross-account invocations, enhancing the flexibility and security of the deployed Lambda functions.
However, there are areas for improvement, particularly around IAM policy restrictions to adhere strictly to the principle of least privilege. The TODO comments indicate ongoing considerations to refine network configurations and environment type management, which are crucial for maintaining a secure and efficient infrastructure.
By leveraging AWS CDK's powerful abstractions and Python's flexibility, this code provides a robust foundation for deploying serverless applications with complex requirements.