woshidan's blog

あいとゆうきとITと、とっておきの話。

Terraformで検証用インスタンスを立ち上げるのに使う最低限の作業についてメモ

検証用の環境作るとき、微妙に設定をいじって立て直す、その後複数台で動かしたい、みたいな場合はTerraformでやったりします*1

そのとき、共通でやる作業についてメモしておきます。

共通

変数設定など

アプリごとにパスフレーズなしの認証鍵を使い捨てで作る

$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/woshidan/.ssh/id_rsa): ./app_secret
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in ./app_secret.
Your public key has been saved in ./app_secret.pub.
access_key = "ACCCCCCCCCCCCCCCCCC"
secret_key = "/VXXXXXXKXXXXXXXXXXXXXXXXXXXXXXXXXX"
region = "ap-northeast-1"
ssh_key_path = "./app_secret.pub"
variable access_key {}
variable secret_key {}
variable region {}

# ssh-keygen -t rsa -f secret_key
variable ssh_key_path {}
# terraform plan --var-file=tf.vars
provider "aws" {
    access_key = "${var.access_key}"
    secret_key = "${var.secret_key}"
    region = "${var.region}"
}

resource "aws_key_pair" "app_secret" {
  key_name   = "app_secret"
  public_key = "${file("./app_secret.pub")}"
}

ざついセキュリティグループ

resource "aws_security_group" "sg-app-server" {
  name        = "app-server-sg"
  // 特に指定しなければデフォルトのVPN

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

  # HTTP access from anywhere
  ingress {
    from_port   = 80
    to_port     = 80
    protocol    = "tcp"
    cidr_blocks = ["0.0.0.0/0"]
  }

  # HTTPS access from anywhere
  ingress {
    from_port   = 443
    to_port     = 443
    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"]
  }
}

AMI作る時のちょっぱや用

refs: https://www.terraform.io/docs/providers/aws/r/instance.html

resource "aws_instance" "web" {
  // aws ec2 describe-images --owners amazon --filters 'Name=name,Valailable' | jq -r '.Images | sort_by(.CreationDate) | last(.[]).ImageId'
  ami           = "ami-08847abae18baa040"
  instance_type = "t2.micro"
  security_groups = ["${aws_security_group.sg-app-server.name}"]
  key_name = "${aws_key_pair.app_secret.key_name}"

  tags {
    Name = "HelloWorld"
  }
}
ssh -i app_secret ec2-user@ec2-12-345-67-89.ap-northeast-1.compute.amazonaws.com

AMI作成によく使うコマンド集

なんだか割とよくJava 1.8を入れている気がする。

yum install java-1.8.0-openjdk

refs: https://docs.aws.amazon.com/ja_jp/cli/latest/userguide/awscli-install-linux-python.html

# 古いバージョンを探す必要がある場合 http://www.atmarkit.co.jp/flinux/rensai/linuxtips/901instoldver.html
yum search python

yum install python

# ami-08847abae18baa040 の場合
$ python --version
Python 2.7.14

# AWSのLinux系インスタンスのEC2にはpythonは2系と3系が入っていてデフォルトでは2系の方が有効になっている
# 切り替えるときは https://aws.amazon.com/jp/premiumsupport/knowledge-center/python-boto3-virtualenv/ などが参考になる
$ python3 --version
Python 3.6.2

もっと色々覚えた気がするけどとりあえず先週分...、現場からは以上です。

*1:計画性がないと言われたらそれまでですが検証がひと段落して終わった後追加で試したいときにも便利...