> ## Documentation Index
> Fetch the complete documentation index at: https://cloudanix.com/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# PubSub Subscriptions Should Have Dead Letter Queue Enabled

### More Info:

Ensure that PubSub Subscriptions have enabled DLQ

### Risk Level

Low

### Address

Reliability, Operational Maturity, Security

### Compliance Standards

HIPAA, SOC2, PCIDSS, NIST

### Triage and Remediation

<Tabs>
  <Tab title="Remediation">
    ### Remediation

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        Sure, here are the step-by-step instructions to remediate the misconfiguration "PubSub Subscriptions Should Have Dead Letter Queue Enabled" in GCP using the GCP console:

        1. Open the GCP console and navigate to the Pub/Sub page.
        2. Select the subscription that needs to be remediated.
        3. Click on the "Edit" button at the top of the page.
        4. Scroll down to the "Delivery" section and click on "Add Dead-letter topic".
        5. In the "Dead-letter topic" field, enter the name of the topic where dead-letter messages should be sent.
        6. Click on the "Create" button to create the dead-letter topic.
        7. Set the maximum delivery attempts for the subscription by entering a value in the "Maximum delivery attempts" field.
        8. Click on the "Save" button to save the changes.

        Congratulations, you have now remediated the misconfiguration "PubSub Subscriptions Should Have Dead Letter Queue Enabled" in GCP using the GCP console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the misconfiguration of PubSub Subscriptions not having a Dead Letter Queue enabled in GCP using GCP CLI, follow the below steps:

        1. Open the Google Cloud Console and navigate to the Pub/Sub section.
        2. Select the subscription that needs to be remediated.
        3. Click on the "Edit" button at the top of the page.
        4. Under the "Delivery retry policy" section, enable the "Dead-letter topic" option.
        5. Select the topic that will be used as the Dead Letter Queue.
        6. Click on the "Save" button.

        Alternatively, you can use the gcloud command-line tool to remediate this misconfiguration. Follow the below steps:

        1. Open the terminal and authenticate to your GCP account using the command: `gcloud auth login`.
        2. Set the project that contains the Pub/Sub subscription using the command: `gcloud config set project [PROJECT_ID]`.
        3. Enable the Dead Letter Queue for the subscription using the command: `gcloud pubsub subscriptions update [SUBSCRIPTION_NAME] --dead-letter-topic=[DEAD_LETTER_TOPIC_NAME] --dead-letter-ack-deadline=[ACK_DEADLINE]`.

        Replace the following variables in the above command:

        * \[SUBSCRIPTION\_NAME]: Name of the subscription that needs to be remediated.
        * \[DEAD\_LETTER\_TOPIC\_NAME]: Name of the topic that will be used as the Dead Letter Queue.
        * \[ACK\_DEADLINE]: Acknowledgement deadline for the Dead Letter Queue in seconds.

        By following these steps, you can remediate the misconfiguration of PubSub Subscriptions not having a Dead Letter Queue enabled in GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the misconfiguration of PubSub Subscriptions not having Dead Letter Queue enabled in GCP using Python, follow these steps:

        1. Import the necessary libraries:

        ```python theme={null}
        from google.cloud import pubsub_v1
        from google.api_core import retry
        ```

        2. Set the project ID and subscription name:

        ```python theme={null}
        project_id = "your-project-id"
        subscription_name = "your-subscription-name"
        ```

        3. Create the PubSub client and subscription object:

        ```python theme={null}
        subscriber = pubsub_v1.SubscriberClient()
        subscription_path = subscriber.subscription_path(project_id, subscription_name)
        ```

        4. Check if the subscription already has a dead letter policy:

        ```python theme={null}
        subscription = subscriber.get_subscription(request={"subscription": subscription_path})
        if subscription.dead_letter_policy:
            print("Dead letter policy already exists.")
            exit()
        ```

        5. If the subscription does not have a dead letter policy, create one:

        ```python theme={null}
        dead_letter_topic = "projects/{}/topics/{}".format(project_id, "your-dead-letter-topic-name")
        dead_letter_policy = {
            "dead_letter_topic": dead_letter_topic,
            "max_delivery_attempts": 10,
        }
        update_mask = {"paths": ["dead_letter_policy"]}
        subscription.dead_letter_policy = dead_letter_policy
        ```

        6. Update the subscription with the new dead letter policy:

        ```python theme={null}
        update_request = {
            "subscription": subscription,
            "update_mask": update_mask,
        }
        response = subscriber.update_subscription(request=update_request)
        print("Dead letter policy has been enabled for the subscription.")
        ```

        7. Handle any errors that may occur during the update process:

        ```python theme={null}
        def handle_error(exception):
            print(f"Error occurred: {exception}")
            return retry.RetryResult.RETRY_ON_EXCEPTION

        retry_settings = retry.Retry(deadline=60, predicate=handle_error)
        response = subscriber.update_subscription(request=update_request, retry=retry_settings)
        ```

        Putting it all together, here's the complete code:

        ```python theme={null}
        from google.cloud import pubsub_v1
        from google.api_core import retry

        project_id = "your-project-id"
        subscription_name = "your-subscription-name"

        subscriber = pubsub_v1.SubscriberClient()
        subscription_path = subscriber.subscription_path(project_id, subscription_name)

        subscription = subscriber.get_subscription(request={"subscription": subscription_path})
        if subscription.dead_letter_policy:
            print("Dead letter policy already exists.")
            exit()

        dead_letter_topic = "projects/{}/topics/{}".format(project_id, "your-dead-letter-topic-name")
        dead_letter_policy = {
            "dead_letter_topic": dead_letter_topic,
            "max_delivery_attempts": 10,
        }
        update_mask = {"paths": ["dead_letter_policy"]}
        subscription.dead_letter_policy = dead_letter_policy

        update_request = {
            "subscription": subscription,
            "update_mask": update_mask,
        }

        def handle_error(exception):
            print(f"Error occurred: {exception}")
            return retry.RetryResult.RETRY_ON_EXCEPTION

        retry_settings = retry.Retry(deadline=60, predicate=handle_error)
        response = subscriber.update_subscription(request=update_request, retry=retry_settings)

        print("Dead letter policy has been enabled for the subscription.")
        ```

        Note: Replace the placeholders "your-project-id", "your-subscription-name", and "your-dead-letter-topic-name" with your actual project ID, subscription name, and dead letter topic name, respectively.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>

### Additional Reading:

* [https://cloud.google.com/pubsub/docs/handling-failures](https://cloud.google.com/pubsub/docs/handling-failures)
