はじめに
インフラのコード化とかよく聞くが、実際に使っているわけではないのでよくわからない、インフラのコード記載でどこまでできるのかいまいちわからない、自動化という点でdockerとの違いは何なのか、曖昧だったのが大体わかるようになったのでそのメモ。
できることを具体的に
例えばAWSでEC2インスタンスを作って何か表示させるのを自動化することは可能。
※AWSでWebページを表示したいならばその箇所の知識は必要。
Terraform設定例
1. プロバイダの設定
provider "aws" {
region = "us-west-2" // ここに適切なリージョンを指定
}
2. セキュリティグループの設定
HTTP (ポート80) とSSH (ポート22) が開く。
resource "aws_security_group" "laravel_sg" {
name = "laravel_sg"
description = "Security group for Laravel application"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
3. EC2インスタンスの設定
Amazon Linux 2 AMIを使用して、Apache HTTPサーバーをインストールし、簡単なHTMLページを表示するためのuser_dataスクリプトの例。
resource "aws_instance" "web_instance" {
ami = "ami-xxxxxxxxxxxxxxxxx" // 適切なAMI IDを指定
instance_type = "t2.micro" // インスタンスタイプを指定
security_groups = [aws_security_group.web_sg.name]
user_data = <<-EOF
#!/bin/bash
sudo yum update -y
sudo yum install -y httpd
sudo systemctl start httpd
sudo systemctl enable httpd
echo '<html><h1>Hello, World!</h1><p>This is a test page.</p></html>' | sudo tee /var/www/html/index.html
EOF
tags = {
Name = "WebServerInstance"
}
}
4. Terraformの実行
-
Terraformを初期化します:
terraform init
-
プランを作成し、どのようなリソースが作成されるかを確認します:
terraform plan
-
リソースをデプロイします:
terraform apply
上記設定記載確認方法
例えばAWSのプロバイダを使用して記載したい場合、terraform AWS providerで、以下を検索し、設定等行う。
まとめ
TerraformでAWSを使用するとEC2作成までをコード化できる。
よって何度も手動でもう一度作る必要はなくなる。
dockerとの違い
以下で棲み分けは大体ピンとくるようになった。
・Terraform:インフラストラクチャのプロビジョニングを担う
・Docker:アプリケーションのコンテナー化を担う
おわりに
きっかけは掴んだ、あとは実際に構築していく。
情報や最初のとっつきにくさに惑わされたりはもうしない。
参考記事
terafform aws providerとかで
https://registry.terraform.io/providers/hashicorp/aws/latest/docs