> ## 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.

# Worker Pool Teardown Policy Should Be Set

### More Info:

Ensure worker pool teardown policy is set

### Risk Level

Low

### Address

Operational Maturity, Reliability

### Compliance Standards

* Cloudanix Best Practice

### Triage and Remediation

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

    <AccordionGroup>
      <Accordion title="Using Console" defaultOpen="true">
        To remediate the "Worker Pool Teardown Policy Should Be Set" misconfiguration in GCP using GCP console, please follow the below steps:

        1. Open the GCP Console and navigate to the Cloud Build page.

        2. Click on the "Worker pools" tab from the left-hand menu.

        3. Select the worker pool for which you want to set the teardown policy.

        4. Click on the "Edit" button at the top of the page.

        5. Scroll down to the "Teardown policy" section.

        6. Select the "Delete instances when the pool is idle" option.

        7. Click on the "Save" button at the bottom of the page.

        8. Verify that the teardown policy has been set correctly by checking the "Teardown policy" section for the worker pool.

        By following these steps, you will have successfully remediated the "Worker Pool Teardown Policy Should Be Set" misconfiguration in GCP using GCP console.

        #
      </Accordion>

      <Accordion title="Using CLI">
        To remediate the "Worker Pool Teardown Policy Should Be Set" misconfiguration for GCP using GCP CLI, you can follow the below steps:

        1. Open the Google Cloud SDK Shell or any other terminal of your choice.

        2. Run the following command to set the worker pool teardown policy to "delete":

        ```
        gcloud container node-pools update [POOL_NAME] --cluster=[CLUSTER_NAME] --workload-metadata=GKE_METADATA --teardown-policy=delete
        ```

        Note: Replace \[POOL\_NAME] with the name of the node pool that you want to update and \[CLUSTER\_NAME] with the name of the cluster that the node pool belongs to.

        3. Once the command is executed successfully, the worker pool teardown policy will be set to "delete".

        4. Verify the changes by running the following command:

        ```
        gcloud container node-pools describe [POOL_NAME] --cluster=[CLUSTER_NAME] --format="json" | jq '.management.autoRepair' 
        ```

        Note: Make sure to replace \[POOL\_NAME] and \[CLUSTER\_NAME] with the actual names.

        5. If the output of the above command is "true", then the worker pool teardown policy has been successfully set to "delete".

        By following these steps, you can remediate the "Worker Pool Teardown Policy Should Be Set" misconfiguration for GCP using GCP CLI.
      </Accordion>

      <Accordion title="Using Python">
        To remediate the "Worker Pool Teardown Policy Should Be Set" misconfiguration in GCP using Python, you can follow the below steps:

        1. Install the required libraries:

           ```
           pip install google-cloud-logging google-auth google-auth-oauthlib google-auth-httplib2
           ```

        2. Set up authentication to access the GCP project:

           ```
           from google.oauth2 import service_account

           credentials = service_account.Credentials.from_service_account_file('path/to/service_account.json')
           ```

        3. Create a Logging client to access the logs:

           ```
           from google.cloud import logging_v2

           client = logging_v2.LoggingServiceV2Client(credentials=credentials)
           ```

        4. Define the filter to search for the relevant log entries:

           ```
           filter_str = 'resource.type="k8s_container" AND log_name="projects/<project_id>/logs/stderr" AND severity="ERROR" AND textPayload:"WorkerPoolTeardownPolicy" AND textPayload:"not set"'
           ```

           Replace `<project_id>` with your GCP project ID.

        5. Retrieve the log entries using the filter:

           ```
           response = client.list_log_entries(filter_=filter_str)
           ```

        6. For each log entry, retrieve the relevant metadata:

           ```
           for entry in response:
               print(f"Log Name: {entry.log_name}")
               print(f"Resource Type: {entry.resource.type}")
               print(f"Resource Labels: {entry.resource.labels}")
               print(f"Severity: {entry.severity}")
               print(f"Timestamp: {entry.timestamp}")
               print(f"Message: {entry.json_payload['message']}")
           ```

        7. For each relevant metadata, remediate the misconfiguration by setting the Worker Pool Teardown Policy:

           ```
           from google.cloud import container_v1

           client = container_v1.ClusterManagerClient(credentials=credentials)

           project_id = "<project_id>"
           zone = "<zone>"
           cluster_id = "<cluster_id>"

           cluster = client.get_cluster(project_id, zone, cluster_id)

           # Update the Worker Pool Teardown Policy
           for pool in cluster.node_pools:
               pool.management.auto_repair = True
               pool.management.auto_upgrade = True
               pool.management.auto_upgrade_maintenance_policy = {
                   "window": {
                       "dailyMaintenanceWindow": {
                           "startTime": "02:00"
                       }
                   }
               }

           # Update the cluster with the new configuration
           update_request = container_v1.types.UpdateClusterRequest(cluster=cluster, update_mask={"paths": ["node_pools"]})
           operation = client.update_cluster(update_request)
           ```

           Replace `<project_id>`, `<zone>` and `<cluster_id>` with your specific details.

        8. Verify that the misconfiguration has been remediated by checking the logs again.
      </Accordion>

      <Accordion title="Using Terraform">
        ```hcl theme={null}
        # This setting is not currently exposed by the Terraform Google provider for Dataflow jobs.
        # The worker pool teardown policy can only be controlled at job run time (e.g. via gcloud flags),
        # not via arguments on google_dataflow_job or any other Terraform-managed resource.

        # Example Dataflow job resource (shown only to clarify that no teardown policy argument exists):
        resource "google_dataflow_job" "example" {
          name              = "EXAMPLE_JOB_NAME"          # replace with your job name
          template_gcs_path = "gs://EXAMPLE_TEMPLATE"     # replace with your template path
          temp_gcs_location = "gs://EXAMPLE_TEMP_BUCKET"  # replace with your temp bucket
          region            = "EXAMPLE_REGION"            # replace with your region
          on_delete         = "cancel"                    # typical lifecycle choice

          # No argument here can set the worker pool teardown policy; the provider does not support it.
        }
        ```

        This finding cannot be remediated via Terraform because the Google provider does not expose the Dataflow worker pool teardown policy. Configure it at job submission time instead, for example with:

        * gcloud: `gcloud dataflow jobs run JOB_NAME --gcs-location=TEMPLATE --worker-pool-teardown-policy=TEARDOWN_POLICY ...`
        * Console: when launching the job from a template, set the worker teardown/retention option in the advanced worker configuration panel.

        For verification, `terraform plan` will show no changes related to teardown policy, since that setting is outside Terraform’s control.
      </Accordion>
    </AccordionGroup>
  </Tab>
</Tabs>
