Infrastructure as Code と Terraform について
こんにちは。NOBORIの村田です。
医療機関向けにAIを用いた診断支援プラットフォームの開発をしています。
今回はクラウド環境の構築自動化に取り組んだ際に活用した、Infrastructure as Code とTerraformについて記事を書いてみようと思います。
Infrastructure as Code とは
Infrastructure as code とはインフラの構成をコード化して管理することです。
コードで管理することによって、バージョン管理や他のメンバーによるレビューが可能になり、また他のチームの設定を見て参考に出来るなどのメリットがあります。
ツール
Infrastructure as Codeを実現するために様々なツールがあります。
Cloud Formation、Terraform、Ansibleなどがあります。
今回はこの中からクラウド環境のプロビジョニングツールであるTerraformについて紹介します。
Terraformとは
OSSのマルチクラウドプロビジョニングツールです。
またクラウド環境だけでなく様々なSaaSにも対応しており、例えばDatadogの監視設定や、Dashbordもコード化することが可能です。
Terraformのサンプル
1. Terraformテンプレートの作成
provider "aws" {
profile = "default"
region = "ap-northeast-1"
}
resource "aws_vpc" "main" {
cidr_block = "10.0.0.0/16"
instance_tenancy = "default"
tags = {
Name = "main-vpc",
Environment = "prd"
}
}
2. ディレクトリの初期化
# コマンド
$ terraform init
3. 定義した内容のチェック
# コマンド
$ terraform plan
# 出力結果
An execution plan has been generated and is shown below.
Resource actions are indicated with the following symbols:
+ create
Terraform will perform the following actions:
# aws_vpc.main will be created
+ resource "aws_vpc" "main" {
+ arn = (known after apply)
+ assign_generated_ipv6_cidr_block = false
+ cidr_block = "10.0.0.0/16"
+ default_network_acl_id = (known after apply)
+ default_route_table_id = (known after apply)
+ default_security_group_id = (known after apply)
+ dhcp_options_id = (known after apply)
+ enable_classiclink = (known after apply)
+ enable_classiclink_dns_support = (known after apply)
+ enable_dns_hostnames = (known after apply)
+ enable_dns_support = true
...
}
Plan: 1 to add, 0 to change, 0 to destroy.
------------------------------------------------------------------------
Note: You didn't specify an "-out" parameter to save this plan, so Terraform
can't guarantee that exactly these actions will be performed if
"terraform apply" is subsequently run.
4. 定義した内容の反映
# コマンド
$ terraform apply
# 出力結果
Plan: 1 to add, 0 to change, 0 to destroy.
Do you want to perform these actions?
Terraform will perform the actions described above.
Only 'yes' will be accepted to approve.
Enter a value: yes
aws_vpc.main: Creating...
aws_vpc.main: Creation complete after 2s [id=vpc-0029053e5cfc1f7d6]
Apply complete! Resources: 1 added, 0 changed, 0 destroyed
まとめ
今回はInfrastructure as Code と Terraformの基本的な使い方について紹介させていただきました。
Github Actionsを使ってTerraformの実行を自動化する仕組みも入れているので次回はそちらも紹介したいと思います。