こんにちは! 今回は、AWSのインフラストラクチャ構築を自動化できるIaCツールについて解説します。
IaCって便利そうだけど、種類が多くてどれを選べばいいか迷っちゃいますよね。
本記事では、AWS IaCツールの中から、よく使われる4つのツールをピックアップして、それぞれのメリット・デメリットやコード例などを紹介します。
IaCとは、インフラストラクチャの構成をコードで定義し、自動的に構築・管理する手法です。従来の手作業による構築と比べて、以下のメリットがあります。
AWSではさまざまなIaCツールが提供されていますが、今回は以下の4つを比較します。
AWS CloudFormationは、AWSのネイティブサービスであり、AWSリソースの構築を自動化するための IaC サービスです。JSON または YAML 形式でテンプレートを作成し、AWSリソースを定義します。CloudFormation は AWS のさまざまなサービスをサポートしており、インフラストラクチャをコードとして管理するための強力なツールです。
Resources:
MyDynamoDbTable:
Type: 'AWS::DynamoDB::Table'
Properties:
AttributeDefinitions:
- AttributeName: id
AttributeType: S
KeySchema:
- AttributeName: id
KeyType: HASH
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
MyLambdaFunction:
Type: 'AWS::Lambda::Function'
Properties:
Handler: index.handler
Role: !GetAtt MyLambdaRole.Arn
Runtime: nodejs14.x
Code:
ZipFile: |
exports.handler = async (event) => {
// Your Lambda function code here
};
MyLambdaRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: 'sts:AssumeRole'
Policies:
- PolicyName: LambdaPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: 'dynamodb:PutItem'
Resource: !GetAtt MyDynamoDbTable.Arn
MyApi:
Type: 'AWS::ApiGateway::RestApi'
Properties:
Name: MyApi
MyApiResource:
Type: 'AWS::ApiGateway::Resource'
Properties:
RestApiId: !GetAtt MyApi.RootResourceId
ParentId: !GetAtt MyApi.RootResourceId
PathPart: items
MyApiMethod:
Type: 'AWS::ApiGateway::Method'
Properties:
HttpMethod: POST
ResourceId: !Ref MyApiResource
RestApiId: !Ref MyApi
AuthorizationType: NONE
Integration:
Type: AWS_PROXY
IntegrationHttpMethod: POST
Uri: !Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/${MyLambdaFunction.Arn}/invocations'
MethodResponses:
- StatusCode: 200
LambdaApiGatewayPermission:
Type: 'AWS::Lambda::Permission'
Properties:
Action: lambda:InvokeFunction
FunctionName: !Ref MyLambdaFunction
Principal: apigateway.amazonaws.com
SourceArn: !Sub 'arn:aws:execute-api:${AWS::Region}:${AWS::AccountId}:${MyApi}/*/*/*'
AWS SAMは、サーバーレスアプリケーションの構築・デプロイを簡素化するためのフレームワークです。CloudFormation をベースに構築されており、サーバーレスリソースをより簡単に定義できます。SAMは、AWS Lambda、Amazon API Gateway、Amazon DynamoDB などのサーバーレスサービスに特化しており、これらのサービスを組み合わせたアプリケーションの構築を容易にします。
Resources:
MyDynamoDbTable:
Type: AWS::Serverless::SimpleTable
Properties:
PrimaryKey:
Name: id
Type: String
ProvisionedThroughput:
ReadCapacityUnits: 5
WriteCapacityUnits: 5
MyLambdaFunction:
Type: AWS::Serverless::Function
Properties:
Handler: index.handler
Runtime: nodejs14.x
CodeUri: ./src
Policies:
- DynamoDBWritePolicy:
TableName: !Ref MyDynamoDbTable
Events:
MyApi:
Type: Api
Properties:
Path: /items
Method: POST
Outputs:
ApiUrl:
Description: API Gateway endpoint URL for Prod stage for Hello World function
Value: !Sub 'https://${ServerlessRestApi}.execute-api.${AWS::Region}.amazonaws.com/Prod/items'
AWS CDKは、使い慣れたプログラミング言語を使用してインフラストラクチャを定義できるフレームワークです。 TypeScript、JavaScript、Python、Java、.NET、Go などの言語をサポートしており、オブジェクト指向の概念を使用してインフラストラクチャをモデル化できます。CDK は、インフラストラクチャコードの再利用性と保守性を向上させるための構成要素を提供します。
const cdk = require('@aws-cdk/core');
const lambda = require('@aws-cdk/aws-lambda');
const dynamodb = require('@aws-cdk/aws-dynamodb');
const apigateway = require('@aws-cdk/aws-apigateway');
class CdkStack extends cdk.Stack {
constructor(scope, id, props) {
super(scope, id, props);
// DynamoDB table
const table = new dynamodb.Table(this, 'MyDynamoDbTable', {
partitionKey: { name: 'id', type: dynamodb.AttributeType.STRING },
readCapacity: 5,
writeCapacity: 5,
});
// Lambda function
const myLambda = new lambda.Function(this, 'MyLambdaFunction', {
runtime: lambda.Runtime.NODEJS_14_X,
handler: 'index.handler',
code: lambda.Code.fromAsset('./src'),
});
// Grant Lambda permission to write to DynamoDB
table.grantWriteData(myLambda);
// API Gateway
const api = new apigateway.RestApi(this, 'MyApi', {
restApiName: 'My API',
});
const items = api.root.addResource('items');
items.addMethod('POST', new apigateway.LambdaIntegration(myLambda));
}
}
module.exports = { CdkStack };
Terraformは、HashiCorp によって開発されたオープンソースの IaC ツールです。
宣言型の構成ファイルを使用して、AWS を含むさまざまなクラウドプロバイダーのインフラストラクチャを定義できます。
Terraform は、モジュール化と状態管理の機能を備えており、大規模で複雑なインフラストラクチャを効率的に管理できます。
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_dynamodb_table" "example" {
name = "example"
read_capacity = 5
write_capacity = 5
hash_key = "id"
attribute {
name = "id"
type = "S"
}
}
resource "aws_lambda_function" "example" {
function_name = "example"
handler = "index.handler"
runtime = "nodejs14.x"
# The filebase64() function is available in Terraform 0.11.12 and later
# For Terraform 0.11.11 and earlier, use the base64encode() function and the file() function:
# code = "${base64encode(file("lambda_function_payload.zip"))}"
code = filebase64("lambda_function_payload.zip")
role = aws_iam_role.iam_for_lambda.arn
environment {
variables = {
foo = "bar"
}
}
}
resource "aws_iam_role" "iam_for_lambda" {
name = "iam_for_lambda"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_role_policy" "lambda_policy" {
name = "lambda_policy"
role = aws_iam_role.iam_for_lambda.id
# Terraform's "jsonencode" function converts a
# Terraform expression result to valid JSON syntax.
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Action = [
"dynamodb:GetItem",
"dynamodb:PutItem",
]
Effect = "Allow"
Resource = aws_dynamodb_table.example.arn
},
]
})
}
resource "aws_api_gateway_rest_api" "example" {
name = "example"
}
resource "aws_api_gateway_resource" "example" {
rest_api_id = aws_api_gateway_rest_api.example.id
parent_id = aws_api_gateway_rest_api.example.root_resource_id
path_part = "example"
}
resource "aws_api_gateway_method" "example" {
rest_api_id = aws_api_gateway_rest_api.example.id
resource_id = aws_api_gateway_resource.example.id
http_method = "ANY"
authorization = "NONE"
}
resource "aws_api_gateway_integration" "example" {
rest_api_id = aws_api_gateway_rest_api.example.id
resource_id = aws_api_gateway_resource.example.id
http_method = aws_api_gateway_method.example.http_method
integration_type = "aws_proxy"
integration_http_method = "POST"
type = "aws"
uri = aws_lambda_function.example.invoke_arn
}
それぞれのツールのメリット・デメリットを理解した上で、プロジェクトの要件に合わせて適切なツールを選択することが重要です。
AWS の IaC ツールには、それぞれメリット・デメリットがあります。
プロジェクトの要件やチームのスキルなどを考慮して、適切なツールを選択することが重要です。
AWSモダナイズ開発、基幹業務システムのUI.UX刷新はお気軽にお問い合わせください。
スモールスタート開発支援、サーバーレス・NoSQLのことなら
ラーゲイトまでご相談ください
低コスト、サーバーレスの
モダナイズ開発をご検討なら
下請け対応可能
Sler企業様からの依頼も歓迎