Terraformの公式チュートリアルをやっていきます。
前提条件
- Terraform CLI (1.0.1+) がインストールされていること
- AWSアカウントを持っていること
- AWS CLI がインストールされていてアカウントの設定が完了していること
この記事では以前構築したCloud9の環境を使用します。

手順
このチュートリアルの最終的なコードはこちらのリポジトリにあります。
Terraformプロバイダーを指定
デプロイするリージョンを入力できるようにします。指定しなかった場合は米国東部が使用されます。
touch variables.tf
variable "aws_region" {
description = "AWS region for all resources."
type = string
default = "us-east-1"
}
プロバイダーの指定を行います。
touch main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0.0"
}
random = {
source = "hashicorp/random"
version = "~> 3.1.0"
}
archive = {
source = "hashicorp/archive"
version = "~> 2.2.0"
}
}
required_version = "~> 1.0"
}
provider "aws" {
region = var.aws_region
}
Lambda関数アーカイブをS3にアップロード
HTTPで”Hello, World!”を返します。
mkdir hello-world
touch hello-world/hello.js
module.exports.handler = async (event) => {
console.log('Event: ', event);
let responseMessage = 'Hello, World!';
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: responseMessage,
}),
}
}
バケットを作成し圧縮したスクリプトをアップロードします。
resource "random_pet" "lambda_bucket_name" {
prefix = "learn-terraform-functions"
length = 4
}
resource "aws_s3_bucket" "lambda_bucket" {
bucket = random_pet.lambda_bucket_name.id
force_destroy = true
}
resource "aws_s3_bucket_acl" "lambda_bucket_acl" {
bucket = aws_s3_bucket.lambda_bucket.id
acl = "private"
}
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 = aws_s3_bucket.lambda_bucket.id
key = "hello-world.zip"
source = data.archive_file.lambda_hello_world.output_path
etag = filemd5(data.archive_file.lambda_hello_world.output_path)
}
terraform init
terraform apply
yes
実行が完了するとS3にhello-world.zipがアップロードされます。
https://s3.console.aws.amazon.com/s3/

Lambda関数を作成
Lambda関数用のCloudWatchロググループとIAMロールも同時に作成します。
resource "aws_lambda_function" "hello_world" {
function_name = "HelloWorld"
s3_bucket = aws_s3_bucket.lambda_bucket.id
s3_key = aws_s3_object.lambda_hello_world.key
runtime = "nodejs12.x"
handler = "hello.handler"
source_code_hash = data.archive_file.lambda_hello_world.output_base64sha256
role = aws_iam_role.lambda_exec.arn
}
resource "aws_cloudwatch_log_group" "hello_world" {
name = "/aws/lambda/${aws_lambda_function.hello_world.function_name}"
retention_in_days = 30
}
resource "aws_iam_role" "lambda_exec" {
name = "serverless_lambda"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Effect = "Allow"
Sid = ""
Principal = {
Service = "lambda.amazonaws.com"
}
}
]
})
}
resource "aws_iam_role_policy_attachment" "lambda_policy" {
role = aws_iam_role.lambda_exec.name
policy_arn = "arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole"
}
Lambda関数の名前を出力するようにします。
touch outputs.tf
output "function_name" {
description = "Name of the Lambda function."
value = aws_lambda_function.hello_world.function_name
}
terraform apply
yes
実行が完了するとLambda関数が作成されます
https://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1#/functions

Lambda関数を呼び出して結果をresponse.jsonに保存します。
aws lambda invoke --region=us-east-1 --function-name=$(terraform output -raw function_name) response.json
{
"StatusCode": 200,
"ExecutedVersion": "$LATEST"
}
response.jsonを表示します。
cat response.json
{"statusCode":200,"headers":{"Content-Type":"application/json"},"body":"{\"message\":\"Hello, World!\"}"}
APIGatewayを使用してHTTP APIを作成
APIGateway用のCloudWatchロググループも同時に作成します。
resource "aws_apigatewayv2_api" "lambda" {
name = "serverless_lambda_gw"
protocol_type = "HTTP"
}
resource "aws_apigatewayv2_stage" "lambda" {
api_id = aws_apigatewayv2_api.lambda.id
name = "serverless_lambda_stage"
auto_deploy = true
access_log_settings {
destination_arn = aws_cloudwatch_log_group.api_gw.arn
format = jsonencode({
requestId = "$context.requestId"
sourceIp = "$context.identity.sourceIp"
requestTime = "$context.requestTime"
protocol = "$context.protocol"
httpMethod = "$context.httpMethod"
resourcePath = "$context.resourcePath"
routeKey = "$context.routeKey"
status = "$context.status"
responseLength = "$context.responseLength"
integrationErrorMessage = "$context.integrationErrorMessage"
}
)
}
}
resource "aws_apigatewayv2_integration" "hello_world" {
api_id = aws_apigatewayv2_api.lambda.id
integration_uri = aws_lambda_function.hello_world.invoke_arn
integration_type = "AWS_PROXY"
integration_method = "POST"
}
resource "aws_apigatewayv2_route" "hello_world" {
api_id = aws_apigatewayv2_api.lambda.id
route_key = "GET /hello"
target = "integrations/${aws_apigatewayv2_integration.hello_world.id}"
}
resource "aws_cloudwatch_log_group" "api_gw" {
name = "/aws/api_gw/${aws_apigatewayv2_api.lambda.name}"
retention_in_days = 30
}
resource "aws_lambda_permission" "api_gw" {
statement_id = "AllowExecutionFromAPIGateway"
action = "lambda:InvokeFunction"
function_name = aws_lambda_function.hello_world.function_name
principal = "apigateway.amazonaws.com"
source_arn = "${aws_apigatewayv2_api.lambda.execution_arn}/*/*"
}
output "base_url" {
description = "Base URL for API Gateway stage."
value = aws_apigatewayv2_stage.lambda.invoke_url
}
terraform apply
yes
実行が完了するとAPIGatewayが作成されます。
https://us-east-1.console.aws.amazon.com/apigateway/main/apis?region=us-east-1

HTTPリクエストを送ります。
curl "$(terraform output -raw base_url)/hello"
{"message":"Hello, World!"}
Lambda関数を更新
クエリパラメータのNameを返すように変更します。
module.exports.handler = async (event) => {
console.log('Event: ', event)
let responseMessage = 'Hello, World!';
if (event.queryStringParameters && event.queryStringParameters['Name']) {
responseMessage = 'Hello, ' + event.queryStringParameters['Name'] + '!';
}
return {
statusCode: 200,
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
message: responseMessage,
}),
}
}
terraform apply
yes
再度HTTPリクエストを送り、変更が反映されているか検証します。
curl "$(terraform output -raw base_url)/hello?Name=Terraform"
{"message":"Hello, Terraform!"}
クリーンアップ
terraform destroy
yes
実行が完了するとS3、Lambda、APIGatewayが破棄されます。
https://s3.console.aws.amazon.com/s3/buckets
https://us-east-1.console.aws.amazon.com/lambda/home?region=us-east-1#/functions
https://us-east-1.console.aws.amazon.com/apigateway/main/apis?region=us-east-1

