-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmain.tf
127 lines (105 loc) · 2.65 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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
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
provisioner "local-exec" {
command = "chmod 400 ${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"]
}
ingress {
from_port = 3000
to_port = 3000
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"
}
provisioner "local-exec" {
command = "touch dynamic_inventory.ini"
}
provisioner "remote-exec" {
inline = [
"echo 'EC2 instance is ready.'"
]
connection {
type = "ssh"
host = self.public_ip
user = "ubuntu"
private_key = tls_private_key.rsa_4096.private_key_pem
}
}
}
data "template_file" "inventory" {
template = <<-EOT
[ec2_instances]
${aws_instance.public_instance.public_ip} ansible_user=ubuntu ansible_private_key_file=${path.module}/${var.key_name}
EOT
}
resource "local_file" "dynamic_inventory" {
depends_on = [aws_instance.public_instance]
filename = "dynamic_inventory.ini"
content = data.template_file.inventory.rendered
provisioner "local-exec" {
command = "chmod 400 ${local_file.dynamic_inventory.filename}"
}
}
resource "null_resource" "run_ansible" {
depends_on = [local_file.dynamic_inventory]
provisioner "local-exec" {
command = "ansible-playbook -i dynamic_inventory.ini deploy-app.yml"
working_dir = path.module
}
}