Reputation: 35
I am trying to create a loadbalancer with a target group attached to the ALB and listeners and instances attached to the target groups.
I have gotten it working for a single load balancer , but i cannot get it working for multiple ALB's with out having to duplicate the code.
I also tried passing input variables in command line appending it with scripting in powershell , but everytime the resources are created ,the state file is over written with the next resource name .
Is there a way to append to existing state file with new resources or a way to create multiple albs with all the other associated resources without duplicating ?
Below is the code:
variable` "name" {}
variable "environment" {
default = "Beta"
}
variable "security_group_id" {
default = ["sg-xxxxxx"]
}
variable "subnet_ids" {
type = "list"
default = ["subnet-xxxxxx","subnet-xxxxxxx","subnet-xxxxxxxxxxx"]
}
variable "instance_ids" {
type = "list"
default = ["xxxxxxx","xxxxxxx"]
}
variable "vpc_id" {
default = "vpc-xxxxxxxxxxxx"
}
variable "ssl_certificate_arn" {
default = "vpc-xxxxxxxxxxx"
}
provider "aws" {
region = "us-west-2"
access_key = "xxxxxxxxxx"
secret_key = "xxxxxxxxxx"
}
resource "aws_alb" "alb" {
count = "1"
name = "${var.name}-${var.environment}"
internal = false
security_groups = ["${var.security_group_id}"]
subnets = ["${var.subnet_ids}"]
tags {
Environment = "${var.environment}"
}
}
resource "aws_alb_target_group" "alb_targets" {
count = "1"
name = "${var.name}-${var.environment}"
port = "80"
protocol = "HTTP"
vpc_id = "${var.vpc_id}"
health_check {
healthy_threshold = 2
interval = 15
path = "/api/health"
timeout = 10
unhealthy_threshold = 2
}
tags {
Environment = "${var.environment}"
}
}
resource "aws_alb_listener" "alb_listener" {
count = "1"
load_balancer_arn = "${aws_alb.alb.arn}"
port = "80"
protocol = "HTTP"
#ssl_policy = "ELBSecurityPolicy-2015-05"
#certificate_arn = "${var.ssl_certificate_arn}"
default_action {
target_group_arn = "${element(aws_alb_target_group.alb_targets.*.arn, 0)}"
type = "forward"
}
}
resource "aws_lb_target_group_attachment" "test" {
target_group_arn = "${aws_alb_target_group.alb_targets.arn}"
target_id = "${element(var.instance_ids,count.index)}"
port = 80
}
Upvotes: 0
Views: 2216
Reputation: 1420
First, let me explain why your ALBs are getting overwritten:
Terraform is a declarative, i.e. it makes the Environment exactly what it looks in the file. So if you create ALB with name ALB1 and some configuration, run Terraform, then change the name in the file to ALB2, call Terraform apply, Terraform will delete the first one (since you need new resource to rename an ALB) and create a new one.
What you want can be easily achieved using Terraform Modules. What you can do is the following:
Check this for more information on modules.
P.S. if you find yourself stuck with this, post a comment and we will solve it.
Upvotes: 1