Search code examples
pythongoogle-cloud-platformgoogle-cloud-resource-manager

How to create an Org Policy Constraint with conditions? - GCP


I am working on a small project in python, with which I could create the org policy gcp.disableSerialPortAccess as "Not Enforced" Org Policy with the condition of "tagValues/776487819778".

I can feel it that is something simple, but i do not understand how to create the request...

I tried using this request https://github.com/googleapis/python-org-policy/blob/main/samples/generated_samples/orgpolicy_v2_generated_org_policy_create_policy_sync.py , but i do not know how to construct it.

This is how i try to end up: https://cloud.google.com/resource-manager/docs/organization-policy/tags-organization-policy#boolean_policy_example

Spec : Rule Enforce with Condition as "tagValues/776487819778"

Can someone please help?

from google.cloud import orgpolicy_v2
from google.cloud.orgpolicy_v2 import types

Exp=(
    "expression" : "tagValues/776487819778",
    "title" : "this is the title",
    "description" : "this is a description",
    )


def build_policy():
    
    
    
    
    
    rule = types.PolicySpec.PolicyRule()
    rule.enforce = False
    rule.condition = (Exp)
    


    print(types.PolicySpec.PolicyRule)
    
    spec = types.PolicySpec()
    spec.rules.append(rule)
    

    policy = types.Policy(
        name="projects/project-id/policies/gcp.disableSerialPortAccess",
        spec = spec
        )

    return policy


def sample_update_policy():
    # Create a client   
    client = orgpolicy_v2.OrgPolicyClient()

    policy = build_policy()

    # Debug - view created policy
    print(policy)

    # Initialize request argument(s)
    request = orgpolicy_v2.UpdatePolicyRequest(
        policy=policy,
    )

    # Make the request
    response = client.update_policy(request=request)
    
    # Handle the response
    print(response)

sample_update_policy()

Solution

  • Exp is a dictionary (Key/Value).

    To duplicate the example in your link use the following code:

    def build_policy():
        Exp = {
            "expression" : "resource.matchTagId('org-id-from-gcp/disableSerialAccess', 'yes')",
            "title" : "this is the title",
            "description" : "this is a description",
        }
    
        rule1 = types.PolicySpec.PolicyRule()
        rule1.enforce = True
        rule1.condition = Exp
    
        rule2 = types.PolicySpec.PolicyRule()
        rule2.enforce = False
    
        spec = types.PolicySpec()
    
        spec.rules.append(rule1)
        spec.rules.append(rule2)
    
        policy = types.Policy(
            name="projects/project-id-from-gcp/policies/gcp.disableSerialPortAccess",
            spec = spec
        )
    
        return policy