How to remove a cloud armor secuiry policy from backend service using Python

Question:

I’m creating a few GCP cloud armor policies across multiple projects using the Python client library and attaching them to several backend services using the .set_security_policy() method

  1. I know you can do it using the console / gcloud but I need to automate this in Python

  2. I’ve tried the .update() method in google-cloud-compute but that did not work out

from google.cloud import compute, compute_v1

client = compute.BackendServicesClient()
backend_service_resource = compute_v1.types.BackendService(security_policy="")
client.update(project='project_id',
             backend_service='backend_service',
             backend_service_resource=backend_service_resource)

The error I got when running the above code is

google.api_core.exceptions.BadRequest: 400 PUT https://compute.googleapis.com/compute/v1/projects/<project-id>/global/backendServices/<backend-name>: Invalid value for field 'resource.loadBalancingScheme': 'INVALID_LOAD_BALANCING_SCHEME'. Cannot change load balancing scheme.

When I specify loadBalancingScheme then the same error occurs with another resource value. At run-time I would not have information of all the meta data of the backend-service and some meta-data might not be initialized in the first place.

Asked By: Anandha Krishnan H

||

Answers:

This is for anyone who had similar issues in the future. I was originally going to call the gcloud commands through python using os.system() as @giles-roberts recommended, but then I stumbled across a proper way to to do this using the Client Libraries

You simply use the same .set_security_policy() to set the security policy in the first place but this time make the policy as None. This is not quite obvious since the name of the security policy has to be a string in the documentation and it does not accept an empty string either.

from google.cloud import compute, compute_v1

client = compute.BackendServicesClient()
resource = compute_v1.types.SecurityPolicyReference(security_policy=None)
error = client.set_security_policy(project='<project_id>',
                                   backend_service='<backend_service>',
                                   security_policy_reference_resource=resource)
Answered By: Anandha Krishnan H
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.