TerraformでLambdaをデプロイする

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バケットに配置されました。

TerraformでLambdaをデプロイする

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;
};

ディレクトリ構成です。

TerraformでLambdaをデプロイする

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でLambdaをデプロイする

最後にterraform destroyしておきます。

Terraform Registry
Terraform Registry
Terraform Registry

コメント

株式会社CONFRAGE ITソリューション事業部をもっと見る

今すぐ購読し、続きを読んで、すべてのアーカイブにアクセスしましょう。

続きを読む

タイトルとURLをコピーしました