LoginSignup
1
0

More than 5 years have passed since last update.

Terraform&AWS初心者のEC2インスタンス作成とping疎通

Last updated at Posted at 2018-07-10

概要

  • Terraformを使用してEC2インスタンスを1つ作成することが今回のゴール
  • ping疎通を可能にするため、ICMP通信を許可するセキュリティグループを付与する
  • 作業環境はMac

Terraformインストール

$ brew install terraform

手順

  1. AWSコンソールにて、IAMユーザーを作成し、アクセスキーとシークレットキーを取得
  2. IAMユーザに「AmazonEC2FullAccess」ポリシーを付与。これを付与しないと、TerraformからEC2インスタンスを作成できない
  3. Terraform用のファイルを作成(EC2インスタンス作成とセキュリティグループの作成および付与を定義)
  4. Terraformの実行

Terraform用のファイルを作成

  • 手順1,2は省略する。
  • 設定ファイル"sample.tf"にEC2インスタンス作成とセキュリティグループの作成および付与を定義
  • 変数用ファイル"terraform.tfvars"にアクセスキーとシークレットキーを定義

sample.tf

variable "access_key" {}
variable "secret_key" {}
variable "region" {
  default = "us-west-2"
}

provider "aws" {
  access_key = "${var.access_key}"
  secret_key = "${var.secret_key}"
  region     = "${var.region}"
}

resource "aws_security_group" "web-sg" {
    name = "web-sg"
    ingress {
    from_port = 8 // ICMP Type "Echo Request"
    to_port = 0 // ICMP Type "Echo Reply"
    protocol = "icmp"
    cidr_blocks = ["0.0.0.0/0"]
    }
}

resource "aws_instance" "web" {
    ami           = "ami-db710fa3"
    instance_type = "t2.micro"
    security_groups = ["${aws_security_group.web-sg.name}"]
}

terraform.tfvars

access_key = "XXXX"
secret_key = "XXXX"

sample.tfの"web"インスタンスへのセキュリティグループの付与は、以下のように直接セキュリティグループ名を与えるとエラーになるので注意。

security_groups = "web-sg"

このようなエラーとなる。

* aws_instance.web1: 1 error(s) occurred:

* aws_instance.web1: Error launching instance, possible mismatch of Security Group IDs and Names. See AWS Instance docs here: https://terraform.io/docs/providers/aws/r/instance.html.

    AWS Error: Value () for parameter groupId is invalid. The value cannot be empty

セキュリティグループのICMP許可の定義のfrom_portとto_portは、ICMP Typeを表している。(通常はポート番号)
https://docs.aws.amazon.com/ja_jp/AWSCloudFormation/latest/UserGuide/aws-properties-ec2-security-group-ingress.html

ICMP Type 一覧: http://www.infraexpert.com/info/5.0adsl.htm

Terraformの実行

以下のコマンドを実行すると、設定ファイルに定義したインスタンスとセキュリティグループが作成される。

$ terraform apply
.
.
.
aws_instance.web: Still creating... (10s elapsed)
aws_instance.web: Still creating... (20s elapsed)
aws_instance.web: Still creating... (30s elapsed)
aws_instance.web: Creation complete after 31s (ID: XXXXXX)

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.

参考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0