Last active
June 14, 2024 15:19
-
-
Save sheikhnavezz/1cb111c42b58cde476a36b84cbbafe59 to your computer and use it in GitHub Desktop.
Terraform code creating EC2 instance with keypair
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
project_directory/ | |
├──provider.tf | |
├── main.tf | |
├── Modules | |
├── Key_pair/ | |
└── main.tf | |
├── ec2/ | |
└── main.tf | |
└── variables.tf | |
└── Output.tf | |
-------------------------------------------------------------------------------------------------------------------------------------- | |
provider.tf: | |
terraform { | |
required_providers { | |
aws = { | |
source = "hashicorp/aws" | |
version = "~> 5.0" | |
} | |
} | |
} | |
provider "aws" { | |
region = "us-east-2" | |
access_key: "**********" | |
Secret_access_key: "*********" | |
} | |
main.tf: | |
module "instance" { | |
source = "./modules/ec2" | |
instance = "ami-09040d770ffe2224f" | |
instance_type = "t2.micro" | |
key_name = module.key_pair.key_name | |
} | |
module "key_pair" { | |
source = "./modules/key_pair" | |
} | |
modules/ec2/main.tf: | |
resource "aws_instance" "example" { | |
ami = var.instance | |
instance_type = var.instance_type | |
key_name = var.key_name | |
security_groups = ["default"] | |
tags = { | |
Name = "my-server" | |
} | |
} | |
modules/ec2/output.tf: | |
output "instance_id" { | |
description = "The ID of the EC2 instance" | |
value = aws_instance.example.id | |
} | |
modules/ec2/variable.tf: | |
variable "instance" { | |
description = "this is the value of the instance" | |
} | |
variable "instance_type" { | |
description = "this is the value of the instance type" | |
} | |
variable "key_name" { | |
description = "key pair name" | |
} | |
modules/key_pair/main.tf: | |
resource "tls_private_key" "rsa-4096-key" { | |
algorithm = "RSA" | |
rsa_bits = 4096 | |
} | |
resource "aws_key_pair" "demo-key_pair" { | |
key_name = "my-key" | |
public_key = tls_private_key.rsa-4096-key.public_key_openssh | |
} | |
resource "local_file" "private_key" { | |
content = tls_private_key.rsa-4096-key.private_key_pem | |
filename = "my-key.pem" | |
} | |
output "key_name" { | |
value = aws_key_pair.demo-key_pair.key_name | |
} | |
terraform init | |
terraform fmt | |
terraform plan | |
terraform apply | |
to take ssh of created instance on third party terminal: | |
(save .pem on your local system) | |
ssh -i <.pem key> ubuntu@<ip of instance> | |
terraform destroy |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment