Skip to content

Commit 6789d3f

Browse files
authored
[수정] user tf 파일 생성 (#13)
1 parent 7fefbca commit 6789d3f

File tree

8 files changed

+127
-115
lines changed

8 files changed

+127
-115
lines changed

app/controllers/terraform_controller.go

+17-23
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,14 @@
11
package controllers
22

33
import (
4-
"github.com/gofiber/fiber/v2"
4+
"path/filepath"
5+
56
"main/app/services"
6-
)
77

8-
// accept랑 produce는 (swagger에서의) 애매해서 생략(s3에서도 생략되어 있음)
9-
// Description Merge module tf file and Add in user folder
10-
// Summary merge module tf file and add in user folder
11-
// Tags Env
12-
// Param email path string true "user email"
13-
// Success 200 {string} status "ok"
8+
"github.com/gofiber/fiber/v2"
9+
)
1410

11+
// Create a user env tf
1512
// @Router /v1/terraform/merge/{email} [post]
1613
func MergeEnvTf(c *fiber.Ctx) error {
1714
var data []map[string]interface{}
@@ -23,30 +20,25 @@ func MergeEnvTf(c *fiber.Ctx) error {
2320
}
2421

2522
email := c.Params("email")
23+
userFolderPath := filepath.Join("usertf", email)
2624

27-
err := services.MergeEnvTf(email, data)
25+
err := services.InitializeFolder(userFolderPath)
2826
if err != nil {
29-
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
27+
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
3028
"error": true,
3129
"msg": err,
3230
})
3331
}
3432

35-
return c.Status(fiber.StatusOK).JSON(fiber.Map{
36-
"error": false,
37-
})
38-
}
39-
40-
// @Router /v1/terraform/tfvars/{email} [post]
41-
func CreateTfvars(c *fiber.Ctx) error {
42-
var data []map[string]interface{}
43-
if err := c.BodyParser(&data); err != nil {
44-
return c.Status(fiber.StatusBadRequest).JSON(err)
33+
err = services.MergeEnvTf(userFolderPath, data)
34+
if err != nil {
35+
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
36+
"error": true,
37+
"msg": err,
38+
})
4539
}
4640

47-
email := c.Params("email")
48-
49-
err := services.CreateTfvars(email, data)
41+
err = services.CreateTfvars(userFolderPath, data)
5042
if err != nil {
5143
return c.Status(fiber.StatusNotFound).JSON(fiber.Map{
5244
"error": true,
@@ -56,9 +48,11 @@ func CreateTfvars(c *fiber.Ctx) error {
5648

5749
return c.Status(fiber.StatusOK).JSON(fiber.Map{
5850
"error": false,
51+
"msg": "merge user env tf success",
5952
})
6053
}
6154

55+
// Apply user env's tf
6256
// @Router /v1/terraform/apply/{email} [post]
6357
func ApplyEnvTf(c *fiber.Ctx) error {
6458
email := c.Params("email")

app/services/terraform_service.go

+25-8
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import (
88
"os"
99
"os/exec"
1010
"path/filepath"
11+
"regexp"
1112
"strconv"
1213
"strings"
1314

@@ -16,7 +17,20 @@ import (
1617
"github.com/hashicorp/hcl"
1718
)
1819

19-
func MergeEnvTf(email string, data []map[string]interface{}) error {
20+
func InitializeFolder(folderPath string) error {
21+
err := os.RemoveAll(folderPath)
22+
if err != nil {
23+
return err
24+
}
25+
err = os.MkdirAll(folderPath, os.ModePerm)
26+
if err != nil {
27+
return err
28+
}
29+
30+
return nil
31+
}
32+
33+
func MergeEnvTf(userFolderPath string, data []map[string]interface{}) error {
2034
for _, item := range data {
2135
folderPath := item["type"].(string)
2236

@@ -32,12 +46,12 @@ func MergeEnvTf(email string, data []map[string]interface{}) error {
3246
return err
3347
}
3448

35-
userMainPath := filepath.Join("usertf", email, "main.tf")
49+
userMainPath := filepath.Join(userFolderPath, "main.tf")
3650
if err := AppendFile(userMainPath, mainContent); err != nil {
3751
return err
3852
}
3953

40-
userVarPath := filepath.Join("usertf", email, "variables.tf")
54+
userVarPath := filepath.Join(userFolderPath, "variables.tf")
4155
if err := AppendFile(userVarPath, varContent); err != nil {
4256
return err
4357
}
@@ -52,7 +66,7 @@ func AppendFile(filePath string, content []byte) error {
5266
return ioutil.WriteFile(filePath, content, 0o644)
5367
}
5468

55-
newContent := append(exist, []byte("\n")...)
69+
newContent := append(exist, []byte("\n\n")...)
5670
newContent = append(newContent, content...)
5771

5872
err = ioutil.WriteFile(filePath, newContent, 0o644)
@@ -63,15 +77,18 @@ func AppendFile(filePath string, content []byte) error {
6377
return nil
6478
}
6579

66-
func CreateTfvars(email string, data []map[string]interface{}) error {
80+
func CreateTfvars(userFolderPath string, data []map[string]interface{}) error {
6781
var v map[string]interface{}
68-
variablesFile := filepath.Join("usertf", email, "variables.tf")
82+
variablesFile := filepath.Join(userFolderPath, "variables.tf")
6983
existingVariables, err := ioutil.ReadFile(variablesFile)
7084
if err != nil {
7185
return err
7286
}
7387

74-
err = hcl.Unmarshal(existingVariables, &v)
88+
re := regexp.MustCompile(`\{[^{}]*\}`)
89+
fileContent := re.ReplaceAllString(string(existingVariables), "{}")
90+
91+
err = hcl.Unmarshal([]byte(fileContent), &v)
7592
if err != nil {
7693
return err
7794
}
@@ -141,7 +158,7 @@ func CreateTfvars(email string, data []map[string]interface{}) error {
141158
tfvars.WriteString("\n")
142159
}
143160

144-
writePath := filepath.Join("usertf", email, "terraform.tfvars")
161+
writePath := filepath.Join(userFolderPath, "terraform.tfvars")
145162
err = ioutil.WriteFile(writePath, []byte(tfvars.String()), 0o644)
146163
if err != nil {
147164
return err

pkg/routes/public_routes.go

+1-2
Original file line numberDiff line numberDiff line change
@@ -11,8 +11,7 @@ func PublicRoutes(a *fiber.App) {
1111
route := a.Group("/api/v1")
1212
// Routes for POST method:
1313
route.Post("/login/new", controllers.UserSignIn)
14-
route.Post("/terraform/merge/:email", controllers.MergeEnvTf)
15-
route.Post("/terraform/tfvars/:email", controllers.CreateTfvars)
14+
route.Post("/terraform/usertf/:email", controllers.MergeEnvTf)
1615
route.Post("/terraform/apply/:email", controllers.ApplyEnvTf)
1716
route.Post("/s3/upload/:email", controllers.UploadHandler)
1817
route.Get("/s3/download/:email", controllers.DownloadHandler)

platform/terraform/alb/main.tf

+32-32
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,41 @@
11
#alb
22
module "alb" {
3-
source = "terraform-aws-modules/alb/aws"
4-
version = "~> 8.0"
5-
6-
name = "terramino"
7-
8-
load_balancer_type = "application"
9-
10-
vpc_id = module.vpc.vpd_id
11-
subnets = module.vpc.public_subnets
12-
security_groups = [module.terramino_lb.id]
13-
internal = false
14-
15-
http_tcp_listeners=[
16-
{
17-
port = 80
18-
protocol="HTTP"
19-
action_type = "forward"
20-
}
21-
]
22-
23-
target_groups = [
24-
name = "learn-asg-terramino"
25-
backend_port = 80
26-
backend_protocol = "HTTP"
27-
]
3+
source = "terraform-aws-modules/alb/aws"
4+
version = "~> 8.0"
5+
6+
name = "terramino"
7+
8+
load_balancer_type = "application"
9+
10+
vpc_id = module.vpc.vpc_id
11+
subnets = module.vpc.public_subnets
12+
security_groups = [module.terramino_lb.security_group_id]
13+
internal = false
14+
15+
http_tcp_listeners = [
16+
{
17+
port = 80
18+
protocol = "HTTP"
19+
action_type = "forward"
20+
}
21+
]
22+
23+
target_groups = [{
24+
name = "learn-asg-terramino"
25+
backend_port = 80
26+
backend_protocol = "HTTP"
27+
}]
2828
}
2929
resource "aws_autoscaling_attachment" "terramino" {
30-
autoscaling_group_name = aws_autoscaling_group.terramino.id
31-
alb_target_group_arn = aws_lb_target_group.terramino.arn
30+
autoscaling_group_name = module.asg.autoscaling_group_id
31+
lb_target_group_arn = module.alb.target_group_arns[0]
3232
}
3333

3434
module "terramino_instance" {
35-
source = "terraform-aws-modules/security-group/aws//modules/http-80"
36-
37-
name = "learn-asg-terramino-instance"
38-
vpc_id = module.vpc.vpc_id
35+
source = "terraform-aws-modules/security-group/aws//modules/http-80"
36+
37+
name = "learn-asg-terramino-instance"
38+
vpc_id = module.vpc.vpc_id
3939

40-
ingress_with_security_group_id = module.terramino_lb.id
40+
ingress_with_source_security_group_id = module.terramino_lb.security_group_id
4141
}

platform/terraform/asg/main.tf

+21-21
Original file line numberDiff line numberDiff line change
@@ -1,32 +1,32 @@
11
# asg
22
module "asg" {
3-
source = "terraform-aws-modules/autoscaling/aws"
3+
source = "terraform-aws-modules/autoscaling/aws"
44

5-
name = "terramino"
6-
min_size = var.asg_min_size ####*
7-
max_size = var.asg_max_size ####*
8-
desired_capacity = var.asg_desired_capacity ####*
9-
vpc_zone_identifier = module.vpc.private_subnets
5+
name = "terramino"
6+
min_size = var.asg_min_size
7+
max_size = var.asg_max_size
8+
desired_capacity = var.asg_desired_capacity
9+
vpc_zone_identifier = module.vpc.private_subnets
1010

11-
launch_template_name = "learn-terraform-aws-asg-" #이건 그냥 asg이름-username-asg-로 하는게 어지
12-
use_name_prefix = true
13-
image_id = var.asg_image_id
14-
instance_type = var.asg_instance_type ####*
15-
user_data = file("user-data.sh") ####*
16-
security_groups = [module.terramino_lb.id]
11+
launch_template_name = "learn-terraform-aws-asg-"
12+
use_name_prefix = true
13+
image_id = data.aws_ami.amazon-linux.id
14+
instance_type = var.asg_instance_type
15+
user_data = file("user-data.sh")
16+
security_groups = [module.terramino_instance.security_group_id]
1717

18-
tags = {
19-
key = "Name"
20-
value = "HashiCorp Learn ASG - Terramino"
21-
propagate_at_launch = true
22-
}
18+
tags = {
19+
key = "Name"
20+
value = "HashiCorp Learn ASG - Terramino"
21+
propagate_at_launch = true
22+
}
2323
}
2424

2525
module "terramino_lb" {
2626
source = "terraform-aws-modules/security-group/aws//modules/http-80"
2727

28-
name = "learn-asg-terramino-lb"
29-
vpc_id = module.vpc.vpd_id
28+
name = "learn-asg-terramino-lb"
29+
vpc_id = module.vpc.vpc_id
3030

31-
ingress_cidr_blocks = ["10.10.0.0/16"]
32-
}
31+
ingress_cidr_blocks = ["0.0.0.0/0"]
32+
}

platform/terraform/asg/variables.tf

+10-10
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,19 @@
1-
variable asg_min_size {
2-
type="number"
1+
variable "asg_min_size" {
2+
type = number
33
}
44

5-
variable asg_max_size {
6-
type="number"
5+
variable "asg_max_size" {
6+
type = number
77
}
88

9-
variable asg_instance_type {
10-
type="string"
9+
variable "asg_instance_type" {
10+
type = string
1111
}
1212

13-
variable asg_desired_capacity {
14-
type="number"
13+
variable "asg_desired_capacity" {
14+
type = number
1515
}
1616

17-
variable asg_image_id {
18-
type="string"
17+
variable "asg_image_id" {
18+
type = string
1919
}

platform/terraform/vpc/main.tf

+13-11
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,25 @@
1+
# vpc
2+
data "aws_availability_zones" "available" {
3+
state = "available"
4+
}
5+
16
module "vpc" {
27
source = "terraform-aws-modules/vpc/aws"
3-
version = "2.77.0"
8+
version = "4.0.1"
49

5-
name = var.vpc_name ####*
10+
name = var.vpc_name
611
cidr = var.vpc_cidr
712

813
azs = data.aws_availability_zones.available.names
9-
private_subnets = var.vpc_privatesubnet
10-
public_subnets = var.vpc_publicsubnet
11-
enable_dns_hostnames = true # VPC 내의 ec2 인스터스에 대해 자동으로 DNS 호스트 이름 할당
12-
enable_dns_support = true # 인스턴스는 아마존 내부 DNS 서비스를 통해 도메인 이름 해석 가능
14+
private_subnets = var.vpc_privatesubnet
15+
public_subnets = var.vpc_publicsubnet
16+
enable_dns_hostnames = true
17+
enable_dns_support = true
1318

14-
#nat를 위한 설정(자동으로 public에만 들어감)
15-
## 나트 수에 따라 달라짐 -> 표시 방식을 먼저 정하기(간소화 or 아이콘 사용)
1619
enable_nat_gateway = true
17-
single_nat_gateway = false
20+
single_nat_gateway = false
1821
}
1922

20-
#ami는 만드는거까진 하지 말자
2123
data "aws_ami" "amazon-linux" {
2224
most_recent = true
2325
owners = ["amazon"]
@@ -26,4 +28,4 @@ data "aws_ami" "amazon-linux" {
2628
name = "name"
2729
values = ["amzn-ami-hvm-*-x86_64-ebs"]
2830
}
29-
}
31+
}

platform/terraform/vpc/variables.tf

+8-8
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
1-
variable vpc_name {
2-
type="string"
1+
variable "vpc_name" {
2+
type = string
33
}
44

5-
variable vpc_cidr {
6-
type="string"
5+
variable "vpc_cidr" {
6+
type = string
77
}
88

9-
variable vpc_publicsubnet {
10-
type="list"
9+
variable "vpc_publicsubnet" {
10+
type = list(any)
1111
}
1212

13-
variable vpc_privatesubnet {
14-
type="list"
13+
variable "vpc_privatesubnet" {
14+
type = list(any)
1515
}

0 commit comments

Comments
 (0)