Terraform Series - SSH Passwordless Login
First Method, I created a key pair called "ec2key" and I downloaded the private key.
I am going to create an EC2 instance using aws_instance resource and refer to the imported key as key_name = "ec2key"
# Terraform Block
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
# Provider Block
provider "aws" {
profile = "default" # AWS Credentials configured via AWS CLI.
region = "us-east-1"
}
# Resource Block
resource "aws_instance" "ec2demo" {
ami = "ami-0b5eea76982371e91" # Amazon Linux in us-east-1
instance_type = "t2.micro"
subnet_id = "subnet-0cfdbb9ad42fcf3c9"
security_groups = ["sg-0495b116a9de10f0c"]
key_name = "ec2key"
tags = {
"Name" = "webserver1"
}
}
Second Method, I generated key pair using openssl client and using "Resource: aws_key_pair" to copy the public key to EC2 instance.
# Terraform Block
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
}
}
}
# Provider Block
provider "aws" {
profile = "default" # AWS Credentials configured via AWS CLI.
region = "us-east-1"
}
# Resource Block
resource "aws_instance" "ec2demo" {
ami = "ami-0b5eea76982371e91" # Amazon Linux in us-east-1
instance_type = "t2.micro"
subnet_id = "subnet-0cfdbb9ad42fcf3c9"
security_groups = ["sg-0495b116a9de10f0c"]
tags = {
"Name" = "webserver1"
}
}
resource "aws_key_pair" "ec2key" {
key_name = "ec2_ssh_key"
public_key = file("aws_public")
}
Comments
Post a Comment