Source code for idem_aws.states.aws.elbv2.listener

"""
Autogenerated using `pop-create-idem <https://gitlab.com/saltstack/pop/pop-create-idem>`__

hub.exec.boto3.client.elbv2.add_listener_certificates
hub.exec.boto3.client.elbv2.create_listener
hub.exec.boto3.client.elbv2.delete_listener
hub.exec.boto3.client.elbv2.describe_listener_certificates
hub.exec.boto3.client.elbv2.describe_listeners
hub.exec.boto3.client.elbv2.describe_rules
hub.exec.boto3.client.elbv2.modify_listener
hub.exec.boto3.client.elbv2.remove_listener_certificates
hub.exec.boto3.client.elbv2.remove_tags
hub.exec.boto3.client.elbv2.describe_tags
hub.exec.boto3.client.elbv2.add_tags


"""
import copy
from dataclasses import field
from dataclasses import make_dataclass
from typing import Any
from typing import Dict
from typing import List

__contracts__ = ["resource"]


[docs]async def present( hub, ctx, name: str, lb_arn: str, default_actions: List[ make_dataclass( "Action", [ ("Type", str), ("TargetGroupArn", str, field(default=None)), ( "AuthenticateOidcConfig", make_dataclass( "AuthenticateOidcActionConfig", [ ("Issuer", str), ("AuthorizationEndpoint", str), ("TokenEndpoint", str), ("UserInfoEndpoint", str), ("ClientId", str), ("ClientSecret", str, field(default=None)), ("SessionCookieName", str, field(default=None)), ("Scope", str, field(default=None)), ("SessionTimeout", int, field(default=None)), ( "AuthenticationRequestExtraParams", Dict[str, str], field(default=None), ), ("OnUnauthenticatedRequest", str, field(default=None)), ("UseExistingClientSecret", bool, field(default=None)), ], ), field(default=None), ), ( "AuthenticateCognitoConfig", make_dataclass( "AuthenticateCognitoActionConfig", [ ("UserPoolArn", str), ("UserPoolClientId", str), ("UserPoolDomain", str), ("SessionCookieName", str, field(default=None)), ("Scope", str, field(default=None)), ("SessionTimeout", int, field(default=None)), ( "AuthenticationRequestExtraParams", Dict[str, str], field(default=None), ), ("OnUnauthenticatedRequest", str, field(default=None)), ], ), field(default=None), ), ("Order", int, field(default=None)), ( "RedirectConfig", make_dataclass( "RedirectActionConfig", [ ("StatusCode", str), ("Protocol", str, field(default=None)), ("Port", str, field(default=None)), ("Host", str, field(default=None)), ("Path", str, field(default=None)), ("Query", str, field(default=None)), ], ), field(default=None), ), ( "FixedResponseConfig", make_dataclass( "FixedResponseActionConfig", [ ("StatusCode", str), ("MessageBody", str, field(default=None)), ("ContentType", str, field(default=None)), ], ), field(default=None), ), ( "ForwardConfig", make_dataclass( "ForwardActionConfig", [ ( "TargetGroups", List[ make_dataclass( "TargetGroupTuple", [ ( "TargetGroupArn", str, field(default=None), ), ("Weight", int, field(default=None)), ], ) ], field(default=None), ), ( "TargetGroupStickinessConfig", make_dataclass( "TargetGroupStickinessConfig", [ ("Enabled", bool, field(default=None)), ("DurationSeconds", int, field(default=None)), ], ), field(default=None), ), ], ), field(default=None), ), ], ) ], resource_id: str = None, protocol: str = None, port: int = None, ssl_policy: str = None, default_certificates: List[ make_dataclass( "Certificate", [ ("CertificateArn", str, field(default=None)), ], ) ] = None, certificates: List[ make_dataclass( "Certificate", [ ("CertificateArn", str, field(default=None)), ], ) ] = None, alpn_policy: List[str] = None, tags: Dict[str, str] = None, ) -> Dict[str, Any]: """Creates a listener for the specified Application Load Balancer, Network Load Balancer, or Gateway Load Balancer. For more information, see the following: Listeners for your Application Load Balancers Listeners for your Network Load Balancers Listeners for your Gateway Load Balancers This operation is idempotent, which means that it completes at most one time. If you attempt to create multiple listeners with the same settings, each call succeeds. Args: name(str): IDEM name of the state. resource_id(str, Optional): An identifier of the resource in the provider. Defaults to None. The Amazon Resource Name (ARN) of the ElasticLoadBalancingv2 listener. lb_arn(str): The Amazon Resource Name (ARN) of the load balancer. protocol(str, Optional): The protocol for connections from clients to the load balancer. For Application Load Balancers, the supported protocols are HTTP and HTTPS. For Network Load Balancers, the supported protocols are TCP, TLS, UDP, and TCP_UDP. You can’t specify the UDP or TCP_UDP protocol if dual-stack mode is enabled. You cannot specify a protocol for a Gateway Load Balancer. Defaults to None. port(int, Optional): The port on which the load balancer is listening. You cannot specify a port for a Gateway LoadBalancer. Defaults to None. ssl_policy(str, Optional): [HTTPS and TLS listeners] The security policy that defines which protocols and ciphers are supported. For more information, see Security policies in the Application Load Balancers Guide and Security policies in the Network Load Balancers Guide. Defaults to None. default_certificates(list[dict[str, Any]], Optional): [HTTPS and TLS listeners] The default certificate for the listener. You must provide exactly one certificate. Set CertificateArn to the certificate ARN but do not set IsDefault. Defaults to None. * CertificateArn (str, Optional): The Amazon Resource Name (ARN) of the certificate. certificates(list[dict[str, Any]], Optional): The certificate to add. You can specify one certificate per call. Set CertificateArn to the certificate ARN but do not set IsDefault . * CertificateArn (str, Optional): The Amazon Resource Name (ARN) of the certificate. default_actions(list[dict[str, Any]]): The actions for the default rule. * Type (str): The type of action. * TargetGroupArn (str, Optional): The Amazon Resource Name (ARN) of the target group. Specify only when Type is forward and you want to route to a single target group. To route to one or more target groups, use ForwardConfig instead. * AuthenticateOidcConfig (dict[str, Any], Optional): [HTTPS listeners] Information about an identity provider that is compliant with OpenID Connect (OIDC). Specify only when Type is authenticate-oidc. * Issuer (str): The OIDC issuer identifier of the IdP. This must be a full URL, including the HTTPS protocol, the domain, and the path. * AuthorizationEndpoint (str): The authorization endpoint of the IdP. This must be a full URL, including the HTTPS protocol, the domain, and the path. * TokenEndpoint (str): The token endpoint of the IdP. This must be a full URL, including the HTTPS protocol, the domain, and the path. * UserInfoEndpoint (str): The user info endpoint of the IdP. This must be a full URL, including the HTTPS protocol, the domain, and the path. * ClientId (str): The OAuth 2.0 client identifier. * ClientSecret (str, Optional): The OAuth 2.0 client secret. This parameter is required if you are creating a rule. If you are modifying a rule, you can omit this parameter if you set UseExistingClientSecret to true. * SessionCookieName (str, Optional): Name of the cookie used to maintain session information. The default is AWSELBAuthSessionCookie. * Scope (str, Optional): The set of user claims to be requested from the IdP. The default is openid. To verify which scope values your IdP supports and how to separate multiple values, see the documentation for your IdP. * SessionTimeout (int, Optional): Maximum duration of authentication session, in seconds. The default is 604800 seconds (7days). * AuthenticationRequestExtraParams (Dict[str, str], Optional): The query parameters (up to 10) to include in the redirect request to the authorization endpoint. * OnUnauthenticatedRequest (str, Optional): The behavior if the user is not authenticated. The following are possible values: deny - Return an HTTP 401 Unauthorized error. allow - Allow the request to be forwarded to the target. authenticate - Redirect the request to IdP authorization endpoint. This is the default value. * UseExistingClientSecret (bool, Optional): Indicates whether to use the existing client secret when modifying a rule. If you are creating a rule, you can omit this parameter or set it to false. * AuthenticateCognitoConfig (dict[str, Any], Optional): [HTTPS listeners] Information for using Amazon Cognito to authenticate users. Specify only when Type is authenticate-cognito. * UserPoolArn (str): The Amazon Resource Name (ARN) of the Amazon Cognito user pool. * UserPoolClientId (str): The ID of the Amazon Cognito user pool client. * UserPoolDomain (str): The domain prefix or fully-qualified domain name of Amazon Cognito user pool. * SessionCookieName (str, Optional): Name of the cookie used to maintain session information. Defaults to AWSELBAuthSessionCookie. * Scope (str, Optional): The set of user claims to be requested from the IdP. The default is openid. To verify which scope values your IdP supports and how to separate multiple values, see the documentation for your IdP. * SessionTimeout (int, Optional): Maximum duration of the authentication session, in seconds. Defaults to 604800 seconds (7days). * AuthenticationRequesstrraParams (dict[str, str], Optional): The query parameters (up to 10) to include in redirect request to authorization endpoint. * OnUnauthenticatedRequest (str, Optional): The behavior if the user is not authenticated. The following are possible values: deny - Return an HTTP 401 Unauthorized error. allow - Allow the request to be forwarded to the target. authenticate - Redirect the request to the IdP authorization endpoint. This is the default value. * Order (int, Optional): The order for the action. This value is required for rules with multiple actions. The action with the lowest value for order is performed first. * RedirectConfig (dict[str, Any], Optional): [Application Load Balancer] Information for creating a redirect action. Specify only when Type is redirect. * Protocol (str, Optional): The protocol. You can specify HTTP, HTTPS, or #{protocol}. You can redirect HTTP to HTTP, HTTP to HTTPS, and HTTPS to HTTPS. You cannot redirect HTTPS to HTTP. * Port (str, Optional): The port. You can specify a value from 1 to 65535 or #{port}. * Host (str, Optional): The hostname. This component is not percent-encoded. The hostname can contain #{host}. * Path (str, Optional): The absolute path, starting with the leading "/". This component is not percent-encoded. The path can contain #{host}, #{path}, and #{port}. * Query (str, Optional): The query parameters, URL-encoded when necessary, but not percent-encoded. Do not include the leading "?", as it is automatically added. You can specify any of the reserved keywords. * StatusCode (str): HTTP redirect code. Redirect is either permanent (HTTP 301) or temporary (HTTP 302). * FixedResponseConfig (dict[str, Any], Optional): [Application Load Balancer] Information for creating an action that returns a custom HTTP response. Specify only when Type is fixed-response. * MessageBody (str, Optional): The message. * StatusCode (str): The HTTP response code (2XX, 4XX, or 5XX). * ContentType (str, Optional): The content type. Valid Values: str/plain | str/css | str/html | application/javascript | application/json * ForwardConfig (dict[str, Any], Optional): Information for creating an action that distributes requests among one or more target groups. For Network Load Balancers, you can specify a single target group. Specify only when Type is forward. If you specify both ForwardConfig and TargetGroupArn, you can specify only one target group using ForwardConfig and it must be the same target group specified in TargetGroupArn. * TargetGroups (list[dict[str, Any]], Optional): One or more target groups. For Network Load Balancers, you can specify a single target group. * TargetGroupArn (str, Optional): The Amazon Resource Name (ARN) of the target group. * Weight (int, Optional): The weight. The range is 0 to 999. * TargetGroupStickinessConfig (dict[str, Any], Optional): The target group stickiness for the rule. * Enabled (bool, Optional): Indicates whether target group stickiness is enabled. * DurationSeconds (int, 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). alpn_policy(list[str], Optional): [TLS listeners] The name of the Application-Layer Protocol Negotiation (ALPN) policy. You can specify one policy name. The following are the possible values: HTTP1Only HTTP2Only HTTP2Optional HTTP2Preferred None tags(dict[str, str], Optional): The tags to assign to the listener. Defaults to None. * Key (str): The key of the tag. * Value (str, Optional): The value of the tag. Request Syntax: [listener-name]: aws.elbv2.listener.present: - name: "string" - lb_arn: "string" - default_actions: "list" - resource_id: "string" - protocol: "string" - port: "integer" - ssl_policy: "string" - default_certificates: "list" - certificates: "list" - alpn_policy: "list" - tags: - 'string': "string" Returns: Dict[str, Any] Examples: .. code-block:: sls resource_is_present: aws.elbv2.listener.present: - name: 'my-listener' - lb_arn: 'arn:aws:elasticloadbalancing:us-west-2:45678908712456908:loadbalancer/app/my-load-balancer/50ghtc66t95c0c9188' - default_actions: - TargetGroupArn: arn:aws:elasticloadbalancing:us-west-2:45678908712456908:targetgroup/my-targets/73e2d6bc24d8a067 Type: Type - resource_id: 'arn:aws:elasticloadbalancing:us-west-2:45678908712456908:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2' - protocol: 'HTTPS' - port: 443 - ssl_policy: 'ELBSecurityPolicy-2015-05' - default_certificates: - CertificateArn: arn:aws:iam::45678908712456908:server-certificate/default-cert - certificates: - CertificateArn: arn:aws:iam::45678908712456908:server-certificate/my-server-cert - alpn_policy: - HTTP2Only - HTTP2Preferred - tags: name: my-listener """ result = dict(comment=[], old_state=None, new_state=None, name=name, result=True) plan_state = {} before = None resource_updated = False if resource_id: before = await hub.exec.aws.elbv2.listener.get( ctx=ctx, name=name, resource_id=resource_id ) if not before["result"] or not before["ret"]: result["result"] = False result["comment"] = before["comment"] return result result["old_state"] = copy.deepcopy(before["ret"]) plan_state = copy.deepcopy(result["old_state"]) input_params = { "port": port, "protocol": protocol, "ssl_policy": ssl_policy, "certificates": certificates, "default_certificates": default_certificates, "default_actions": default_actions, "tags": tags, "alpn_policy": alpn_policy, "listener_arn": resource_id, } update_return = await hub.tool.aws.elbv2.listener.update( ctx=ctx, name=name, current_state=result["old_state"], input_map=input_params, resource_id=resource_id, ) result["comment"] = update_return["comment"] if not update_return["result"]: result["result"] = False return result resource_updated = bool(update_return["ret"]) if resource_updated: if update_return["ret"] is not None: for updated_value in update_return["ret"]: plan_state[updated_value.get("Key")] = updated_value.get("Value") if ctx.get("test", False): result["comment"] += hub.tool.aws.comment_utils.would_update_comment( resource_type="aws.elbv2.listener", name=name ) else: result["comment"] += hub.tool.aws.comment_utils.update_comment( resource_type="aws.elbv2.listener", name=name ) if tags is not None and tags != result["old_state"].get("tags"): # Update tags update_tags = await hub.tool.aws.elbv2.tag.update( ctx=ctx, resource_id=resource_id, old_tags=result["old_state"].get("tags"), new_tags=tags, ) result["comment"] += update_tags["comment"] result["result"] = update_tags["result"] resource_updated = resource_updated or bool(update_tags["ret"]) if ctx.get("test", False) and update_tags["ret"]: plan_state["tags"] = update_tags["ret"] else: if ctx.get("test", False): result["new_state"] = hub.tool.aws.test_state_utils.generate_test_state( enforced_state={}, desired_state={ "name": name, "lb_arn": lb_arn, "default_actions": default_actions, "default_certificates": default_certificates, "protocol": protocol, "port": port, "ssl_policy": ssl_policy, "certificates": certificates, "alpn_policy": alpn_policy, "tags": tags, }, ) result["comment"] = hub.tool.aws.comment_utils.would_create_comment( resource_type="aws.elbv2.listener", name=name ) return result ret = await hub.exec.boto3.client.elbv2.create_listener( ctx, LoadBalancerArn=lb_arn, Protocol=protocol, Port=port, SslPolicy=ssl_policy, Certificates=default_certificates, DefaultActions=default_actions, AlpnPolicy=alpn_policy, Tags=hub.tool.aws.tag_utils.convert_tag_dict_to_list(tags) if tags else None, ) if not ret["result"] and not ret["ret"]: result["comment"] = ret["comment"] result["result"] = False return result resource_id = (ret["ret"]["Listeners"][0]).get("ListenerArn") result["comment"] = hub.tool.aws.comment_utils.create_comment( resource_type="aws.elbv2.listener", name=name ) if certificates: for certificate in certificates: add_certificate = ( await hub.exec.boto3.client.elbv2.add_listener_certificates( ctx, ListenerArn=resource_id, Certificates=[certificate] ) ) if not add_certificate["result"]: result["comment"] += add_certificate["comment"] result["result"] = False return result result["comment"] += ["Added Certificates."] if ctx.get("test", False): result["new_state"] = plan_state elif (not result["old_state"]) or resource_updated: after = await hub.exec.aws.elbv2.listener.get( ctx=ctx, name=name, resource_id=resource_id ) if not after["result"] or not after["ret"]: result["result"] = False result["comment"] += after["comment"] return result result["new_state"] = copy.deepcopy(after["ret"]) else: result["new_state"] = copy.deepcopy(result["old_state"]) return result
[docs]async def absent( hub, ctx, name: str, resource_id: str = None, ) -> Dict[str, Any]: """ Deletes the specified listener. Alternatively, your listener is deleted when you delete the load balancer to which it is attached. Args: name(str): Idem name of the ElasticLoadBalancingv2 Listener. resource_id(str, Optional): The Amazon Resource Name (ARN) of the ElasticLoadBalancingv2 listener. Request Syntax: [listener-name]: aws.elbv2.listener.absent: - name: "string" - resource_id: "string" Returns: Dict[str, Any] Examples: .. code-block:: sls test_listener_name: aws.elbv2.listener.absent: - name: test_listener_name - resource_id: arn:aws:elasticloadbalancing:ua-west-2:45678908712456908:listener/app/my-load-balancer/50dc6c495c0c9188/f2f7dc8efc522ab2 """ result = dict(comment=[], old_state=None, new_state=None, name=name, result=True) if not resource_id: result["comment"] = hub.tool.aws.comment_utils.already_absent_comment( resource_type="aws.elbv2.listener", name=name ) return result before = await hub.exec.aws.elbv2.listener.get( ctx=ctx, name=name, resource_id=resource_id ) if not before["result"]: result["comment"] = before["comment"] result["result"] = False return result if not before["ret"]: result["comment"] = hub.tool.aws.comment_utils.already_absent_comment( resource_type="aws.elbv2.listener", name=name ) else: result["old_state"] = before["ret"] if ctx.get("test", False): result["comment"] = hub.tool.aws.comment_utils.would_delete_comment( resource_type="aws.elbv2.listener", name=name ) return result else: ret = await hub.exec.boto3.client.elbv2.delete_listener( ctx, ListenerArn=resource_id ) if not ret["result"]: result["comment"] = before["comment"] result["result"] = False return result result["comment"] = hub.tool.aws.comment_utils.delete_comment( resource_type="aws.elbv2.listener", name=name ) return result
[docs]async def describe( hub, ctx, ) -> Dict[str, Dict[str, Any]]: """ 1. Describe the resource in a way that can be recreated/managed with the corresponding "present" function. 2. Describes the specified listeners or the listeners for the specified Application Load Balancer, Network Load Balancer, or Gateway Load Balancer. You must specify either a load balancer or one or more listeners. 3. Users must specify one of the 2 params: list of listener ARNs or a load balancer ARN. Else, describe operation fails with the following error. 'ClientError: An error occurred (ValidationError) when calling the DescribeListeners operation: You must specify either listener ARNs or a load balancer ARN' Returns: Dict[str, Any] Examples: .. code-block:: sls $ idem describe aws.elbv2.listener """ result = {} load_balancer_ret = await hub.exec.boto3.client.elbv2.describe_load_balancers(ctx) if not load_balancer_ret["result"]: hub.log.warning( f"Could not describe aws.elbv2.load_balancer: {load_balancer_ret['comment']}" ) return result if load_balancer_ret["ret"].get("LoadBalancers"): for load_balancer in load_balancer_ret["ret"].get("LoadBalancers"): ret = await hub.exec.boto3.client.elbv2.describe_listeners( ctx, LoadBalancerArn=load_balancer.get("LoadBalancerArn") ) if not ret["result"]: hub.log.debug( f"Could not describe aws.elbv2.listener(s) for aws.elbv2.load_balancer with ARN " f"{load_balancer.get('LoadBalancerArn')}: {ret['comment']}" ) continue if ret["ret"].get("Listeners"): for listener in ret["ret"]["Listeners"]: tags_ret = await hub.exec.boto3.client.elbv2.describe_tags( ctx, ResourceArns=[listener.get("ListenerArn")] ) if not tags_ret["result"]: # Error fetching tags. If fetching tags itself fails, skip and continue. Since tags are # optional, they need not be associated with all listener(s). But API needs to succeed. hub.log.warning( f"Failed listing tags for aws.elbv2.listener '{listener.get('ListenerArn')}'" f"Describe will skip this aws.elbv2.listener and continue. " ) continue tags = [] if tags_ret.get("ret") and tags_ret.get("ret")["TagDescriptions"]: tags = tags_ret["ret"]["TagDescriptions"][0].get("Tags") certificates_ret = await hub.exec.boto3.client.elbv2.describe_listener_certificates( ctx, ListenerArn=listener.get("ListenerArn") ) if not certificates_ret["result"]: # Since certificates are optional, they need not be associated with all listener(s). # For some reason the API fails if there are no certificates hub.log.info( f"Failed listing certificates for aws.elbv2.listener '{listener.get('ListenerArn')}'." f"This listener may not have certificates. " ) certificates = [] if certificates_ret.get("ret") and certificates_ret.get("ret").get( "Certificates" ): certificates = certificates_ret["ret"]["Certificates"] resource_converted = hub.tool.aws.elbv2.conversion_utils.convert_raw_listener_to_present( raw_resource=listener, idem_resource_name=listener.get("ListenerArn"), tags=hub.tool.aws.tag_utils.convert_tag_list_to_dict(tags), certificates=certificates, ) result[resource_converted["resource_id"]] = { "aws.elbv2.listener.present": [ {parameter_key: parameter_value} for parameter_key, parameter_value in resource_converted.items() ] } return result