Giter Site home page Giter Site logo

terraform-aws-modules / terraform-aws-alb Goto Github PK

View Code? Open in Web Editor NEW
428.0 23.0 667.0 379 KB

Terraform module to create AWS Application/Network Load Balancer (ALB/NLB) resources πŸ‡ΊπŸ‡¦

Home Page: https://registry.terraform.io/modules/terraform-aws-modules/alb/aws

License: Apache License 2.0

HCL 100.00%
alb aws application-load-balancer terraform-module nlb network-load-balancer

terraform-aws-alb's Introduction

AWS Application and Network Load Balancer (ALB & NLB) Terraform module

Terraform module which creates Application and Network Load Balancer resources on AWS.

SWUbanner

Usage

When you're using ALB Listener rules, make sure that every rule's actions block ends in a forward, redirect, or fixed-response action so that every rule will resolve to some sort of an HTTP response. Checkout the AWS documentation for more information.

Application Load Balancer

HTTP to HTTPS redirect

module "alb" {
  source = "terraform-aws-modules/alb/aws"

  name    = "my-alb"
  vpc_id  = "vpc-abcde012"
  subnets = ["subnet-abcde012", "subnet-bcde012a"]

  # Security Group
  security_group_ingress_rules = {
    all_http = {
      from_port   = 80
      to_port     = 80
      ip_protocol = "tcp"
      description = "HTTP web traffic"
      cidr_ipv4   = "0.0.0.0/0"
    }
    all_https = {
      from_port   = 443
      to_port     = 443
      ip_protocol = "tcp"
      description = "HTTPS web traffic"
      cidr_ipv4   = "0.0.0.0/0"
    }
  }
  security_group_egress_rules = {
    all = {
      ip_protocol = "-1"
      cidr_ipv4   = "10.0.0.0/16"
    }
  }

  access_logs = {
    bucket = "my-alb-logs"
  }

  listeners = {
    ex-http-https-redirect = {
      port     = 80
      protocol = "HTTP"
      redirect = {
        port        = "443"
        protocol    = "HTTPS"
        status_code = "HTTP_301"
      }
    }
    ex-https = {
      port            = 443
      protocol        = "HTTPS"
      certificate_arn = "arn:aws:iam::123456789012:server-certificate/test_cert-123456789012"

      forward = {
        target_group_key = "ex-instance"
      }
    }
  }

  target_groups = {
    ex-instance = {
      name_prefix      = "h1"
      protocol         = "HTTP"
      port             = 80
      target_type      = "instance"
      target_id        = "i-0f6d38a07d50d080f"
    }
  }

  tags = {
    Environment = "Development"
    Project     = "Example"
  }
}

Cognito authentication

module "alb" {
  source = "terraform-aws-modules/alb/aws"

  # Truncated for brevity ...

  listeners = {
    ex-http-https-redirect = {
      port     = 80
      protocol = "HTTP"
      redirect = {
        port        = "443"
        protocol    = "HTTPS"
        status_code = "HTTP_301"
      }
    }
    ex-cognito = {
      port            = 444
      protocol        = "HTTPS"
      certificate_arn = "arn:aws:iam::123456789012:server-certificate/test_cert-123456789012"

      authenticate_cognito = {
        authentication_request_extra_params = {
          display = "page"
          prompt  = "login"
        }
        on_unauthenticated_request = "authenticate"
        session_cookie_name        = "session-${local.name}"
        session_timeout            = 3600
        user_pool_arn              = "arn:aws:cognito-idp:us-west-2:123456789012:userpool/us-west-2_abcdefghi"
        user_pool_client_id        = "us-west-2_fak3p001B"
        user_pool_domain           = "https://fak3p001B.auth.us-west-2.amazoncognito.com"
      }

      forward = {
        target_group_key = "ex-instance"
      }

      rules = {
        ex-oidc = {
          priority = 2

          actions = [
            {
              type = "authenticate-oidc"
              authentication_request_extra_params = {
                display = "page"
                prompt  = "login"
              }
              authorization_endpoint = "https://foobar.com/auth"
              client_id              = "client_id"
              client_secret          = "client_secret"
              issuer                 = "https://foobar.com"
              token_endpoint         = "https://foobar.com/token"
              user_info_endpoint     = "https://foobar.com/user_info"
            },
            {
              type             = "forward"
              target_group_key = "ex-instance"
            }
          ]
        }
      }
    }
  }
}

Cognito authentication on certain paths, redirects for others

module "alb" {
  source = "terraform-aws-modules/alb/aws"

  # Truncated for brevity ...

  listeners = {
    https = {
      port            = 443
      protocol        = "HTTPS"
      certificate_arn = "arn:aws:iam::123456789012:server-certificate/test_cert-123456789012"

      forward = {
        target_group_key = "instance"
      }

      rules = {
        redirect = {
          priority = 5000
          actions = [{
            type        = "redirect"
            status_code = "HTTP_302"
            host        = "www.youtube.com"
            path        = "/watch"
            query       = "v=dQw4w9WgXcQ"
            protocol    = "HTTPS"
          }]

          conditions = [{
            path_pattern = {
              values = ["/onboarding", "/docs"]
            }
          }]
        }

        cognito = {
          priority = 2
          actions = [
            {
              type                = "authenticate-cognito"
              user_pool_arn       = "arn:aws:cognito-idp::123456789012:userpool/test-pool"
              user_pool_client_id = "6oRmFiS0JHk="
              user_pool_domain    = "test-domain-com"
            },
            {
              type             = "forward"
              target_group_key = "instance"
            }
          ]

          conditions = [{
            path_pattern = {
              values = ["/protected-route", "private/*"]
            }
          }]
        }
      }
    }
  }

  target_groups = {
    instance = {
      name_prefix = "default"
      protocol    = "HTTPS"
      port        = 443
      target_type = "instance"
      target_id   = "i-0f6d38a07d50d080f"
    }
  }
}

Network Load Balancer

TCP_UDP, UDP, TCP and TLS listeners

module "nlb" {
  source = "terraform-aws-modules/alb/aws"

  name               = "my-nlb"
  load_balancer_type = "network"
  vpc_id             = "vpc-abcde012"
  subnets            = ["subnet-abcde012", "subnet-bcde012a"]

  # Security Group
  enforce_security_group_inbound_rules_on_private_link_traffic = "on"
  security_group_ingress_rules = {
    all_http = {
      from_port   = 80
      to_port     = 82
      ip_protocol = "tcp"
      description = "HTTP web traffic"
      cidr_ipv4   = "0.0.0.0/0"
    }
    all_https = {
      from_port   = 443
      to_port     = 445
      ip_protocol = "tcp"
      description = "HTTPS web traffic"
      cidr_ipv4   = "0.0.0.0/0"
    }
  }
  security_group_egress_rules = {
    all = {
      ip_protocol = "-1"
      cidr_ipv4   = "10.0.0.0/16"
    }
  }

  access_logs = {
    bucket = "my-nlb-logs"
  }

  listeners = {
    ex-tcp-udp = {
      port     = 81
      protocol = "TCP_UDP"
      forward = {
        target_group_key = "ex-target"
      }
    }

    ex-udp = {
      port     = 82
      protocol = "UDP"
      forward = {
        target_group_key = "ex-target"
      }
    }

    ex-tcp = {
      port     = 83
      protocol = "TCP"
      forward = {
        target_group_key = "ex-target"
      }
    }

    ex-tls = {
      port            = 84
      protocol        = "TLS"
      certificate_arn = "arn:aws:iam::123456789012:server-certificate/test_cert-123456789012"
      forward = {
        target_group_key = "ex-target"
      }
    }
  }

  target_groups = {
    ex-target = {
      name_prefix = "pref-"
      protocol    = "TCP"
      port        = 80
      target_type = "ip"
      target_id   = "10.0.47.1"
    }
  }

  tags = {
    Environment = "Development"
    Project     = "Example"
  }
}

Conditional creation

The following values are provided to toggle on/off creation of the associated resources as desired:

module "alb" {
  source = "terraform-aws-modules/alb/aws"

  # Disable creation of the LB and all resources
  create = false

 # ... omitted
}

Examples

See patterns.md for additional configuration snippets for common usage patterns.

Requirements

Name Version
terraform >= 1.0
aws >= 5.59

Providers

Name Version
aws >= 5.59

Modules

No modules.

Resources

Name Type
aws_lambda_permission.this resource
aws_lb.this resource
aws_lb_listener.this resource
aws_lb_listener_certificate.this resource
aws_lb_listener_rule.this resource
aws_lb_target_group.this resource
aws_lb_target_group_attachment.additional resource
aws_lb_target_group_attachment.this resource
aws_route53_record.this resource
aws_security_group.this resource
aws_vpc_security_group_egress_rule.this resource
aws_vpc_security_group_ingress_rule.this resource
aws_wafv2_web_acl_association.this resource
aws_partition.current data source

Inputs

Name Description Type Default Required
access_logs Map containing access logging configuration for load balancer map(string) {} no
additional_target_group_attachments Map of additional target group attachments to create. Use target_group_key to attach to the target group created in target_groups any {} no
associate_web_acl Indicates whether a Web Application Firewall (WAF) ACL should be associated with the load balancer bool false no
client_keep_alive Client keep alive value in seconds. The valid range is 60-604800 seconds. The default is 3600 seconds. number null no
connection_logs Map containing access logging configuration for load balancer map(string) {} no
create Controls if resources should be created (affects nearly all resources) bool true no
create_security_group Determines if a security group is created bool true no
customer_owned_ipv4_pool The ID of the customer owned ipv4 pool to use for this load balancer string null no
default_port Default port used across the listener and target group number 80 no
default_protocol Default protocol used across the listener and target group string "HTTP" no
desync_mitigation_mode Determines how the load balancer handles requests that might pose a security risk to an application due to HTTP desync. Valid values are monitor, defensive (default), strictest string null no
dns_record_client_routing_policy Indicates how traffic is distributed among the load balancer Availability Zones. Possible values are any_availability_zone (default), availability_zone_affinity, or partial_availability_zone_affinity. Only valid for network type load balancers. string null no
drop_invalid_header_fields Indicates whether HTTP headers with header fields that are not valid are removed by the load balancer (true) or routed to targets (false). The default is true. Elastic Load Balancing requires that message header names contain only alphanumeric characters and hyphens. Only valid for Load Balancers of type application bool true no
enable_cross_zone_load_balancing If true, cross-zone load balancing of the load balancer will be enabled. For application load balancer this feature is always enabled (true) and cannot be disabled. Defaults to true bool true no
enable_deletion_protection If true, deletion of the load balancer will be disabled via the AWS API. This will prevent Terraform from deleting the load balancer. Defaults to true bool true no
enable_http2 Indicates whether HTTP/2 is enabled in application load balancers. Defaults to true bool null no
enable_tls_version_and_cipher_suite_headers Indicates whether the two headers (x-amzn-tls-version and x-amzn-tls-cipher-suite), which contain information about the negotiated TLS version and cipher suite, are added to the client request before sending it to the target. Only valid for Load Balancers of type application. Defaults to false bool null no
enable_waf_fail_open Indicates whether to allow a WAF-enabled load balancer to route requests to targets if it is unable to forward the request to AWS WAF. Defaults to false bool null no
enable_xff_client_port Indicates whether the X-Forwarded-For header should preserve the source port that the client used to connect to the load balancer in application load balancers. Defaults to false bool null no
enforce_security_group_inbound_rules_on_private_link_traffic Indicates whether inbound security group rules are enforced for traffic originating from a PrivateLink. Only valid for Load Balancers of type network. The possible values are on and off. string null no
idle_timeout The time in seconds that the connection is allowed to be idle. Only valid for Load Balancers of type application. Default: 60 number null no
internal If true, the LB will be internal. Defaults to false bool null no
ip_address_type The type of IP addresses used by the subnets for your load balancer. The possible values are ipv4 and dualstack string null no
listeners Map of listener configurations to create any {} no
load_balancer_type The type of load balancer to create. Possible values are application, gateway, or network. The default value is application string "application" no
name The name of the LB. This name must be unique within your AWS account, can have a maximum of 32 characters, must contain only alphanumeric characters or hyphens, and must not begin or end with a hyphen string null no
name_prefix Creates a unique name beginning with the specified prefix. Conflicts with name string null no
preserve_host_header Indicates whether the Application Load Balancer should preserve the Host header in the HTTP request and send it to the target without any change. Defaults to false bool null no
putin_khuylo Do you agree that Putin doesn't respect Ukrainian sovereignty and territorial integrity? More info: https://en.wikipedia.org/wiki/Putin_khuylo! bool true no
route53_records Map of Route53 records to create. Each record map should contain zone_id, name, and type any {} no
security_group_description Description of the security group created string null no
security_group_egress_rules Security group egress rules to add to the security group created any {} no
security_group_ingress_rules Security group ingress rules to add to the security group created any {} no
security_group_name Name to use on security group created string null no
security_group_tags A map of additional tags to add to the security group created map(string) {} no
security_group_use_name_prefix Determines whether the security group name (security_group_name) is used as a prefix bool true no
security_groups A list of security group IDs to assign to the LB list(string) [] no
subnet_mapping A list of subnet mapping blocks describing subnets to attach to load balancer list(map(string)) [] no
subnets A list of subnet IDs to attach to the LB. Subnets cannot be updated for Load Balancers of type network. Changing this value for load balancers of type network will force a recreation of the resource list(string) null no
tags A map of tags to add to all resources map(string) {} no
target_groups Map of target group configurations to create any {} no
timeouts Create, update, and delete timeout configurations for the load balancer map(string) {} no
vpc_id Identifier of the VPC where the security group will be created string null no
web_acl_arn Web Application Firewall (WAF) ARN of the resource to associate with the load balancer string null no
xff_header_processing_mode Determines how the load balancer modifies the X-Forwarded-For header in the HTTP request before sending the request to the target. The possible values are append, preserve, and remove. Only valid for Load Balancers of type application. The default is append string null no

Outputs

Name Description
arn The ID and ARN of the load balancer we created
arn_suffix ARN suffix of our load balancer - can be used with CloudWatch
dns_name The DNS name of the load balancer
id The ID and ARN of the load balancer we created
listener_rules Map of listeners rules created and their attributes
listeners Map of listeners created and their attributes
route53_records The Route53 records created and attached to the load balancer
security_group_arn Amazon Resource Name (ARN) of the security group
security_group_id ID of the security group
target_groups Map of target groups created and their attributes
zone_id The zone_id of the load balancer to assist with creating DNS records

Authors

Module is maintained by Anton Babenko with help from these awesome contributors.

License

Apache 2 Licensed. See LICENSE for full details.

Additional information for users from Russia and Belarus

terraform-aws-alb's People

Contributors

alexbricepalo avatar alexjurkiewicz avatar andyli avatar angstwad avatar antonbabenko avatar bengaywins avatar betajobot avatar brandonjbjelland avatar bryantbiggs avatar dbgoytia avatar devzx avatar dmattia avatar drfaust92 avatar dtw45 avatar dylan-feith avatar eamonnmoloney avatar egarbi avatar florian0410 avatar glennbech avatar jeff-everett avatar krewenki avatar magreenbaum avatar mbolek avatar mohsen0 avatar nahuel242 avatar rdhar avatar semantic-release-bot avatar staticaland avatar tpoindessous avatar veilig2000 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

terraform-aws-alb's Issues

Not possible to use a lambda target group?

Describe the bug
Attempting to use a lambda function for the target group of an ALB, I get various errors. Documentation does not have a clear example of how to implement this functionality, if it is supported at all.

To Reproduce
Steps to reproduce the behavior:

  1. Create a lambda function "foo"
  2. Attempt to use a target group of type "LAMBDA":

module "alb" {
[...omitted for brevity...]
target_groups = [ {
name = "test"
backend_protocol = "LAMBDA"
backend_port = "3000"
} ]
target_groups_count = "1"
}

  1. Run terraform apply
  2. See error

Expected behavior
Creates an ALB resource with a lambda target group available for attaching functions

Actual behavior

Error: module.provider-console_lb.aws_lb_target_group.main_no_logs: expected health_check.0.protocol to be one of [HTTP HTTPS TCP], got LAMBDA

Error: module.provider-console_lb.aws_lb_target_group.main_no_logs: expected protocol to be one of [HTTP HTTPS TCP TLS], got LAMBDA

Additional context
Lambda target groups have been supported by the AWS provider since version 1.53. When specifying a lambda target group, the backend_port parameter is not required, but omitting it with this module also causes an error.

best way to do multiple listeners

Great work on this module, really wraps this process easily.
question:
If I have 2 listeners to implement, do I just create the listener and target group pairs separately and attach to the alb arn?

Access Logs should be optional

Current Module version - 3.1.0

I apologize ahead of time for dragging this issue back up.

Issue

By including the access_log block like this -

access_logs {
    enabled = true
    bucket  = "${var.log_bucket_name}"
    prefix  = "${var.log_location_prefix}"
}

You are prescribing a certain resource structure instead of letting the module user decide what they want.

Background

Previous related issue - #31
Summarized outcome from issue - make access logs required

Based upon the AWS Documentation -
"Access logging is an optional feature of Elastic Load Balancing that is disabled by default."

Proposal

resource "aws_lb" "lb_without_logs" {
  count = {create if use_log var is not set}
  ...
}

resource "aws_lb" "lb_with_logs" {
  count = {create if use_log var is set}
  ...
  access_logs {
    ...
  }
}

# to dry things out a little
locals {
  lb_arn = {conditional arn based on use_log var}
}

Default security group

Would you consider adding a default security group for the alb? I would think almost any app using this module would need a security group declared to actually use the alb. I'm happy to make a pull request.

Unable to use conditional expression to set value of create_alb

Describe the bug
Unable to use a ternary conditional expression to determine the value of create_alb

To Reproduce
Steps to reproduce the behavior:

  1. Add create_alb = "${local.some_var=="some val"?true:false}" to alb definition

Expected behavior
ALB to be created or not based on the interpolated value

Desktop (please complete the following information):

  • OS: Amazon Linux
  • Versions terraform v0.11.14, aws-alb v3.6.0

Additional context
These are the errors I get but I don't think they're particularly helpful:

Error: module.swarm-alb.aws_lb_listener.frontend_http_tcp: 1 error occurred:

  • module.swarm-alb.aws_lb_listener.frontend_http_tcp: At column 32, line 1: list "var.http_tcp_listeners" does not have any elements so cannot determine type. in:

${lookup(var.http_tcp_listeners[count.index], "port")}

Error: module.swarm-alb.aws_lb_listener_certificate.https_listener: 1 error occurred:

  • module.swarm-alb.aws_lb_listener_certificate.https_listener: At column 29, line 1: list "var.extra_ssl_certs" does not have any elements so cannot determine type. in:

${lookup(var.extra_ssl_certs[count.index], "certificate_arn")}

Error: module.swarm-alb.aws_lb_listener.frontend_http_tcp_no_logs: 1 error occurred:

  • module.swarm-alb.aws_lb_listener.frontend_http_tcp_no_logs: At column 70, line 1: list "var.http_tcp_listeners" does not have any elements so cannot determine type. in:

${aws_lb_target_group.main_no_logs.*.id[lookup(var.http_tcp_listeners[count.index], "target_group_index", 0)]}

Error: module.swarm-alb.aws_lb_listener_certificate.https_listener_no_logs: 1 error occurred:

  • module.swarm-alb.aws_lb_listener_certificate.https_listener_no_logs: At column 29, line 1: list "var.extra_ssl_certs" does not have any elements so cannot determine type. in:

${lookup(var.extra_ssl_certs[count.index], "certificate_arn")}

load_balancer_name length restriction?

I'm trying to understand what the logic was behind restricting the load_balancer_name length per:

locals {
prefix_length = "${length(var.load_balancer_name) < 6 ? length(var.load_balancer_name) : 6 }"
name_prefix = "${substr(var.load_balancer_name, 0, local.prefix_length)}"
}

The AWS docs indicate a max length of 32 characters, so why limit that further?
Ref: https://docs.aws.amazon.com/elasticloadbalancing/2012-06-01/APIReference/API_CreateLoadBalancer.html

ALB outputs reference invalid resource attributes

Describe the bug
The module throws an error when I add HTTPS listeners due to invalid attributes in the aws_lb_listener resource.

To Reproduce
Try to create an ALB with an HTTPS listener.

Expected behavior
An ALB is created with an HTTPS listener attached

Desktop (please complete the following information):

  • OS: Mac OSX High Sierra
  • Versions
    • Terraform v0.11.7

Additional context
Error: Error running plan: 2 error(s) occurred:

* module.app-alb.output.https_listener_arns: Resource 'aws_lb_listener.frontend_https' does not have attribute 'arn' for variable 'aws_lb_listener.frontend_https.*.arn'
* module.app-alb.output.https_listener_ids: Resource 'aws_lb_listener.frontend_https' does not have attribute 'id' for variable 'aws_lb_listener.frontend_https.*.id'`

Travis failures appear to be from missing envvars

Describe the bug

Travis builds are failing.

To Reproduce

  1. Submit a PR to this repo

  2. Observe that Travis fails continually with region problems:

     Error: provider.aws: "region": required field is not set
    
  3. See that the command to get the region fails with an authentication problem: An error occurred (AuthFailure) when calling the DescribeRegions operation: Authorization header or parameters are not formatted correctly.

Expected behavior

Tests should be run!

Additional context

I attempted to run that same command without the AWS_ACCESS_KEY_ID and AWS_SECRET_KEY_ID parameters set:

$ docker run --env AWS_DEFAULT_REGION=us-east-2 --env AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} --env AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} garland/aws-cli-docker aws ec2 describe-regions --query 'Regions[].{Name:RegionName}' --output text
Unable to find image 'garland/aws-cli-docker:latest' locally
latest: Pulling from garland/aws-cli-docker
605ce1bd3f31: Pulling fs layer
aae50b72bdad: Pulling fs layer
3372006e603a: Pulling fs layer
3372006e603a: Verifying Checksum
3372006e603a: Download complete
605ce1bd3f31: Verifying Checksum
605ce1bd3f31: Download complete
605ce1bd3f31: Pull complete
aae50b72bdad: Verifying Checksum
aae50b72bdad: Download complete
aae50b72bdad: Pull complete
3372006e603a: Pull complete
Digest: sha256:dfaac9a1eee5f18e854e844f3b485265644c18e5adc7a9f9888c7ce70f924fa5
Status: Downloaded newer image for garland/aws-cli-docker:latest

An error occurred (AuthFailure) when calling the DescribeRegions operation: Authorization header or parameters are not formatted correctly.

After setting them:

$ docker run --env AWS_DEFAULT_REGION=us-east-2 --env AWS_SECRET_ACCESS_KEY=${AWS_SECRET_ACCESS_KEY} --env AWS_ACCESS_KEY_ID=${AWS_ACCESS_KEY_ID} garland/aws-cli-docker aws ec2 describe-regions --query 'Regions[].{Name:RegionName}' --output text
ap-south-1
eu-west-3
eu-west-2
eu-west-1
ap-northeast-2
ap-northeast-1
sa-east-1
ca-central-1
ap-southeast-1
ap-southeast-2
eu-central-1
us-east-1
us-east-2
us-west-1
us-west-2

If soneone with admin privs to the Travis repo re-added those, I think it'd work…

Multiple Target Groups per ALB

I'm needing to create ALBs with multiple Target Groups (TG). The back end may and generally is the same port but are configured in my case by different paths in the URL. I have resources already built by other modules for VPC, security groups, etc. and looking to create ALBs with one or more TGs.

AWS LB resource created without specifying vpc_id

Describe the bug
The aws_lb resource is created without explicitly specifying it's VPC ID. This means that even if a VPC ID is specified in the module inputs, the default VPC for the AWS account will be used anyway.

To Reproduce
Steps to reproduce the behavior:

  1. Set up an AWS account and region with 2 VPCs
  2. Set VPC 1 to be the default VPC
  3. Run this module with the vpc_id set to VPC 2
  4. Observe that the associated alb.aws_lb.application is created in VPC 1 instead of VPC 2.

Expected behavior
All of the resources required for the Application Load Balancer are created with the VPC specified in the input to the module.

Desktop (please complete the following information):

  • OS: Mac OS X 10.13.5
  • Versions:
    Terraform v0.11.7
    provider.aws v1.25.0

Additional context
N/A

Additional flexibility for custom endpoints

While calling custom endpoints is allowed, it does this at the provider level, which means you need to instantiate multiple providers if you are using multiple endpoints based on the resource

It would be nice to have an optional field that could pass a custom endpoint at the resource level. e.g. we need a fips alb, but the rest of the albs in the environment do not need that level of restrictiveness. Currently we would need to have multiple providers, or create the alb via the cli and import it in.

Change Logging_enabled default to false

Describe the bug
The readme states that log_bucket_name and log_location_prefix are not required. Using a module with only the required parameters, these parameters are required as logging_enabled is set to true as default. Applying would result in an error in this state.

Error: Failure configuring LB attributes: ValidationError: The value of 'access_logs.s3.bucket' cannot be empty
	status code: 400, request id: 27420ad0-bd00-11e9-9575-1d4789fd3dae

To Reproduce
Steps to reproduce the behavior:

  1. Use the module with only required parameters.
  2. Apply the module
  3. See error

Expected behavior
If I fill in all required parameters, I would expect the module to apply.

Desktop (please complete the following information):

  • OS: OSX
  • Versions terraform 0.12.4, module version 4.1.0

Additional context
I can make a PR for it.

Need tests for the not logging scenario

Per #22 it sounds like users are struggling to make the module work for both use cases of logging and not logging. This issue is to prove out through tests and examples that this is possible given the current module OR to find a way to add it.

Optional log bucket

When I try to create an alb with just the seven mandatory variables, I get this error:

* aws_alb.main: Failure configuring ALB attributes: ValidationError: The value of 'access_logs.s3.bucket' cannot be empty
	status code: 400, request id: 266322f3-fa78-11e7-a2c3-ade7d8e52966

The problem is that that access_logs block of the aws_alb resource is always defined, even if you don't specify a bucket name.

I don't believe Terraform's configuration language can support making the access_logs block optional, because sub-blocks cannot have a count parameter. So the best "workaround" for now is probably just to mark the bucket name as a required parameter, and accept people can't use this module without specifying a log bucket.

Error on aws_route53_record creation

I'm using terraform 0.12.6 to plan a recordset and an ALB, with your module:

module "alb_webserver" {
  source                   = "terraform-aws-modules/alb/aws"
  version                  = "~> 4.1"

  // required
  load_balancer_name       = module.airflow_labels_webserver.id
  security_groups          = list(module.sg_airflow.this_security_group_id)
  subnets                  = var.public_subnets
  vpc_id                   = data.aws_vpc.default.id

  // optional
  http_tcp_listeners          = var.webserver_http_tcp_listeners
  http_tcp_listeners_count    = var.webserver_http_tcp_listeners_count
  https_listeners             = var.webserver_https_listeners
  https_listeners_count       = var.webserver_https_listeners_count
  target_groups               = var.webserver_target_groups
  target_groups_count         = var.webserver_target_groups_count
  tags                        = module.airflow_labels_webserver.tags
  listener_ssl_policy_default = var.webserver_listener_ssl_policy
  logging_enabled             = false
}

data "aws_route53_zone" "webserver" {
  name = var.webserver_host_domain
}

resource "aws_route53_record" "webserver" {
  zone_id                  = data.aws_route53_zone.webserver.zone_id
  name                     = join(".", list(var.webserver_host_subdomain, var.webserver_host_domain))
  type                     = "A"
  alias {
    name                   = module.alb_webserver.dns_name
    zone_id                = module.alb_webserver.load_balancer_zone_id
    evaluate_target_health = var.webserver_evaluate_target_health
  }
}

Error message:

Error: expected length of alias.0.zone_id to be in the range (1 - 32), got

  on ../../webserver.tf line 72, in resource "aws_route53_record" "webserver":
  72: resource "aws_route53_record" "webserver" {

Error: expected length of alias.0.name to be in the range (1 - 1024), got

  on ../../webserver.tf line 72, in resource "aws_route53_record" "webserver":
  72: resource "aws_route53_record" "webserver" {

I'm not sure what exactly I'm missing, thank you for guidance.

Access logs on server side encrypted bucket?

Because of standards I need to make sure my ALB access logs are also encrypted.
Is this supported ? I am using standard S3 KMS as default encryption for S3 bucket .

When I try to do it I am getting this error:

aws_alb.my_alb: Failure configuring LB attributes: InvalidConfigurationRequest: Access Denied for bucket: my.bucketname. Please check S3bucket permission

Support for TF 0.12

Describe the bug
A clear and concise description of what the bug is.

To Reproduce
Steps to reproduce the behavior:

  1. Go to '...'
  2. Click on '....'
  3. Scroll down to '....'
  4. See error

Expected behavior
A clear and concise description of what you expected to happen.

Desktop (please complete the following information):

  • OS: [e.g. Linux]
  • Versions [e.g. terraform version, kitchen-terraform version, module version, etc.]

Additional context
Add any other context about the problem here.

Enabling Logs to S3 backup for existing LB

Is your feature request related to a problem? Please describe.
I was thinking to use the module, however I run into a problem.
If I want to enable Logs to be sent to an S3 buckt, LB will be recreated.

Describe the solution you'd like
For production usage, LB recreation that means chaning DNS name and downtime are not good at all.

Describe alternatives you've considered
Do not have alternative here.

Additional context
N/A

Default Target-Group of a listener cant be modified

Terraform Version

Terraform v0.11.4

Terraform Configuration Files

module "ECS_ALB" {
  source  = "terraform-aws-modules/alb/aws"
  version = "3.1.0"

  load_balancer_name         = "${var.name}-${var.environment}"
  subnets                    = "${module.vpc.private_subnets}"
  load_balancer_is_internal  = "true"
  security_groups            = ["${module.security_groups.internal_elb}"]
  vpc_id                     = "${module.vpc.vpc_id}"
  enable_deletion_protection = true

  # Listener
  http_tcp_listeners_count = "1"
  http_tcp_listeners       = "${list(map("port", "8080", "protocol", "HTTP"))}"

  // Default Target-Group
  target_groups       = "${list(map("name", "first-${var.environment}", "backend_protocol", "HTTP", "backend_port", "8080"))}"
  target_groups_count = "1"

  #
  // Logging
  log_bucket_name = "${var.name}-${var.environment}-share-alb-logs"

  //Tagging
  tags = {
    Name = "${var.name}"

    Environment = "${var.environment}"
  }
}

Expected Behavior

The module should allow modify the default target-group (rule) associated with a listener.
For this particular example, let's suppose that I have already created a listener with the target-group first-testing as default and I want to change it to be default-testing.

Actual Behavior

Terraform apply fails with the following message:

module.stack.module.ECS_ALB.aws_lb_target_group.main: Destroying... (ID: arn:aws:elasticloadbalancing:us-west-4:...tgroup/first-testing/6f58a25341942b21)

Error: Error applying plan:

1 error(s) occurred:

* module.stack.module.ECS_ALB.aws_lb_target_group.main (destroy): 1 error(s) occurred:

* aws_lb_target_group.main: Error deleting Target Group: ResourceInUse: Target group 'arn:aws:elasticloadbalancing:us-west-4:12345678910:targetgroup/first-testing/6f58a25341942b21' is currently in use by a listener or a rule

Steps to Reproduce

  1. create the resources using the configuration file above, init, plan and apply
  2. modify the default target group as follow:
17c17
<   target_groups                 = "${list(map("name", "first-${var.environment}", "backend_protocol", "HTTP", "backend_port", "8080"))}"
---
>   target_groups                 = "${list(map("name", "default-${var.environment}", "backend_protocol", "HTTP", "backend_port", "8080"))}"
  1. plan
  2. apply

Maybe adding 'lifecycle {crate_before_destroy => true}` into aws_lb_target_group to solve it?
I will test later better

Draft a new release

Can you tag a release? Looks like we're 6 commits ahead of the last one @ 2.4.0

Target_group_count doesn't account for target_groups being zero indexed

Describe the bug
target_groups attribute is zero indexed but target_groups_count starts at 1 when slicing a list of target groups.

Example error:

  • module.sage_ess_alb.output.target_group_names: slice: to index must be <= length of the input list in:

${slice(concat(aws_lb_target_group.main..name, aws_lb_target_group.main_no_logs..name), 0, var.target_groups_count)}

Relevant attribute states upon getting this error:
target_groups = "${list(map( "name", "vague-ess", "backend_protocol", "HTTPS", "backend_port", "1234"), map( "name", "vague-ess-app", "backend_protocol", "HTTPS", "backend_port", "4321"))}"
target_groups_count = "2"

Setting target_groups_count to 1 results in it successfully running the plan and picking up both target groups in the list.

To Reproduce
Steps to reproduce the behavior:

  1. Create an ALB module
  2. Add two (or more) target groups
  3. Set target_groups_count to equal list length
  4. Run a tf plan

Expected behavior
Plan succeeds

Desktop (please complete the following information):

  • OS:Debian Stretch
  • Versions:
    TF 0.11.10
    3.5.0 of terraform-aws-modules/alb/aws

Extend this module to support NLB

Is your feature request related to a problem? Please describe.

ALB and NLB are rather close in terms of API in AWS and Terraform AWS providers, so maybe extend this module and allow users to specify load_balancer_type here:

load_balancer_type = "application"

Describe alternatives you've considered

Alternatively, this module can be renamed to terraform-aws-lb and support both ALB and NLB.

Additional context

I have not heard requests about NLB so often to consider this as an urgent feature. What do you think @brandoconnor ?

How can both modules be instantiated in the same state?

I have set up with the terragrunt and I am following instructions from terraform-aws-alb/main.tf . So how I can manage the autoscaling module and the terraform-aws-alb module are instantiated in the same state?
I have tried with *.auto.tfvars as well as with

terragrunt = {
terraform {
source = [
source = "git::[email protected]:terraform-aws-modules/terraform-aws-alb.git"
"git::[email protected]:terraform-aws-modules/terraform-aws-autoscaling.git?ref=v2.9.1"
]
}

but no luck yet.

access_logs.s3.bucket empty errors

Failure configuring ALB attributes: ValidationError: The value of 'access_logs.s3.bucket' cannot be empty status code: 400, request id: cd69fceb-bb12-11e7-a276-19494eb0aecb
I get the above message when I do not set any value for log_bucket. Currently I can see that 'enabled' for access_logs is based on setting the log_bucket:
access_logs { bucket = "${var.log_bucket}" prefix = "${var.log_prefix}" enabled = "${var.log_bucket != ""}" }
I think it would be better to have this as a separate value (enable_access_logs ?) so it is possible to pass the log_bucket but not enable the access_logs. What do you think about this?

Also, the job failed when setting the log_bucket to a chosen one when it has just been created - I think s3 didn't converge fully before the bucket assignement to ALB - maybe a backoff timer or something. Don't know if terraform actually has something to fix this

After apply, it deleted my vpc

Describe the bug
Usedthe module to create an ALB. I used a previous module state as a data source. ALB gets created.
When it times out due to provisioning [no tgs currently], it eventually went and deleted my whole vpc!

Expected behavior
If the ALB times out, dont go delete the vpc

Desktop (please complete the following information):
MAC, TF 0.11.13, AWS-CLI 1.16.140

Additional context
I created a vpc using the official TF vpc module, but stripped the SG and Routes out for my own reasons.
I used the tfstate that was outputted to S3 for some vars for the ALB.
I manually entered the default SG.

Re-destroying throws `module.alb.output.target_group_arns: slice: to index must be <= length of the input list`

Describe the bug

Re-destroying throws module.alb.output.target_group_arns: slice: to index must be <= length of the input list.

To Reproduce

  1. Add an ALB and set target_groups_count = "1"
  2. Run a destroy
  3. Run a second destroy

See e.g.:

data.null_data_source.lambda_archive: Refreshing state...
data.null_data_source.lambda_file: Refreshing state...
data.null_data_source.lambda_archive: Refreshing state...
data.null_data_source.lambda_file: Refreshing state...
data.archive_file.notify_slack: Refreshing state...
data.archive_file.notify_slack: Refreshing state...
data.aws_elb_service_account.default: Refreshing state...
data.aws_route53_zone.api2vpc2: Refreshing state...
data.aws_availability_zones.available: Refreshing state...
data.aws_ami.ubuntu: Refreshing state...
data.aws_iam_policy_document.assume_role: Refreshing state...
data.aws_ami.ubuntu: Refreshing state...
data.aws_region.current: Refreshing state...
data.aws_iam_policy_document.lambda_basic: Refreshing state...
data.aws_region.current: Refreshing state...
data.aws_caller_identity.eu-west-2: Refreshing state...
data.aws_iam_policy_document.notify_slack_role_doc: Refreshing state...
data.aws_caller_identity.us-east-2: Refreshing state...
data.aws_region.current: Refreshing state...
data.aws_elb_service_account.default: Refreshing state...
data.aws_route53_zone.api2vpc2: Refreshing state...
data.aws_region.current: Refreshing state...
data.aws_iam_policy_document.notify_slack_role_doc: Refreshing state...
data.aws_ami.ubuntu: Refreshing state...
data.aws_ami.ubuntu: Refreshing state...
data.aws_iam_policy_document.lambda_basic: Refreshing state...
data.aws_availability_zones.available: Refreshing state...
data.aws_iam_policy_document.assume_role: Refreshing state...

Error: Error applying plan:

2 error(s) occurred:

* module.region_us-east-2.module.connectivity.module.alb.output.target_group_arns: slice: to index must be <= length of the input list in:

${slice(concat(aws_lb_target_group.main.*.arn, aws_lb_target_group.main_no_logs.*.arn), 0, var.target_groups_count)}
* module.region_eu-west-2.module.connectivity.module.alb.output.target_group_arns: slice: to index must be <= length of the input list in:

${slice(concat(aws_lb_target_group.main.*.arn, aws_lb_target_group.main_no_logs.*.arn), 0, var.target_groups_count)}

Set target_groups_count = "0", run another destory, see:

Destroy complete! Resources: 0 destroyed.

Expected behavior

I'd like destroys to be idempotent. So far they have been but the alb module is preventing this now it seems. Although to be fair, it could also very well be that the problem exists between keyboard and chair :) If anything, I hope to learn from submitting this issue.

Desktop (please complete the following information):

  • OS: Ubuntu 18.04.1 LTS
  • Versions: Terraform v0.11.8, alb module 3.4.0, aws provider 1.35.0

Additional context

Thanks for an awesome module! πŸ’―

Errors if log_prefix, certificate_arn not set

From @hasbro-ielo :

The documentation says that log_prefix, certificate_arn are optional. If I don't set them I get the following:

| => tf validate && tf plan
1 error(s) occurred:

* module root: 
    module alb: required variable "certificate_arn" not set
    module alb: required variable "log_prefix" not set

Here's how I'm using the module

module "alb" {
  source = "modules/terraform-community-modules/tf_aws_alb/alb"

  //alb_is_internal = ""
  //alb_name
  //alb_protocols
  alb_security_groups = "${module.alb_sg.security_group_id_web}"
  aws_region  = "${var.region}"
  aws_account_id = "${var.account_id}"
  //backend_port
  //backend_protocol
  //certificate_arn
  //cookie_duration
  //health_check_path
  log_bucket = "${var.alb_logs_bucket}"
  //log_prefix
  //principal_account_id
  subnets = "${var.alb_subnets}"
  vpc_id = "${module.vpc.vpc_id}"
  //tags
}

Improvement request: New variable for HTTP port listener

Would it be possible to have a new variable (defaulted to 80) to be able to change the port for the HTTP listener for other than 80?
This is specially useful in my usecase when using this module to create an Internal ALB.
We dont use the default port for internal ones.
If you agree I can create the PR to have it done

enable_cross_zone_load_balancing is not a valid argument

Module input "enable_cross_zone_load_balancing" is not a valid argument says Terraform. It seems to be too silly to be a bug, however I can run successfully terraform plan as soon as I comment out this input arg.

To Reproduce
Steps to reproduce the behavior:

module "alb" {
# add mandatory inputs
  enable_cross_zone_load_balancing = "true"
}

Terraform output:

Error: module "alb": "enable_cross_zone_load_balancing" is not a valid argument

Expected behavior
terraform plan will give usual output

Desktop (please complete the following information):

  • OS: Linux
  • Versions Terraform v0.11.8 provider.aws v1.41.0

Variable to enable creation of alb resources

Is your feature request related to a problem? Please describe.

I'm trying to use the terraform-aws-alb in a conditional fashion. In my configuration, I only want to create an ALB in certain cases. Unfortunately, Terraform doesn't support the count parameter for modules (hashicorp/terraform#953), and there's no variable in this module to control whether it creates resources or not.

Describe the solution you'd like

The terraform-aws-vpc module has a variable named create_vpc that controls whether or not it creates actually creates VPC resources. I'd like something similar (e.g., create_alb) in this module.

https://github.com/terraform-aws-modules/terraform-aws-vpc/blob/master/variables.tf#L1

Describe alternatives you've considered

I couldn't find any alternative ways to conditionally enable/disable this module.

Additional context

None.

Modifying target_groups_defaults seems painful

Is your feature request related to a problem? Please describe.
if you want to modify a single property in the target_groups_defaults map do you have to then pass the whole thing back in?

I want to do something like to modify a single key from defaults map and keep the rest

  target_groups_defaults = "${list(map("health_check_path", "/health"))}"

but when I do that I get

module.services.module.alb.aws_lb_target_group.main_no_logs: lookup: lookup failed to find 'health_check_matcher' in:

${lookup(var.target_groups[count.index], "health_check_matcher", lookup(var.target_groups_defaults, "health_check_matcher"))}

making it seem like I would have to do something like the following

  target_groups_defaults   = "${list(map("health_check_path", "/health", "cookie_duration", 86400, "deregistration_delay", 300, "health_check_interval", 10, "health_check_healthy_threshold", 3, "health_check_path", "/", "health_check_port", "traffic-port", "health_check_timeout", 5, "health_check_unhealthy_threshold", 3, "health_check_matcher", "200-299", "stickiness_enabled", true, "target_type", "instance"))})"

Describe the solution you'd like
a change to the argument or arguments to make this easier

Describe alternatives you've considered
the above re-passing of the entire map

Additional context
new to terraform so I feel like I may be just missing something?

target_groups optional param is not optional

Describe the bug
the target_group param is listed as optional but if you don't pass it then the module will always fail with

Error: Invalid index

  on .terraform/modules/alb/terraform-aws-modules-terraform-aws-alb-61e7316/alb_no_logs.tf line 130, in resource "aws_lb_listener" "frontend_http_tcp_no_logs":
 130:     target_group_arn = aws_lb_target_group.main_no_logs[lookup(var.http_tcp_listeners[count.index], "target_group_index", 0)].id
    |----------------
    | aws_lb_target_group.main_no_logs is empty tuple
    | count.index is 0
    | var.http_tcp_listeners is list of map of string with 1 element

The given key does not identify an element in this collection value.

because the counton this resource doesn't check for the target_group length, only for var.create_alb and it always tries to add a TG in the default_action{} of the aws_lb_listener

This applies to the log enabled version of the ALB too

Desktop (please complete the following information):

  • OS: Linux
  • Terraform 0.12.8 and terrafor-aws-alb 4.1.0

Additional context
I can open a PR to try to fix this but the best solution is not that clear to me. A default_action{} must be provided for any listener so it should be either a TG or some of the new targets ALB now permits (like a fixed response). WDYT?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.