# coding=utf-8
# *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. ***
# *** Do not edit by hand unless you're certain you know what you are doing! ***

import warnings
import pulumi
import pulumi.runtime
from typing import Any, Mapping, Optional, Sequence, Union
from .. import _utilities, _tables

__all__ = ['TopicSubscription']


class TopicSubscription(pulumi.CustomResource):
    def __init__(__self__,
                 resource_name: str,
                 opts: Optional[pulumi.ResourceOptions] = None,
                 confirmation_timeout_in_minutes: Optional[pulumi.Input[int]] = None,
                 delivery_policy: Optional[pulumi.Input[str]] = None,
                 endpoint: Optional[pulumi.Input[str]] = None,
                 endpoint_auto_confirms: Optional[pulumi.Input[bool]] = None,
                 filter_policy: Optional[pulumi.Input[str]] = None,
                 protocol: Optional[pulumi.Input[str]] = None,
                 raw_message_delivery: Optional[pulumi.Input[bool]] = None,
                 topic: Optional[pulumi.Input[str]] = None,
                 __props__=None,
                 __name__=None,
                 __opts__=None):
        """
        Provides a resource for subscribing to SNS topics. Requires that an SNS topic exist for the subscription to attach to.
        This resource allows you to automatically place messages sent to SNS topics in SQS queues, send them as HTTP(S) POST requests
        to a given endpoint, send SMS messages, or notify devices / applications. The most likely use case will
        probably be SQS queues.

        > **NOTE:** If the SNS topic and SQS queue are in different AWS regions, it is important for the "sns.TopicSubscription" to use an AWS provider that is in the same region of the SNS topic. If the "sns.TopicSubscription" is using a provider with a different region than the SNS topic, the subscription will fail to create.

        > **NOTE:** Setup of cross-account subscriptions from SNS topics to SQS queues requires the provider to have access to BOTH accounts.

        > **NOTE:** If SNS topic and SQS queue are in different AWS accounts but the same region it is important for the "sns.TopicSubscription" to use the AWS provider of the account with the SQS queue. If "sns.TopicSubscription" is using a Provider with a different account than the SQS queue, the provider creates the subscriptions but does not keep state and tries to re-create the subscription at every apply.

        > **NOTE:** If SNS topic and SQS queue are in different AWS accounts and different AWS regions it is important to recognize that the subscription needs to be initiated from the account with the SQS queue but in the region of the SNS topic.

        ## Example Usage

        You can directly supply a topic and ARN by hand in the `topic_arn` property along with the queue ARN:

        ```python
        import pulumi
        import pulumi_aws as aws

        user_updates_sqs_target = aws.sns.TopicSubscription("userUpdatesSqsTarget",
            endpoint="arn:aws:sqs:us-west-2:432981146916:queue-too",
            protocol="sqs",
            topic="arn:aws:sns:us-west-2:432981146916:user-updates-topic")
        ```

        Alternatively you can use the ARN properties of a managed SNS topic and SQS queue:

        ```python
        import pulumi
        import pulumi_aws as aws

        user_updates = aws.sns.Topic("userUpdates")
        user_updates_queue = aws.sqs.Queue("userUpdatesQueue")
        user_updates_sqs_target = aws.sns.TopicSubscription("userUpdatesSqsTarget",
            topic=user_updates.arn,
            protocol="sqs",
            endpoint=user_updates_queue.arn)
        ```

        You can subscribe SNS topics to SQS queues in different Amazon accounts and regions:

        ```python
        import pulumi
        import pulumi_aws as aws
        import pulumi_pulumi as pulumi

        config = pulumi.Config()
        sns = config.get_object("sns")
        if sns is None:
            sns = {
                "account-id": "111111111111",
                "role-name": "service/service",
                "name": "example-sns-topic",
                "display_name": "example",
                "region": "us-west-1",
            }
        sqs = config.get_object("sqs")
        if sqs is None:
            sqs = {
                "account-id": "222222222222",
                "role-name": "service/service",
                "name": "example-sqs-queue",
                "region": "us-east-1",
            }
        sns_topic_policy = aws.iam.get_policy_document(policy_id="__default_policy_ID",
            statements=[
                aws.iam.GetPolicyDocumentStatementArgs(
                    actions=[
                        "SNS:Subscribe",
                        "SNS:SetTopicAttributes",
                        "SNS:RemovePermission",
                        "SNS:Receive",
                        "SNS:Publish",
                        "SNS:ListSubscriptionsByTopic",
                        "SNS:GetTopicAttributes",
                        "SNS:DeleteTopic",
                        "SNS:AddPermission",
                    ],
                    conditions=[aws.iam.GetPolicyDocumentStatementConditionArgs(
                        test="StringEquals",
                        variable="AWS:SourceOwner",
                        values=[sns["account-id"]],
                    )],
                    effect="Allow",
                    principals=[aws.iam.GetPolicyDocumentStatementPrincipalArgs(
                        type="AWS",
                        identifiers=["*"],
                    )],
                    resources=[f"arn:aws:sns:{sns['region']}:{sns['account-id']}:{sns['name']}"],
                    sid="__default_statement_ID",
                ),
                aws.iam.GetPolicyDocumentStatementArgs(
                    actions=[
                        "SNS:Subscribe",
                        "SNS:Receive",
                    ],
                    conditions=[aws.iam.GetPolicyDocumentStatementConditionArgs(
                        test="StringLike",
                        variable="SNS:Endpoint",
                        values=[f"arn:aws:sqs:{sqs['region']}:{sqs['account-id']}:{sqs['name']}"],
                    )],
                    effect="Allow",
                    principals=[aws.iam.GetPolicyDocumentStatementPrincipalArgs(
                        type="AWS",
                        identifiers=["*"],
                    )],
                    resources=[f"arn:aws:sns:{sns['region']}:{sns['account-id']}:{sns['name']}"],
                    sid="__console_sub_0",
                ),
            ])
        sqs_queue_policy = aws.iam.get_policy_document(policy_id=f"arn:aws:sqs:{sqs['region']}:{sqs['account-id']}:{sqs['name']}/SQSDefaultPolicy",
            statements=[aws.iam.GetPolicyDocumentStatementArgs(
                sid="example-sns-topic",
                effect="Allow",
                principals=[aws.iam.GetPolicyDocumentStatementPrincipalArgs(
                    type="AWS",
                    identifiers=["*"],
                )],
                actions=["SQS:SendMessage"],
                resources=[f"arn:aws:sqs:{sqs['region']}:{sqs['account-id']}:{sqs['name']}"],
                conditions=[aws.iam.GetPolicyDocumentStatementConditionArgs(
                    test="ArnEquals",
                    variable="aws:SourceArn",
                    values=[f"arn:aws:sns:{sns['region']}:{sns['account-id']}:{sns['name']}"],
                )],
            )])
        # provider to manage SNS topics
        aws_sns = pulumi.providers.Aws("awsSns",
            region=sns["region"],
            assume_role=aws.config.AssumeRoleArgs(
                role_arn=f"arn:aws:iam::{sns['account-id']}:role/{sns['role-name']}",
                session_name=f"sns-{sns['region']}",
            ))
        # provider to manage SQS queues
        aws_sqs = pulumi.providers.Aws("awsSqs",
            region=sqs["region"],
            assume_role=aws.config.AssumeRoleArgs(
                role_arn=f"arn:aws:iam::{sqs['account-id']}:role/{sqs['role-name']}",
                session_name=f"sqs-{sqs['region']}",
            ))
        # provider to subscribe SQS to SNS (using the SQS account but the SNS region)
        sns2sqs = pulumi.providers.Aws("sns2sqs",
            region=sns["region"],
            assume_role=aws.config.AssumeRoleArgs(
                role_arn=f"arn:aws:iam::{sqs['account-id']}:role/{sqs['role-name']}",
                session_name=f"sns2sqs-{sns['region']}",
            ))
        sns_topic_topic = aws.sns.Topic("sns-topicTopic",
            display_name=sns["display_name"],
            policy=sns_topic_policy.json,
            opts=pulumi.ResourceOptions(provider="aws.sns"))
        sqs_queue = aws.sqs.Queue("sqs-queue", policy=sqs_queue_policy.json,
        opts=pulumi.ResourceOptions(provider="aws.sqs"))
        sns_topic_topic_subscription = aws.sns.TopicSubscription("sns-topicTopicSubscription",
            topic=sns_topic_topic.arn,
            protocol="sqs",
            endpoint=sqs_queue.arn,
            opts=pulumi.ResourceOptions(provider="aws.sns2sqs"))
        ```

        ## Import

        SNS Topic Subscriptions can be imported using the `subscription arn`, e.g.

        ```sh
         $ pulumi import aws:sns/topicSubscription:TopicSubscription user_updates_sqs_target arn:aws:sns:us-west-2:0123456789012:my-topic:8a21d249-4329-4871-acc6-7be709c6ea7f
        ```

        :param str resource_name: The name of the resource.
        :param pulumi.ResourceOptions opts: Options for the resource.
        :param pulumi.Input[int] confirmation_timeout_in_minutes: Integer indicating number of minutes to wait in retying mode for fetching subscription arn before marking it as failure. Only applicable for http and https protocols (default is 1 minute).
        :param pulumi.Input[str] delivery_policy: JSON String with the delivery policy (retries, backoff, etc.) that will be used in the subscription - this only applies to HTTP/S subscriptions. Refer to the [SNS docs](https://docs.aws.amazon.com/sns/latest/dg/DeliveryPolicies.html) for more details.
        :param pulumi.Input[str] endpoint: The endpoint to send data to, the contents will vary with the protocol. (see below for more information)
        :param pulumi.Input[bool] endpoint_auto_confirms: Boolean indicating whether the end point is capable of [auto confirming subscription](http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html#SendMessageToHttp.prepare) e.g., PagerDuty (default is false)
        :param pulumi.Input[str] filter_policy: JSON String with the filter policy that will be used in the subscription to filter messages seen by the target resource. Refer to the [SNS docs](https://docs.aws.amazon.com/sns/latest/dg/message-filtering.html) for more details.
        :param pulumi.Input[str] protocol: The protocol to use. The possible values for this are: `sqs`, `sms`, `lambda`, `application`. (`http` or `https` are partially supported, see below) (`email` is an option but is unsupported, see below).
        :param pulumi.Input[bool] raw_message_delivery: Boolean indicating whether or not to enable raw message delivery (the original message is directly passed, not wrapped in JSON with the original message in the message property) (default is false).
        :param pulumi.Input[str] topic: The ARN of the SNS topic to subscribe to
        """
        if __name__ is not None:
            warnings.warn("explicit use of __name__ is deprecated", DeprecationWarning)
            resource_name = __name__
        if __opts__ is not None:
            warnings.warn("explicit use of __opts__ is deprecated, use 'opts' instead", DeprecationWarning)
            opts = __opts__
        if opts is None:
            opts = pulumi.ResourceOptions()
        if not isinstance(opts, pulumi.ResourceOptions):
            raise TypeError('Expected resource options to be a ResourceOptions instance')
        if opts.version is None:
            opts.version = _utilities.get_version()
        if opts.id is None:
            if __props__ is not None:
                raise TypeError('__props__ is only valid when passed in combination with a valid opts.id to get an existing resource')
            __props__ = dict()

            __props__['confirmation_timeout_in_minutes'] = confirmation_timeout_in_minutes
            __props__['delivery_policy'] = delivery_policy
            if endpoint is None and not opts.urn:
                raise TypeError("Missing required property 'endpoint'")
            __props__['endpoint'] = endpoint
            __props__['endpoint_auto_confirms'] = endpoint_auto_confirms
            __props__['filter_policy'] = filter_policy
            if protocol is None and not opts.urn:
                raise TypeError("Missing required property 'protocol'")
            __props__['protocol'] = protocol
            __props__['raw_message_delivery'] = raw_message_delivery
            if topic is None and not opts.urn:
                raise TypeError("Missing required property 'topic'")
            __props__['topic'] = topic
            __props__['arn'] = None
        super(TopicSubscription, __self__).__init__(
            'aws:sns/topicSubscription:TopicSubscription',
            resource_name,
            __props__,
            opts)

    @staticmethod
    def get(resource_name: str,
            id: pulumi.Input[str],
            opts: Optional[pulumi.ResourceOptions] = None,
            arn: Optional[pulumi.Input[str]] = None,
            confirmation_timeout_in_minutes: Optional[pulumi.Input[int]] = None,
            delivery_policy: Optional[pulumi.Input[str]] = None,
            endpoint: Optional[pulumi.Input[str]] = None,
            endpoint_auto_confirms: Optional[pulumi.Input[bool]] = None,
            filter_policy: Optional[pulumi.Input[str]] = None,
            protocol: Optional[pulumi.Input[str]] = None,
            raw_message_delivery: Optional[pulumi.Input[bool]] = None,
            topic: Optional[pulumi.Input[str]] = None) -> 'TopicSubscription':
        """
        Get an existing TopicSubscription resource's state with the given name, id, and optional extra
        properties used to qualify the lookup.

        :param str resource_name: The unique name of the resulting resource.
        :param pulumi.Input[str] id: The unique provider ID of the resource to lookup.
        :param pulumi.ResourceOptions opts: Options for the resource.
        :param pulumi.Input[str] arn: The ARN of the subscription stored as a more user-friendly property
        :param pulumi.Input[int] confirmation_timeout_in_minutes: Integer indicating number of minutes to wait in retying mode for fetching subscription arn before marking it as failure. Only applicable for http and https protocols (default is 1 minute).
        :param pulumi.Input[str] delivery_policy: JSON String with the delivery policy (retries, backoff, etc.) that will be used in the subscription - this only applies to HTTP/S subscriptions. Refer to the [SNS docs](https://docs.aws.amazon.com/sns/latest/dg/DeliveryPolicies.html) for more details.
        :param pulumi.Input[str] endpoint: The endpoint to send data to, the contents will vary with the protocol. (see below for more information)
        :param pulumi.Input[bool] endpoint_auto_confirms: Boolean indicating whether the end point is capable of [auto confirming subscription](http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html#SendMessageToHttp.prepare) e.g., PagerDuty (default is false)
        :param pulumi.Input[str] filter_policy: JSON String with the filter policy that will be used in the subscription to filter messages seen by the target resource. Refer to the [SNS docs](https://docs.aws.amazon.com/sns/latest/dg/message-filtering.html) for more details.
        :param pulumi.Input[str] protocol: The protocol to use. The possible values for this are: `sqs`, `sms`, `lambda`, `application`. (`http` or `https` are partially supported, see below) (`email` is an option but is unsupported, see below).
        :param pulumi.Input[bool] raw_message_delivery: Boolean indicating whether or not to enable raw message delivery (the original message is directly passed, not wrapped in JSON with the original message in the message property) (default is false).
        :param pulumi.Input[str] topic: The ARN of the SNS topic to subscribe to
        """
        opts = pulumi.ResourceOptions.merge(opts, pulumi.ResourceOptions(id=id))

        __props__ = dict()

        __props__["arn"] = arn
        __props__["confirmation_timeout_in_minutes"] = confirmation_timeout_in_minutes
        __props__["delivery_policy"] = delivery_policy
        __props__["endpoint"] = endpoint
        __props__["endpoint_auto_confirms"] = endpoint_auto_confirms
        __props__["filter_policy"] = filter_policy
        __props__["protocol"] = protocol
        __props__["raw_message_delivery"] = raw_message_delivery
        __props__["topic"] = topic
        return TopicSubscription(resource_name, opts=opts, __props__=__props__)

    @property
    @pulumi.getter
    def arn(self) -> pulumi.Output[str]:
        """
        The ARN of the subscription stored as a more user-friendly property
        """
        return pulumi.get(self, "arn")

    @property
    @pulumi.getter(name="confirmationTimeoutInMinutes")
    def confirmation_timeout_in_minutes(self) -> pulumi.Output[Optional[int]]:
        """
        Integer indicating number of minutes to wait in retying mode for fetching subscription arn before marking it as failure. Only applicable for http and https protocols (default is 1 minute).
        """
        return pulumi.get(self, "confirmation_timeout_in_minutes")

    @property
    @pulumi.getter(name="deliveryPolicy")
    def delivery_policy(self) -> pulumi.Output[Optional[str]]:
        """
        JSON String with the delivery policy (retries, backoff, etc.) that will be used in the subscription - this only applies to HTTP/S subscriptions. Refer to the [SNS docs](https://docs.aws.amazon.com/sns/latest/dg/DeliveryPolicies.html) for more details.
        """
        return pulumi.get(self, "delivery_policy")

    @property
    @pulumi.getter
    def endpoint(self) -> pulumi.Output[str]:
        """
        The endpoint to send data to, the contents will vary with the protocol. (see below for more information)
        """
        return pulumi.get(self, "endpoint")

    @property
    @pulumi.getter(name="endpointAutoConfirms")
    def endpoint_auto_confirms(self) -> pulumi.Output[Optional[bool]]:
        """
        Boolean indicating whether the end point is capable of [auto confirming subscription](http://docs.aws.amazon.com/sns/latest/dg/SendMessageToHttp.html#SendMessageToHttp.prepare) e.g., PagerDuty (default is false)
        """
        return pulumi.get(self, "endpoint_auto_confirms")

    @property
    @pulumi.getter(name="filterPolicy")
    def filter_policy(self) -> pulumi.Output[Optional[str]]:
        """
        JSON String with the filter policy that will be used in the subscription to filter messages seen by the target resource. Refer to the [SNS docs](https://docs.aws.amazon.com/sns/latest/dg/message-filtering.html) for more details.
        """
        return pulumi.get(self, "filter_policy")

    @property
    @pulumi.getter
    def protocol(self) -> pulumi.Output[str]:
        """
        The protocol to use. The possible values for this are: `sqs`, `sms`, `lambda`, `application`. (`http` or `https` are partially supported, see below) (`email` is an option but is unsupported, see below).
        """
        return pulumi.get(self, "protocol")

    @property
    @pulumi.getter(name="rawMessageDelivery")
    def raw_message_delivery(self) -> pulumi.Output[Optional[bool]]:
        """
        Boolean indicating whether or not to enable raw message delivery (the original message is directly passed, not wrapped in JSON with the original message in the message property) (default is false).
        """
        return pulumi.get(self, "raw_message_delivery")

    @property
    @pulumi.getter
    def topic(self) -> pulumi.Output[str]:
        """
        The ARN of the SNS topic to subscribe to
        """
        return pulumi.get(self, "topic")

    def translate_output_property(self, prop):
        return _tables.CAMEL_TO_SNAKE_CASE_TABLE.get(prop) or prop

    def translate_input_property(self, prop):
        return _tables.SNAKE_TO_CAMEL_CASE_TABLE.get(prop) or prop

