LoginSignup
6
6

More than 5 years have passed since last update.

terraformでsshアクセス可能なEC2インスタンスを作成する

Posted at

目的

とにかくterraform使って、簡単にsshアクセスできるEC2インスタンス作成したい。

環境

  • terraform v0.3.6
  • OSX 10.10.3

前提

  • 権限のあるIAMユーザを作成
  • instanceに導入する公開鍵を事前に作成

terraformを導入する

Macだとbrew install terraformで導入できます。ただしバージョンが若干古いです。(20150513時点の最新はv0.5.0)

設定ファイルを作成する

  • 基本の設定ファイル
example.tf
resource "aws_instance" "example" {
    ami = "ami-89634988" # 好きなAMIを選択
    instance_type = "t2.micro"
    key_name = "${var.key_name}"

    # Our Security group to allow HTTP and SSH access
    security_groups = ["${aws_security_group.default.name}"]
}

resource "aws_security_group" "default" {
    name = "terraform_example"
    description = "Used in the terraform"

    # SSH access from anywhere
    ingress {
        from_port = 22
        to_port = 22
        protocol = "tcp"
        cidr_blocks = ["0.0.0.0/0"]

    }

}
  • IAMの情報を持ってるファイル(gitにコミットしない!)
aws_region.tf
provider "aws" {
    access_key = ""
    secret_key = ""
    region = "ap-northeast-1"
}
  • 変数ファイル
variable.tf
variable "key_name" {
    default = "key-name" # key pairを指定
}
  • 上記3ファイルをカレントに作成し、terraform applyを実行するとEC2インスタンスができるはずです。たぶんこんなにファイルわけなくてもいいはず

終わりに

とりあえず作成するだけなら簡単にできました。VPCがファイルの構成とかもう少し考えたほうがよさそうです。公式のサンプルもあるので、そちらも参考になると思います。

参考

6
6
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
6
6