How to launch an EC2 instance without key pair via Terraform?

Viewed 699

I would like to launch an EC2 instance without key pair with my Terraform configuration. I could not find any info on internet which indicates usage of "no keypair" in Terraform. Anyone who have configured Terraform to be used this way?

1 Answers

Here's Terraform script that makes an EC2 instance of type t2.micro without a key and output its IP address.

terraform.tf:

provider "aws" {
  profile = "default"
  region  = "us-west-2"
}

variable "instance_type" {
 default = "t2.micro"
}

resource "aws_instance" "ec2_instance" {
 ami = "ami-0d1cd67c26f5fca19"
 instance_type = "var.instance_type"
}

output "ip" {
 value = "aws_instance.ec2_instance.public_ip"
}

Put it on a dir and run it by using this command terraform apply. You can use terraform plan for testing it.

Note: Don't forget to add your access_key and secret_key to your local aws configuration (aws configure) in order for it to work. You can also use aws-vault to avoid mistakenly exposing your credentials.

Related