masalibの日記

システム開発、運用と猫の写真ブログです

terraformはaws構成ツールとして便利だね

機械学習の勉強の備忘録 その6です
機械学習の勉強なのにサーバー構成ツールを
勉強するという意味のわからない記事です
前回のDeNAの勉強会で知った
terraformについて勉強しました


terraformというのはクラウドの構成ツールです
vagrantというサーバー構成ツールを作った会社が作りました
自分のイメージだと
vagrantはローカル
・terraformはクラウド

aws以外にGCPも同じツールで管理できるみたいで
便利だね

また環境に依存されないつくりで
macでもwindowsでも動きます

若干、バージョンは古いが
下記のサイトを参考にしました

Terraform for さくらのクラウド スタートガイド (第一回) ~インストールから基本操作 ~ | さくらのナレッジ
dev.classmethod.jp

普通の人はハマらずにインストールできると思います
自分のmacは2011年に購入したものなので
単純にインストールができず、結局パスを無理やり認識させた

terraformを使う前に
しないといけないことがあります
IAMというセキュリティの設定です

ec2に関してフルオープンなアカウントを作成します
ファイルをダウンロードする
access_keyとsecret_keyをメモる
この記事では
xxxxxxxaccess_keyxxxxxxx
xxxxxxxsecret_keyxxxxxxx
と表現しています

AWS IAMポリシーを理解する | Developers.IO

を参考にしました

鍵はterraformでもできるのですが
めんどくさいのでguiで作成しました
kenzo0107.hatenablog.com

つくったキーファイル名はterraform-us-east-1です
やりたいことは機械学習なのでシンプルな構成でいきました

f:id:masalib:20170402211237j:plain

前提としては
キーファイル名はterraform-us-east-1
リージョンはus-east-1です
(東京のリージョンはGPUが対応していない)

ec2のインスタンスの作成をおこなう
前回と同様に適当なフォルダを作成する

mkdir ec2-test
作成したフォルダに移動して下記のファイルを作成する

ec2-test/aws_region.tf

provider "aws" {
    access_key = "xxxxxxxaccess_keyxxxxxxx"
    secret_key = "xxxxxxxsecret_keyxxxxxxx"
    region = "us-east-1"
}

ec2-test/variable.tf

variable "key_name" {
    default = "terraform-us-east-1" # key pairを指定
}
variable "security_group_name" {
    default = "terraform_example" # セキュリティグループ
}

ec2-test/ec2-crate.tf

resource "aws_instance" "example" {
    ami = "ami-0b33d91d" # 好きな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 = "ec2-test"
    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"]

    }

    # HTTP access from the VPC
    ingress {
      from_port   = 80
      to_port     = 80
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }
    # HTTP(graph) access from the VPC
    ingress {
      from_port   = 6006
      to_port     = 6006
      protocol    = "tcp"
      cidr_blocks = ["0.0.0.0/0"]
    }

    # outbound internet access
    egress {
      from_port   = 0
      to_port     = 0
      protocol    = "-1"
      cidr_blocks = ["0.0.0.0/0"]
    }

}


planは実際につくらずにテストしてくれるものです
planで成功したからといって過信してはいけない
セキュリティの設定ミスとかでよくエラーになる

terraform plan

エラーなく終わったら

terraform apply

で作成する

もしいらなくなったら

terraform destroy

で削除できる

次回は、sporリクエストでの
terraformをあきらめた・・・です(笑)