-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathcreate-ec2-with-terraform.tf
72 lines (61 loc) · 1.42 KB
/
create-ec2-with-terraform.tf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 4.0"
}
}
}
provider "aws" {
region = "AWS_REGION"
access_key = "AWS_ACCESS_KEY"
secret_key = "AWS_SECRET_KEY"
}
// To Generate Private Key
resource "tls_private_key" "rsa_4096" {
algorithm = "RSA"
rsa_bits = 4096
}
variable "key_name" {
description = "Name of the SSH key pair"
}
// Create Key Pair for Connecting EC2 via SSH
resource "aws_key_pair" "key_pair" {
key_name = var.key_name
public_key = tls_private_key.rsa_4096.public_key_openssh
}
// Save PEM file locally
resource "local_file" "private_key" {
content = tls_private_key.rsa_4096.private_key_pem
filename = var.key_name
}
# Create a security group
resource "aws_security_group" "sg_ec2" {
name = "sg_ec2"
description = "Security group for EC2"
ingress {
from_port = 22
to_port = 22
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
}
resource "aws_instance" "public_instance" {
ami = "ami-0f5ee92e2d63afc18"
instance_type = "t2.micro"
key_name = aws_key_pair.key_pair.key_name
vpc_security_group_ids = [aws_security_group.sg_ec2.id]
tags = {
Name = "public_instance"
}
root_block_device {
volume_size = 30
volume_type = "gp2"
}
}