①Cloud9でprovider.tfを作成する

  1. provider "aws" {
  2. region = "ap-northeast-1"
  3. }

 

②cloud9でaws_vpc.tfを作成する

 

  1. #----------------------------------------
  2. # VPCの作成
  3. #----------------------------------------
  4. resource "aws_vpc" "sample_vpc" {
  5. cidr_block = "10.0.0.0/16"
  6. enable_dns_hostnames = true
  7. }
  8.  
  9. #----------------------------------------
  10. # パブリックサブネットの作成
  11. #----------------------------------------
  12. resource "aws_subnet" "sample_subnet" {
  13. vpc_id = aws_vpc.sample_vpc.id
  14. cidr_block = "10.0.1.0/24"
  15. availability_zone = "ap-northeast-1a"
  16. map_public_ip_on_launch = true
  17. }
  18.  
  19. #----------------------------------------
  20. # インターネットゲートウェイの作成
  21. #----------------------------------------
  22. resource "aws_internet_gateway" "sample_igw" {
  23. vpc_id = aws_vpc.sample_vpc.id
  24. }
  25.  
  26. #----------------------------------------
  27. # ルートテーブルの作成
  28. #----------------------------------------
  29. resource "aws_route_table" "sample_rtb" {
  30. vpc_id = aws_vpc.sample_vpc.id
  31.  
  32. route {
  33. cidr_block = "0.0.0.0/0"
  34. gateway_id = aws_internet_gateway.sample_igw.id
  35. }
  36. }
  37.  
  38. #----------------------------------------
  39. # サブネットにルートテーブルを紐づけ
  40. #----------------------------------------
  41. resource "aws_route_table_association" "sample_rt_assoc" {
  42. subnet_id = aws_subnet.sample_subnet.id
  43. route_table_id = aws_route_table.sample_rtb.id
  44. }
  45.  
  46. #----------------------------------------
  47. # セキュリティグループの作成
  48. #----------------------------------------
  49. resource "aws_security_group" "sample_sg" {
  50. name = "sample-sg"
  51. vpc_id = aws_vpc.sample_vpc.id
  52.  
  53. ingress {
  54. from_port = 80
  55. to_port = 80
  56. protocol = "tcp"
  57. cidr_blocks = ["0.0.0.0/0"]
  58. }
  59.  
  60. egress {
  61. from_port = 0
  62. to_port = 0
  63. protocol = "-1"
  64. cidr_blocks = ["0.0.0.0/0"]
  65. }
  66.  
  67. }
 
cloud9でaws_ec2.tfを作成する
  1. #----------------------------------------
  2. # EC2インスタンスの作成
  3. #----------------------------------------
  4. resource "aws_instance" "sample_web_server" {
  5. ami = "ami-09d28faae2e9e7138" # Amazon Linux 2
  6. instance_type = "t2.micro"
  7. subnet_id = aws_subnet.sample_subnet.id
  8. vpc_security_group_ids = [aws_security_group.sample_sg.id]
  9.  
  10. user_data = <<EOF
  11. #! /bin/bash
  12. sudo yum install -y httpd
  13. sudo systemctl start httpd
  14. sudo systemctl enable httpd
  15. EOF
  16.  
  17. }
④$ terraform apply で実行する
Apply complete! Resources: 7 added, 0 changed, 0 destroyed.
と出力されていればapplyは成功しています。
 
⑤AWSマネジメントコンソールのVPC、EC2の画面に遷移し、問題なく構築されていることを確認します。
 
 

 

以上