forked from iam-veeramalla/terraform-zero-to-hero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.tf
106 lines (89 loc) · 2.57 KB
/
main.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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
# Define the AWS provider configuration.
provider "aws" {
region = "us-east-1" # Replace with your desired AWS region.
}
variable "cidr" {
default = "10.0.0.0/16"
}
resource "aws_key_pair" "example" {
key_name = "terraform-demo-abhi" # Replace with your desired key name
public_key = file("~/.ssh/id_rsa.pub") # Replace with the path to your public key file
}
resource "aws_vpc" "myvpc" {
cidr_block = var.cidr
}
resource "aws_subnet" "sub1" {
vpc_id = aws_vpc.myvpc.id
cidr_block = "10.0.0.0/24"
availability_zone = "us-east-1a"
map_public_ip_on_launch = true
}
resource "aws_internet_gateway" "igw" {
vpc_id = aws_vpc.myvpc.id
}
resource "aws_route_table" "RT" {
vpc_id = aws_vpc.myvpc.id
route {
cidr_block = "0.0.0.0/0"
gateway_id = aws_internet_gateway.igw.id
}
}
resource "aws_route_table_association" "rta1" {
subnet_id = aws_subnet.sub1.id
route_table_id = aws_route_table.RT.id
}
resource "aws_security_group" "webSg" {
name = "web"
vpc_id = aws_vpc.myvpc.id
ingress {
description = "HTTP from VPC"
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
ingress {
description = "SSH"
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"]
}
tags = {
Name = "Web-sg"
}
}
resource "aws_instance" "server" {
ami = "ami-0261755bbcb8c4a84"
instance_type = "t2.micro"
key_name = aws_key_pair.example.key_name
vpc_security_group_ids = [aws_security_group.webSg.id]
subnet_id = aws_subnet.sub1.id
connection {
type = "ssh"
user = "ubuntu" # Replace with the appropriate username for your EC2 instance
private_key = file("~/.ssh/id_rsa") # Replace with the path to your private key
host = self.public_ip
}
# File provisioner to copy a file from local to the remote EC2 instance
provisioner "file" {
source = "app.py" # Replace with the path to your local file
destination = "/home/ubuntu/app.py" # Replace with the path on the remote instance
}
provisioner "remote-exec" {
inline = [
"echo 'Hello from the remote instance'",
"sudo apt update -y", # Update package lists (for ubuntu)
"sudo apt-get install -y python3-pip", # Example package installation
"cd /home/ubuntu",
"sudo pip3 install flask",
"sudo python3 app.py &",
]
}
}