Software Engineering

How to create an AWS Lambda in Terraform


Step 1 – Lambda Code in Python

The following code expects a python file with the contents as follows in a file called python/script1.py:

def lambda_handler(event, context):
    return {
        'code': 200,
        'message': 'Triggered'
    }

Step 2 – Lambda Code in Terraform

Now we create the lambda.tf:

data "archive_file" "zip_python_code_create" {
  type        = "zip"
  source_file = "python/script1.py"
  output_path = "python/script1.zip"
}

resource "aws_lambda_function" "lambda_script1" {
  filename      = "python/script1.zip"
  function_name = "LambdaScript1"
  role          = aws_iam_role.lambda_role.arn
  description   = "LambdaScript1"
  handler       = "create.lambda_handler"
  runtime       = "python3.8"
  depends_on    = [aws_iam_role_policy_attachment.attach_iam_policy_to_iam_role]
}

Step 3 – IAM and Permissions in Terraform

We need to specify the permissions for the Lambda:

resource "aws_iam_role" "lambda_role" {
  name   = "PipelineApprovals_Lambda_Function_Role"
  assume_role_policy = jsonencode({
   Version: "2012-10-17",
   Statement: [
     {
       Action: "sts:AssumeRole",
       Principal: {
         Service: "lambda.amazonaws.com"
       },
       Effect: "Allow",
       Sid: ""
     }
   ]
  })
}

resource "aws_iam_policy" "iam_policy_for_lambda" {
  name         = "aws_iam_policy_for_terraform_aws_lambda_role"
  path         = "/"
  description  = "AWS IAM Policy for managing aws lambda role"
  policy = jsonencode({
    Version: "2012-10-17",
    Statement: [{
      Action: [
        "logs:*"
      ],
      Resource: "*",
      Effect: "Allow"
    }]
  })
}

resource "aws_iam_role_policy_attachment" "attach_iam_policy_to_iam_role" {
  role        = aws_iam_role.lambda_role.name
  policy_arn  = aws_iam_policy.iam_policy_for_lambda.arn
}

resource "aws_iam_role" "pipeline-approvals-ci-role" {
  assume_role_policy = jsonencode({
    Version: "2012-10-17",
    Statement: [{
      Action: "sts:AssumeRole",
      Principal: {
        Service: "lambda.amazonaws.com"
      },
      Effect: "Allow"
    }]
  })
}