Infrastructure as Codeとは
IaC(Infrastructure as Code)は、サーバーやネットワークなどのインフラをコードで定義・管理するプラクティスです。手作業による設定ミスをなくし、環境の再現性・変更履歴管理を実現します。
TerraformとAnsibleの違い
| ツール | 種類 | 得意領域 |
|---|---|---|
| Terraform | プロビジョニング | インフラの作成・変更・削除 |
| Ansible | 構成管理 | サーバー内のソフトウェア設定 |
Terraformでクラウドリソースを作り、Ansibleでその中身を設定するのが定番の組み合わせです。
Terraform入門
# main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "ap-northeast-1"
}
resource "aws_instance" "web" {
ami = "ami-0c1de55112523456"
instance_type = "t3.micro"
tags = {
Name = "web-server"
Env = var.environment
}
}
output "public_ip" {
value = aws_instance.web.public_ip
}
terraform init # プロバイダーのダウンロード
terraform plan # 変更内容をプレビュー
terraform apply # 実際に適用
terraform destroy # リソースを削除
Ansibleの基本
# playbook.yml
- name: Webサーバーのセットアップ
hosts: web_servers
become: yes
tasks:
- name: Nginxのインストール
apt:
name: nginx
state: present
update_cache: yes
- name: Nginxの設定コピー
template:
src: nginx.conf.j2
dest: /etc/nginx/nginx.conf
notify: nginx再起動
- name: Nginxの起動と自動起動
service:
name: nginx
state: started
enabled: yes
handlers:
- name: nginx再起動
service:
name: nginx
state: restarted
ansible-playbook -i inventory.ini playbook.yml
状態管理のベストプラクティス
Terraformの状態ファイル(terraform.tfstate)はS3などのリモートバックエンドで管理します。
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "ap-northeast-1"
}
}
IaCを導入することで、開発・ステージング・本番の環境差異をなくし、災害時の復旧時間を劇的に短縮できます。





