Terraform
- VPC1つの中にSubnetを切ってその中にEC2を1つ
- インターネットのアクセスをすべて受け入れる(
0.0.0.0/0
)設定なので、yourIp/32
に置き換えた方がいいかもしれない
- インターネットのアクセスをすべて受け入れる(
# provider
provider "aws" {
version = "~> 2.0"
region = "ap-northeast-1"
}
# VPC
resource "aws_vpc" "VPC" {
cidr_block = "10.1.0.0/16"
instance_tenancy = "default"
enable_dns_support = "true"
enable_dns_hostnames = "false"
tags = {
Name = "Terraform-VPC"
}
}
# IGW
resource "aws_internet_gateway" "GW" {
vpc_id = "${aws_vpc.VPC.id}"
tags = {
Name = "Terraform-IGW"
}
}
# Subnet
resource "aws_subnet" "public-subnet" {
vpc_id = "${aws_vpc.VPC.id}"
cidr_block = "10.1.1.0/24"
availability_zone = "ap-northeast-1a"
tags = {
Name = "Terraform-subnet"
}
}
# route table
resource "aws_route_table" "public-route" {
vpc_id = "${aws_vpc.VPC.id}"
route {
cidr_block = "0.0.0.0/0"
gateway_id = "${aws_internet_gateway.GW.id}"
}
tags = {
Name = "Terraform-rtb"
}
}
# routing
resource "aws_route_table_association" "puclic-routing" {
subnet_id = "${aws_subnet.public-subnet.id}"
route_table_id = "${aws_route_table.public-route.id}"
}
# SG
resource "aws_security_group" "Terraform-EC2-SG" {
name = "Terraform-ec2"
description = "Allow SSH And HTTP inbound traffic"
vpc_id = "${aws_vpc.VPC.id}"
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"]
}
tags = {
Name = "Terraform-SG"
}
}
# 最新のAMIを取得
data aws_ssm_parameter amzn2_ami {
name = "/aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2"
}
# EC2
resource "aws_instance" "Terraform-ec2" {
ami = data.aws_ssm_parameter.amzn2_ami.value
instance_type = "t2.micro"
key_name = "Key-Name"
vpc_security_group_ids = [
"${aws_security_group.Terraform-EC2-SG.id}"
]
subnet_id = "${aws_subnet.public-subnet.id}"
associate_public_ip_address = "true"
root_block_device {
volume_type = "gp2"
volume_size = "20"
}
tags = {
Name = "Terraform EC2"
}
user_data = "${file("./userdata.sh")}"
}
UserData
- なんか入れたい奴書く
#! /bin/bash
# なんか入れたい奴書く
yum update -y
書いてみた感想
- CloudFormationより見てくれが美しい
- 秘密鍵をフォルダ内に内包できるのがうれしい
- CloudFormationは特殊な方法を使わないと無理だと思う
- AlibabaやYandex Cloudまで対応しているので、中国やロシア進出があっても安心
- いろいろ変数が使えるので使った方が楽(tagsとか特に)だけど、使いすぎると可読性が落ちる
- 複数人で書くときは特にそうだった