Skip to content

Resource: awsLbListenerRule

Provides a Load Balancer Listener Rule resource.

\~> Note: awsAlbListenerRule is known as awsLbListenerRule. The functionality is identical.

Example Usage

/*Provider bindings are generated by running cdktf get.
See https://cdk.tf/provider-generation for more details.*/
import * as aws from "./.gen/providers/aws";
const awsCognitoUserPoolPool = new aws.cognitoUserPool.CognitoUserPool(
  this,
  "pool",
  {}
);
const awsCognitoUserPoolClientClient =
  new aws.cognitoUserPoolClient.CognitoUserPoolClient(this, "client", {});
const awsCognitoUserPoolDomainDomain =
  new aws.cognitoUserPoolDomain.CognitoUserPoolDomain(this, "domain", {});
new aws.lb.Lb(this, "front_end", {});
const awsLbListenerFrontEnd = new aws.lbListener.LbListener(
  this,
  "front_end_4",
  {}
);
/*This allows the Terraform resource name to match the original name. You can remove the call if you don't need them to match.*/
awsLbListenerFrontEnd.overrideLogicalId("front_end");
new aws.lbListenerRule.LbListenerRule(this, "admin", {
  action: [
    {
      authenticateCognito: {
        userPoolArn: awsCognitoUserPoolPool.arn,
        userPoolClientId: awsCognitoUserPoolClientClient.id,
        userPoolDomain: awsCognitoUserPoolDomainDomain.domain,
      },
      type: "authenticate-cognito",
    },
    {
      targetGroupArn: "${aws_lb_target_group.static.arn}",
      type: "forward",
    },
  ],
  listenerArn: awsLbListenerFrontEnd.arn,
});
new aws.lbListenerRule.LbListenerRule(this, "health_check", {
  action: [
    {
      fixedResponse: {
        contentType: "text/plain",
        messageBody: "HEALTHY",
        statusCode: "200",
      },
      type: "fixed-response",
    },
  ],
  condition: [
    {
      queryString: [
        {
          key: "health",
          value: "check",
        },
        {
          value: "bar",
        },
      ],
    },
  ],
  listenerArn: awsLbListenerFrontEnd.arn,
});
new aws.lbListenerRule.LbListenerRule(this, "host_based_routing", {
  action: [
    {
      forward: {
        stickiness: {
          duration: 600,
          enabled: true,
        },
        targetGroup: [
          {
            arn: "${aws_lb_target_group.main.arn}",
            weight: 80,
          },
          {
            arn: "${aws_lb_target_group.canary.arn}",
            weight: 20,
          },
        ],
      },
      type: "forward",
    },
  ],
  condition: [
    {
      hostHeader: {
        values: ["my-service.*.terraform.io"],
      },
    },
  ],
  listenerArn: awsLbListenerFrontEnd.arn,
  priority: 99,
});
new aws.lbListenerRule.LbListenerRule(this, "host_based_weighted_routing", {
  action: [
    {
      targetGroupArn: "${aws_lb_target_group.static.arn}",
      type: "forward",
    },
  ],
  condition: [
    {
      hostHeader: {
        values: ["my-service.*.terraform.io"],
      },
    },
  ],
  listenerArn: awsLbListenerFrontEnd.arn,
  priority: 99,
});
new aws.lbListenerRule.LbListenerRule(this, "oidc", {
  action: [
    {
      authenticateOidc: {
        authorizationEndpoint: "https://example.com/authorization_endpoint",
        clientId: "client_id",
        clientSecret: "client_secret",
        issuer: "https://example.com",
        tokenEndpoint: "https://example.com/token_endpoint",
        userInfoEndpoint: "https://example.com/user_info_endpoint",
      },
      type: "authenticate-oidc",
    },
    {
      targetGroupArn: "${aws_lb_target_group.static.arn}",
      type: "forward",
    },
  ],
  listenerArn: awsLbListenerFrontEnd.arn,
});
new aws.lbListenerRule.LbListenerRule(this, "redirect_http_to_https", {
  action: [
    {
      redirect: {
        port: "443",
        protocol: "HTTPS",
        statusCode: "HTTP_301",
      },
      type: "redirect",
    },
  ],
  condition: [
    {
      httpHeader: {
        httpHeaderName: "X-Forwarded-For",
        values: ["192.168.1.*"],
      },
    },
  ],
  listenerArn: awsLbListenerFrontEnd.arn,
});
new aws.lbListenerRule.LbListenerRule(this, "static", {
  action: [
    {
      targetGroupArn: "${aws_lb_target_group.static.arn}",
      type: "forward",
    },
  ],
  condition: [
    {
      pathPattern: {
        values: ["/static/*"],
      },
    },
    {
      hostHeader: {
        values: ["example.com"],
      },
    },
  ],
  listenerArn: awsLbListenerFrontEnd.arn,
  priority: 100,
});

Argument Reference

The following arguments are supported:

  • listenerArn - (Required, Forces New Resource) The ARN of the listener to which to attach the rule.
  • priority - (Optional) The priority for the rule between 1 and 50000. Leaving it unset will automatically set the rule with next available priority after currently existing highest rule. A listener can't have multiple rules with the same priority.
  • action - (Required) An Action block. Action blocks are documented below.
  • condition - (Required) A Condition block. Multiple condition blocks of different types can be set and all must be satisfied for the rule to match. Condition blocks are documented below.
  • tags - (Optional) A map of tags to assign to the resource. If configured with a provider defaultTags configuration block present, tags with matching keys will overwrite those defined at the provider-level.

Action Blocks

Action Blocks (for action) support the following:

  • type - (Required) The type of routing action. Valid values are forward, redirect, fixedResponse, authenticateCognito and authenticateOidc.
  • targetGroupArn - (Optional) The ARN of the Target Group to which to route traffic. Specify only if type is forward and you want to route to a single target group. To route to one or more target groups, use a forward block instead.
  • forward - (Optional) Information for creating an action that distributes requests among one or more target groups. Specify only if type is forward. If you specify both forward block and targetGroupArn attribute, you can specify only one target group using forward and it must be the same target group specified in targetGroupArn.
  • redirect - (Optional) Information for creating a redirect action. Required if type is redirect.
  • fixedResponse - (Optional) Information for creating an action that returns a custom HTTP response. Required if type is fixedResponse.
  • authenticateCognito - (Optional) Information for creating an authenticate action using Cognito. Required if type is authenticateCognito.
  • authenticateOidc - (Optional) Information for creating an authenticate action using OIDC. Required if type is authenticateOidc.

Forward Blocks (for forward) support the following:

  • targetGroup - (Required) One or more target groups block.
  • stickiness - (Optional) The target group stickiness for the rule.

Target Group Blocks (for targetGroup) supports the following:

  • arn - (Required) The Amazon Resource Name (ARN) of the target group.
  • weight - (Optional) The weight. The range is 0 to 999.

Target Group Stickiness Config Blocks (for stickiness) supports the following:

  • enabled - (Required) Indicates whether target group stickiness is enabled.
  • duration - (Optional) The time period, in seconds, during which requests from a client should be routed to the same target group. The range is 1-604800 seconds (7 days).

Redirect Blocks (for redirect) support the following:

\~> NOTE:: You can reuse URI components using the following reserved keywords: #{protocol}, #{host}, #{port}, #{path} (the leading "/" is removed) and #{query}.

  • host - (Optional) The hostname. This component is not percent-encoded. The hostname can contain #{host}. Defaults to #{host}.
  • path - (Optional) The absolute path, starting with the leading "/". This component is not percent-encoded. The path can contain #{host}, #{path}, and #{port}. Defaults to /#{path}.
  • port - (Optional) The port. Specify a value from 1 to 65535 or #{port}. Defaults to #{port}.
  • protocol - (Optional) The protocol. Valid values are http, https, or #{protocol}. Defaults to #{protocol}.
  • query - (Optional) The query parameters, URL-encoded when necessary, but not percent-encoded. Do not include the leading "?". Defaults to #{query}.
  • statusCode - (Required) The HTTP redirect code. The redirect is either permanent (HTTP_301) or temporary (HTTP_302).

Fixed-response Blocks (for fixedResponse) support the following:

  • contentType - (Required) The content type. Valid values are text/plain, text/css, text/html, application/javascript and application/json.
  • messageBody - (Optional) The message body.
  • statusCode - (Optional) The HTTP response code. Valid values are 2Xx, 4Xx, or 5Xx.

Authenticate Cognito Blocks (for authenticateCognito) supports the following:

  • authenticationRequestExtraParams - (Optional) The query parameters to include in the redirect request to the authorization endpoint. Max: 10.
  • onUnauthenticatedRequest - (Optional) The behavior if the user is not authenticated. Valid values: deny, allow and authenticate
  • scope - (Optional) The set of user claims to be requested from the IdP.
  • sessionCookieName - (Optional) The name of the cookie used to maintain session information.
  • sessionTimeout - (Optional) The maximum duration of the authentication session, in seconds.
  • userPoolArn - (Required) The ARN of the Cognito user pool.
  • userPoolClientId - (Required) The ID of the Cognito user pool client.
  • userPoolDomain - (Required) The domain prefix or fully-qualified domain name of the Cognito user pool.

Authenticate OIDC Blocks (for authenticateOidc) supports the following:

  • authenticationRequestExtraParams - (Optional) The query parameters to include in the redirect request to the authorization endpoint. Max: 10.
  • authorizationEndpoint - (Required) The authorization endpoint of the IdP.
  • clientId - (Required) The OAuth 2.0 client identifier.
  • clientSecret - (Required) The OAuth 2.0 client secret.
  • issuer - (Required) The OIDC issuer identifier of the IdP.
  • onUnauthenticatedRequest - (Optional) The behavior if the user is not authenticated. Valid values: deny, allow and authenticate
  • scope - (Optional) The set of user claims to be requested from the IdP.
  • sessionCookieName - (Optional) The name of the cookie used to maintain session information.
  • sessionTimeout - (Optional) The maximum duration of the authentication session, in seconds.
  • tokenEndpoint - (Required) The token endpoint of the IdP.
  • userInfoEndpoint - (Required) The user info endpoint of the IdP.

Authentication Request Extra Params Blocks (for authenticationRequestExtraParams) supports the following:

  • key - (Required) The key of query parameter
  • value - (Required) The value of query parameter

Condition Blocks

One or more condition blocks can be set per rule. Most condition types can only be specified once per rule except for httpHeader and queryString which can be specified multiple times.

Condition Blocks (for condition) support the following:

  • hostHeader - (Optional) Contains a single values item which is a list of host header patterns to match. The maximum size of each pattern is 128 characters. Comparison is case insensitive. Wildcard characters supported: * (matches 0 or more characters) and ? (matches exactly 1 character). Only one pattern needs to match for the condition to be satisfied.
  • httpHeader - (Optional) HTTP headers to match. HTTP Header block fields documented below.
  • httpRequestMethod - (Optional) Contains a single values item which is a list of HTTP request methods or verbs to match. Maximum size is 40 characters. Only allowed characters are A-Z, hyphen (-) and underscore (_). Comparison is case sensitive. Wildcards are not supported. Only one needs to match for the condition to be satisfied. AWS recommends that GET and HEAD requests are routed in the same way because the response to a HEAD request may be cached.
  • pathPattern - (Optional) Contains a single values item which is a list of path patterns to match against the request URL. Maximum size of each pattern is 128 characters. Comparison is case sensitive. Wildcard characters supported: * (matches 0 or more characters) and ? (matches exactly 1 character). Only one pattern needs to match for the condition to be satisfied. Path pattern is compared only to the path of the URL, not to its query string. To compare against the query string, use a queryString condition.
  • queryString - (Optional) Query strings to match. Query String block fields documented below.
  • sourceIp - (Optional) Contains a single values item which is a list of source IP CIDR notations to match. You can use both IPv4 and IPv6 addresses. Wildcards are not supported. Condition is satisfied if the source IP address of the request matches one of the CIDR blocks. Condition is not satisfied by the addresses in the xForwardedFor header, use httpHeader condition instead.

\~> NOTE:: Exactly one of hostHeader, httpHeader, httpRequestMethod, pathPattern, queryString or sourceIp must be set per condition.

HTTP Header Blocks

HTTP Header Blocks (for httpHeader) support the following:

  • httpHeaderName - (Required) Name of HTTP header to search. The maximum size is 40 characters. Comparison is case insensitive. Only RFC7240 characters are supported. Wildcards are not supported. You cannot use HTTP header condition to specify the host header, use a hostHeader condition instead.
  • values - (Required) List of header value patterns to match. Maximum size of each pattern is 128 characters. Comparison is case insensitive. Wildcard characters supported: * (matches 0 or more characters) and ? (matches exactly 1 character). If the same header appears multiple times in the request they will be searched in order until a match is found. Only one pattern needs to match for the condition to be satisfied. To require that all of the strings are a match, create one condition block per string.

Query String Blocks

Query String Blocks (for queryString) support the following:

  • values - (Required) Query string pairs or values to match. Query String Value blocks documented below. Multiple values blocks can be specified, see example above. Maximum size of each string is 128 characters. Comparison is case insensitive. Wildcard characters supported: * (matches 0 or more characters) and ? (matches exactly 1 character). To search for a literal '*' or '?' character in a query string, escape the character with a backslash (\). Only one pair needs to match for the condition to be satisfied.

Query String Value Blocks (for queryStringValues) support the following:

  • key - (Optional) Query string key pattern to match.
  • value - (Required) Query string value pattern to match.

Attributes Reference

In addition to all arguments above, the following attributes are exported:

  • id - The ARN of the rule (matches arn)
  • arn - The ARN of the rule (matches id)
  • tagsAll - A map of tags assigned to the resource, including those inherited from the provider defaultTags configuration block.

Import

Rules can be imported using their ARN, e.g.,

$ terraform import aws_lb_listener_rule.front_end arn:aws:elasticloadbalancing:us-west-2:187416307283:listener-rule/app/test/8e4497da625e2d8a/9ab28ade35828f96/67b3d2d36dd7c26b