Skip to content

Instantly share code, notes, and snippets.

@CR11CS
Last active August 27, 2022 02:01
Show Gist options
  • Save CR11CS/44d023b28e52defc329e0c98accdeae0 to your computer and use it in GitHub Desktop.
Save CR11CS/44d023b28e52defc329e0c98accdeae0 to your computer and use it in GitHub Desktop.
Terraform (Windows) file to provision an AWS EC2 instance and associated RSA key pair then exports .pem SSH key to local device and outputs instance public IP for quick reference.
/*
Created by CR11CS
https://github.com/CR11CS
Generates an SSH keypair and stores SSH key to local folder, then outputs your server public IP for quick reference.
Windows Compatible version (using PowerShell)
*/
############################ Generic Terraform AWS EC2 Config
terraform {
required_version = "~>1.2.3"
required_providers {
aws = {
source = "hashicorp/aws"
version = ">=4.16"
}
}
}
provider "aws" {
region = "us-east-1"
}
resource "aws_instance" "example_server" {
ami = "ami-090fa75af13c156b4"
instance_type = "t2.micro"
key_name = "myKey"
// Waits for aws_key_pair resource generation first
depends_on = [
aws_key_pair.kp
]
}
// Output public IP for SSH
output "Server-IP" {
value = aws_instance.example_server.public_ip
}
############################ AWS Key Pair Generate & Store Locally
resource "tls_private_key" "pk" {
algorithm = "RSA"
rsa_bits = 4096
}
// Create aws_key_pair resource
resource "aws_key_pair" "kp" {
key_name = "myKey"
public_key = chomp(tls_private_key.pk.public_key_openssh)
// Executes local PowerShell code to write private key to local folder, same as downloading from EC2
provisioner "local-exec" {
command = <<EOT
'${tls_private_key.pk.private_key_pem}' | % {$_ -replace "`r", ""} | Set-Content -NoNewline ./'myKey.pem' -Force
EOT
interpreter = ["PowerShell", "-Command"]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment