CloudWiki
Resource

Lambda Function

Amazon Web Services
Compute
AWS Lambda is a serverless, event-driven service that lets you run code for any type of application or backend service without provisioning or managing servers. The code is uploaded as a “Lambda function” and can be triggered from different AWS services or SaaS applications, while you only pay for the compute time consumed.
Terraform Name
terraform
aws_lambda_function
Lambda Function
attributes:

The following arguments are required:

  • function_name - (Required) Unique name for your Lambda Function.
  • role - (Required) Amazon Resource Name (ARN) of the function's execution role. The role provides the function's identity and access to AWS services and resources.

The following arguments are optional:

  • architectures - (Optional) Instruction set architecture for your Lambda function. Valid values are ["x86_64"] and ["arm64"]. Default is ["x86_64"]. Removing this attribute, function's architecture stay the same.
  • code_signing_config_arn - (Optional) To enable code signing for this function, specify the ARN of a code-signing configuration. A code-signing configuration includes a set of signing profiles, which define the trusted publishers for this function.
  • dead_letter_config - (Optional) Configuration block. Detailed below.
  • description - (Optional) Description of what your Lambda Function does.
  • environment - (Optional) Configuration block. Detailed below.
  • ephemeral_storage - (Optional) The amount of Ephemeral storage(/tmp) to allocate for the Lambda Function in MB. This parameter is used to expand the total amount of Ephemeral storage available, beyond the default amount of 512MB. Detailed below.
  • file_system_config - (Optional) Configuration block. Detailed below.
  • filename - (Optional) Path to the function's deployment package within the local filesystem. Conflicts with image_uri, s3_bucket, s3_key, and s3_object_version.
  • handler - (Optional) Function entrypoint in your code.
  • image_config - (Optional) Configuration block. Detailed below.
  • image_uri - (Optional) ECR image URI containing the function's deployment package. Conflicts with filename, s3_bucket, s3_key, and s3_object_version.
  • kms_key_arn - (Optional) Amazon Resource Name (ARN) of the AWS Key Management Service (KMS) key that is used to encrypt environment variables. If this configuration is not provided when environment variables are in use, AWS Lambda uses a default service key. If this configuration is provided when environment variables are not in use, the AWS Lambda API does not save this configuration and Terraform will show a perpetual difference of adding the key. To fix the perpetual difference, remove this configuration.
  • layers - (Optional) List of Lambda Layer Version ARNs (maximum of 5) to attach to your Lambda Function. See Lambda Layers
  • memory_size - (Optional) Amount of memory in MB your Lambda Function can use at runtime. Defaults to 128. See Limits
  • package_type - (Optional) Lambda deployment package type. Valid values are Zip and Image. Defaults to Zip.
  • publish - (Optional) Whether to publish creation/change as new Lambda Function Version. Defaults to false.
  • reserved_concurrent_executions - (Optional) Amount of reserved concurrent executions for this lambda function. A value of 0 disables lambda from being triggered and -1 removes any concurrency limitations. Defaults to Unreserved Concurrency Limits -1. See Managing Concurrency
  • runtime - (Optional) Identifier of the function's runtime. See Runtimes for valid values.
  • s3_bucket - (Optional) S3 bucket location containing the function's deployment package. Conflicts with filename and image_uri. This bucket must reside in the same AWS region where you are creating the Lambda function.
  • s3_key - (Optional) S3 key of an object containing the function's deployment package. Conflicts with filename and image_uri.
  • s3_object_version - (Optional) Object version containing the function's deployment package. Conflicts with filename and image_uri.
  • source_code_hash - (Optional) Used to trigger updates. Must be set to a base64-encoded SHA256 hash of the package file specified with either filename or s3_key. The usual way to set this is filebase64sha256("file.zip") (Terraform 0.11.12 and later) or base64sha256(file("file.zip")) (Terraform 0.11.11 and earlier), where "file.zip" is the local filename of the lambda function source archive.
  • tags - (Optional) Map of tags to assign to the object. If configured with a provider default_tags configuration block present, tags with matching keys will overwrite those defined at the provider-level.
  • timeout - (Optional) Amount of time your Lambda Function has to run in seconds. Defaults to 3. See Limits.
  • tracing_config - (Optional) Configuration block. Detailed below.
  • vpc_config - (Optional) Configuration block. Detailed below.

dead_letter_config

Dead letter queue configuration that specifies the queue or topic where Lambda sends asynchronous events when they fail processing. For more information, see Dead Letter Queues.

  • target_arn - (Required) ARN of an SNS topic or SQS queue to notify when an invocation fails. If this option is used, the function's IAM role must be granted suitable access to write to the target object, which means allowing either the sns:Publish or sqs:SendMessage action on this ARN, depending on which service is targeted.

environment

  • variables - (Optional) Map of environment variables that are accessible from the function code during execution.

ephemeral_storage

  • size - (Required) The size of the Lambda function Ephemeral storage(/tmp) represented in MB. The minimum supported ephemeral_storage value defaults to 512MB and the maximum supported value is 10240MB.

file_system_config

Connection settings for an EFS file system. Before creating or updating Lambda functions with file_system_config, EFS mount targets must be in available lifecycle state. Use depends_on to explicitly declare this dependency. See Using Amazon EFS with Lambda.

  • arn - (Required) Amazon Resource Name (ARN) of the Amazon EFS Access Point that provides access to the file system.
  • local_mount_path - (Required) Path where the function can access the file system, starting with /mnt/.

image_config

Container image configuration values that override the values in the container image Dockerfile.

  • command - (Optional) Parameters that you want to pass in with entry_point.
  • entry_point - (Optional) Entry point to your application, which is typically the location of the runtime executable.
  • working_directory - (Optional) Working directory.

tracing_config

  • mode - (Required) Whether to to sample and trace a subset of incoming requests with AWS X-Ray. Valid values are PassThrough and Active. If PassThrough, Lambda will only trace the request from an upstream service if it contains a tracing header with "sampled=1". If Active, Lambda will respect any tracing header it receives from an upstream service. If no tracing header is received, Lambda will call X-Ray for a tracing decision.

vpc_config

For network connectivity to AWS resources in a VPC, specify a list of security groups and subnets in the VPC. When you connect a function to a VPC, it can only access resources and the internet through that VPC. See VPC Settings.

  • security_group_ids - (Required) List of security group IDs associated with the Lambda function.
  • subnet_ids - (Required) List of subnet IDs associated with the Lambda function.

Associating resources with a
Lambda Function
Resources do not "belong" to a
Lambda Function
Rather, one or more Security Groups are associated to a resource.
Create
Lambda Function
via Terraform:
The following HCL creates a simple Lambda Function
Syntax:

resource "aws_lambda_function" "test_lambda" {
 # If the file is not in the current working directory you will need to include a
 # path.module in the filename.
 filename      = "lambda_function_payload.zip"
 function_name = "lambda_function_name"
 role          = aws_iam_role.iam_for_lambda.arn
 handler       = "index.test"

 # The filebase64sha256() function is available in Terraform 0.11.12 and later
 # For Terraform 0.11.11 and earlier, use the base64sha256() function and the file() function:
 # source_code_hash = "${base64sha256(file("lambda_function_payload.zip"))}"
 source_code_hash = filebase64sha256("lambda_function_payload.zip")

 runtime = "nodejs16.x"

 environment {
   variables = {
     foo = "bar"
   }
 }
}

Create
Lambda Function
via CLI:
Parametres:

create-function
--function-name <value>
[--runtime <value>]
--role <value>
[--handler <value>]
[--code <value>]
[--description <value>]
[--timeout <value>]
[--memory-size <value>]
[--publish | --no-publish]
[--vpc-config <value>]
[--package-type <value>]
[--dead-letter-config <value>]
[--environment <value>]
[--kms-key-arn <value>]
[--tracing-config <value>]
[--tags <value>]
[--layers <value>]
[--file-system-configs <value>]
[--image-config <value>]
[--code-signing-config-arn <value>]
[--architectures <value>]
[--ephemeral-storage <value>]
[--zip-file <value>]
[--cli-input-json | --cli-input-yaml]
[--generate-cli-skeleton <value>]
[--debug]
[--endpoint-url <value>]
[--no-verify-ssl]
[--no-paginate]
[--output <value>]
[--query <value>]
[--profile <value>]
[--region <value>]
[--version <value>]
[--color <value>]
[--no-sign-request]
[--ca-bundle <value>]
[--cli-read-timeout <value>]
[--cli-connect-timeout <value>]
[--cli-binary-format <value>]
[--no-cli-pager]
[--cli-auto-prompt]
[--no-cli-auto-prompt]

Example:

aws lambda create-function \
   --function-name my-function \
   --runtime nodejs14.x \
   --zip-file fileb://my-function.zip \
   --handler my-function.handler \
   --role arn:aws:iam::123456789012:role/service-role/MyTestFunction-role-tges6bf4

aws cost
Costs
AWS Lambda charges for the amount of compute time used by your functions. You are also charged for the number of requests made to your functions and the amount of storage used by your functions. The cost of running a Lambda function varies depending on the amount of resources used by the function and the duration of its execution.
Direct Cost

Lambda-GB-Second

Request

$ per GB - <Region> data transfer to <Region>

$ per GB - first 10 TB / month data transfer out beyond the global free tier

$ per GB for <Region>-AWS-Out-Bytes in <Region>

Indirect Cost
No items found.
Best Practices for
Lambda Function

Categorized by Availability, Security & Compliance and Cost

Low
Access allowed from VPN
No items found.
Low
Auto Scaling Group not in use
No items found.
Medium
Connections towards DynamoDB should be via VPC endpoints
No items found.
Medium
Container in CrashLoopBackOff state
No items found.
Low
EC2 with GPU capabilities
No items found.
Medium
EC2 with high privileged policies
No items found.
Medium
ECS cluster delete alarm
No items found.
Critical
ECS task with Admin access (*:*)
Medium
ECS task with high privileged policies
No items found.
Critical
EKS cluster delete alarm
No items found.
Medium
ElastiCache cluster delete alarm
No items found.
Medium
Ensure Container liveness probe is configured
No items found.
Medium
Ensure ECS task definition has memory limit
No items found.
Critical
Ensure EMR cluster master nodes are not publicly accessible
No items found.
More from
Amazon Web Services