如何在Terraform模块中覆盖ELB监听器资源?
Absolutely! You can customize the HTTPS listener for your ELB when calling the module, but you can't directly "override" a hardcoded listener block in the module's aws_elb resource. Instead, you need to refactor the module to make listeners configurable via variables first. Here's how to do it step by step:
Step 1: Refactor the Service Module to Support Configurable Listeners
First, adjust your ./service module to accept listener configurations as an input variable, replacing the hardcoded listener block.
- Add a listener variable in
variables.tf(inside the./servicemodule):
variable "elb_listeners" { type = list(object({ instance_port = number instance_protocol = string lb_port = number lb_protocol = string ssl_certificate_id = optional(string) # Only required for HTTPS/SSL listeners })) description = "List of listeners to configure for the Elastic Load Balancer" # Optional: Set a default HTTP listener as fallback default = [ { instance_port = 80 instance_protocol = "HTTP" lb_port = 80 lb_protocol = "HTTP" } ] }
- Update the
aws_elbresource inservice.tfwith a dynamic listener block:
Use Terraform'sdynamicblock to generate listeners based on the variable input, instead of hardcoding them:
resource "aws_elb" "main" { # Keep your existing ELB config (name, subnets, security groups, etc.) here dynamic "listener" { for_each = var.elb_listeners content { instance_port = listener.value.instance_port instance_protocol = listener.value.instance_protocol lb_port = listener.value.lb_port lb_protocol = listener.value.lb_protocol # Only include the SSL certificate ID if it's provided (for HTTPS) dynamic "ssl_certificate_id" { for_each = listener.value.ssl_certificate_id != null ? [true] : [] content { ssl_certificate_id = listener.value.ssl_certificate_id } } } } }
Step 2: Call the Module with Your Custom HTTPS Listener
Now when you invoke the module, you can pass in your desired HTTPS listener configuration to replace or supplement the default:
module "test" { source = "./service" # Pass other required module variables (subnets, security groups, etc.) here elb_listeners = [ { instance_port = 443 instance_protocol = "HTTPS" lb_port = 443 lb_protocol = "HTTPS" ssl_certificate_id = "arn:aws:acm:us-east-1:123456789012:certificate/abc123-xyz456" # Replace with your cert ARN } # Add more listeners here if needed (e.g., a HTTP listener that redirects to HTTPS) ] }
Key Tips
- If you want to retain default listeners alongside custom ones, just include both entries in the
elb_listenerslist when calling the module. - The
optional()type modifier (available in Terraform 1.3+) lets you reuse the same variable for both HTTP and HTTPS listeners without errors. - Double-check that your ELB's security groups allow incoming traffic on the LB port you're using (443 for HTTPS).
内容的提问来源于stack exchange,提问作者Nipun
相关产品推荐
相关产品推荐

