①Cloud9でprovider.tfを作成する
provider "aws" {
region = "ap-northeast-1"
}
②cloud9でaws_vpc.tfを作成する
#----------------------------------------
# VPCの作成
#----------------------------------------
resource "aws_vpc" "sample_vpc" {
cidr_block = "10.0.0.0/16"
enable_dns_hostnames = true
}
#----------------------------------------
# パブリックサブネットの作成
#----------------------------------------
resource "aws_subnet" "sample_subnet" {
vpc_id = aws_vpc.sample_vpc.id
cidr_block = "10.0.1.0/24"
availability_zone = "ap-northeast-1a"
map_public_ip_on_launch = true
}
#----------------------------------------
# インターネットゲートウェイの作成
#----------------------------------------
resource "aws_internet_gateway" "sample_igw" {
vpc_id = aws_vpc.sample_vpc.id
}
#----------------------------------------
# ルートテーブルの作成
#----------------------------------------
resource "aws_route_table" "sample_rtb" {
vpc_id = aws_vpc.sample_vpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.sample_igw.id
}
}
#----------------------------------------
# サブネットにルートテーブルを紐づけ
#----------------------------------------
resource "aws_route_table_association" "sample_rt_assoc" {
subnet_id = aws_subnet.sample_subnet.id
route_table_id = aws_route_table.sample_rtb.id
}
#----------------------------------------
# セキュリティグループの作成
#----------------------------------------
resource "aws_security_group" "sample_sg" {
name = "sample-sg"
vpc_id = aws_vpc.sample_vpc.id
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"]
}
}
③cloud9でaws_ec2.tfを作成する
#----------------------------------------
# EC2インスタンスの作成
#----------------------------------------
resource "aws_instance" "sample_web_server" {
ami = "ami-09d28faae2e9e7138" # Amazon Linux 2
instance_type = "t2.micro"
subnet_id = aws_subnet.sample_subnet.id
vpc_security_group_ids = [aws_security_group.sample_sg.id]
user_data = <<EOF
#! /bin/bash
sudo yum install -y httpd
sudo systemctl start httpd
sudo systemctl enable httpd
EOF
}
④$ terraform apply で実行する
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.
と出力されていればapplyは成功しています。
と出力されていればapplyは成功しています。
⑤AWSマネジメントコンソールのVPC、EC2の画面に遷移し、問題なく構築されていることを確認します。
以上