今回やること
Mac ローカルで公開鍵、秘密鍵を生成
Terraform で EC2 起動、セキュリティグループで SSH (ポート 22)許可、key-pair 登録
Terraform の Hello World 的なチュートリアルと思っていただけたら幸いです。
環境
Mac OS 10.12.3 (Sierra)
Terraform 0.9.1
公開鍵、秘密鍵生成 RSA フォーマットで鍵を生成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 $ ssh-keygen -t rsa Enter file in which to save the key (/Users/kenzo_tanaka/.ssh/id_rsa): /Users/kenzo_tanaka/.ssh/terraform-test Enter passphrase (empty for no passphrase): (空のままEnter) Enter same passphrase again: (空のままEnter) ... ... // 生成されたか確認 $ ls ~/.ssh/terraform-test* /Users/kenzo_tanaka/.ssh/terraform-test # 秘密鍵 /Users/kenzo_tanaka/.ssh/terraform-test.pub # 公開鍵
公開鍵を起動した EC2 インスタンスに登録し 秘密鍵でアクセスします。
以下のように利用する予定です。
1 $ ssh -i ~/.ssh/terraform-test <ec2 user>@<ec2 public ip>
Terraform 設定ファイル
Point !
resource "aws_key_pair"
で使用する公開鍵設定をしています。
resource "aws_security_group"
で SSH(ポート 22)を開いてます。
resource "aws_instance"
で使用しているセキュリティグループの指定は vpc_security_group_ids
を利用
セキュリティグループの条件追加・削除する場合にインスタンスを一度削除し作り直すことをしたくない場合に vpc_security_group_ids を利用すると良いです。
main.tf
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 provider "aws" { access_key = "${var.access_key}" secret_key = "${var.secret_key}" region = "${var.region}" } resource "aws_instance" "example" { ami = "${lookup(var.amis, var.region)}" instance_type = "t2.nano" key_name = "${aws_key_pair.auth.id}" vpc_security_group_ids = ["${aws_security_group.default.id}"] } resource "aws_key_pair" "auth" { key_name = "${var.key_name}" public_key = "${file(var.public_key_path)}" } resource "aws_security_group" "default" { name = "terraform_security_group" 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"] } }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 variable "access_key" {} variable "secret_key" {} variable "region" { default = "ap-northeast-1" } variable "amis" { type = "map" default = { us-east-1 = "ami-13be557e" us-west-2 = "ami-21f78e11" ap-northeast-1 = "ami-1bfdb67c" } } variable "key_name" { description = "Desired name of AWS key pair" } variable "public_key_path" { description = <<DESCRIPTION Path to the SSH public key to be used for authentication. Ensure this keypair is added to your local SSH agent so provisioners can connect. Example: ~/.ssh/terraform.pub DESCRIPTION }
1 2 3 4 5 access_key = "A******************Q" secret_key = "q**************************************Z" key_name = "terraform-test" public_key_path = "~/.ssh/terraform-test.pub"
いざ実行
確認
AWS コンソール上で起動確認
キーペアに terraform-test が指定されています。
vpc, subnet も自動的にアタッチされてます。
キーペア 一応キーペアを見てみると登録されているのがわかります。
1 $ ssh -i ~/.ssh/terraform-test ubuntu@ec2-54-65-244-25.ap-northeast-1.compute.amazonaws.com
無事 SSH ログインできました!
所感 terraform を見ながら各パラメータの利用意図を確認しながら 設定してみましたが パラメータの説明自体はざっくりで利用方法まではわからないです。
Teffaform のチュートリアル に始まり その他 Stack Overflow で 適宜パターンを蓄積していく学習が程よいと思います。
参考