TerraformでLambdaをデプロイする
Lambdaアーカイブ
新規ディレクトリでmain.tf作成します。
main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
archive = {
source = "hashicorp/archive"
version = "~> 2.2.0"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "ap-northeast-1"
}
data "archive_file" "lambda_hello_world" {
type = "zip"
source_dir = "${path.module}/hello-world"
output_path = "${path.module}/hello-world.zip"
}
resource "aws_s3_object" "lambda_hello_world" {
bucket = "aabbcc12"
key = "hello-world.zip"
source = data.archive_file.lambda_hello_world.output_path
etag = filemd5(data.archive_file.lambda_hello_world.output_path)
}
bucketは既存のバケット「aabbcc12」とします。
初期化して適用します。
$ terraform init $ terraform apply
zipがS3バケットに配置されました。
Lambdaデプロイ
Lambdaをhello-worldディレクトリ配下に作成します。
mkdir hello-world cd hello-world touch index.mjs
index.mjs
export const handler = async(event) => {
// TODO implement
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!'),
};
return response;
};
ディレクトリ構成です。
main.tfを追記します。
main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.16"
}
}
required_version = ">= 1.2.0"
}
provider "aws" {
region = "ap-northeast-1"
}
data "archive_file" "lambda_hello_world" {
type = "zip"
source_dir = "${path.module}/hello-world"
output_path = "${path.module}/hello-world.zip"
}
resource "aws_s3_object" "lambda_hello_world" {
bucket = "aabbcc12"
key = "hello-world.zip"
source = data.archive_file.lambda_hello_world.output_path
etag = filemd5(data.archive_file.lambda_hello_world.output_path)
}
resource "aws_lambda_function" "hello_world" {
function_name = "HelloWorld"
s3_bucket = "aabbcc12"
s3_key = aws_s3_object.lambda_hello_world.key
runtime = "nodejs18.x"
handler = "hello.handler"
source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256
role = "arn:aws:iam::123456789012:role/SampleRole"
}
roleは既存のロールのarn「arn:aws:iam::123456789012:role/SampleRole」としています。
S3も既存のバケット「aabbcc12」とします。
terraform apply
Lambdaデプロイできました。
最後にterraform destroyしておきます。
Terraform Registry
Terraform Registry
Terraform Registry

KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES20xx),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^




コメント