SSH into an EC2 Instance Launched with a Key Pair Registered via Terraform
What We’ll Do This Time
- Generate a public key and a private key locally on a Mac
- Use Terraform to launch an EC2 instance, allow SSH (port 22) via a security group, and register the key pair
Think of this as a “Hello World” style tutorial for Terraform.
Environment
- Mac OS 10.12.3 (Sierra)
- Terraform 0.9.1
Generating the Public and Private Keys
Generate the keys in RSA format.
1 | $ ssh-keygen -t rsa |
We’ll register the public key on the launched EC2 instance and access it with the private key.
We plan to use it as follows.
1 | $ ssh -i ~/.ssh/terraform-test <ec2 user>@<ec2 public ip> |
Terraform Configuration Files
Point!
- The public key configuration used is set in
resource "aws_key_pair". - SSH (port 22) is opened in
resource "aws_security_group". - The security group used in
resource "aws_instance"is specified viavpc_security_group_ids.- Using
vpc_security_group_idsis a good idea when you don’t want the instance to be destroyed and recreated each time you add or remove security group conditions.
- Using
- The public key configuration used is set in
main.tf
1 | provider "aws" { |
- variables.tf
1 | variable "access_key" {} |
- terraform.tfvars
1 | access_key = "A******************Q" |
Let’s Run It
- Check the execution plan
1 | $ terraform plan |
- Apply
1 | $ terraform apply |
Verification
Verify the launch in the AWS console
terraform-testis specified as the key pair.- The VPC and subnet are also attached automatically.
- Key pair
If you take a look at the key pairs, you can confirm it has been registered.
- Verify the security group
- Verify SSH login
1 | $ ssh -i ~/.ssh/terraform-test ubuntu@ec2-54-65-244-25.ap-northeast-1.compute.amazonaws.com |
SSH login succeeded!
Impressions
I configured this while referring to terraform to check the intended use of each parameter, but the parameter descriptions themselves are rather rough and don’t go as far as explaining how to use them.
I think a good way to learn is to start with the Terraform tutorial and then accumulate patterns as needed from sources like Stack Overflow.
References

Terraformで立てたEC2に後からSGを追加しようとするとEC2が再作成される - tjinjin's blog
About 初回に立てた時はSGが1つだったが、あとからSGを追加したくなったときどうなるか試した結果です。

