Google Cloud Org Policy

1.17.0 · active · verified Sun Apr 12

The Google Cloud Org Policy API client library allows users to configure governance rules on their GCP resources across the Cloud Resource Hierarchy. It is currently at version 1.17.0 and maintains a regular release cadence with updates often for new features or bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to instantiate the `OrgPolicyClient` and list all available organization constraints for a given Google Cloud organization. It highlights the use of `orgpolicy_v2` for API versioning and standard Google Cloud authentication practices.

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

# Set your Google Cloud Project ID and Organization ID
# Or ensure GOOGLE_APPLICATION_CREDENTIALS environment variable is set.
# For local development, use 'gcloud auth application-default login'
# For deployed apps, use attached service accounts.

def list_organization_constraints(organization_id: str):
    """Lists all organization constraints.

    Args:
        organization_id: The numeric ID of your Google Cloud Organization (e.g., '12345678901').
    """
    client = orgpolicy_v2.OrgPolicyClient()

    # The parent resource for all constraints (e.g., 'organizations/ORGANIZATION_ID')
    parent_resource = f"organizations/{organization_id}"

    print(f"Listing constraints for organization: {parent_resource}")

    # Initialize request argument(s)
    request = types.ListConstraintsRequest(parent=parent_resource)

    # Make the request
    page_result = client.list_constraints(request=request)

    # Handle the response
    for response in page_result:
        print(f"Constraint: {response.name} ({response.display_name})")
        print(f"  Description: {response.description}")
        print(f"  Supports Conditions: {response.supports_conditions}")

# Example usage (replace with your actual organization ID)
if __name__ == "__main__":
    # It's recommended to set GOOGLE_APPLICATION_CREDENTIALS or use 'gcloud auth application-default login'
    # for local execution. For this example, we'll try to get it from environment or use a placeholder.
    # Replace 'YOUR_ORGANIZATION_ID' with your actual Google Cloud Organization ID
    org_id = os.environ.get('GCP_ORGANIZATION_ID', 'YOUR_ORGANIZATION_ID')

    if org_id == 'YOUR_ORGANIZATION_ID':
        print("Please set the GCP_ORGANIZATION_ID environment variable or replace 'YOUR_ORGANIZATION_ID' in the code.")
    else:
        try:
            list_organization_constraints(org_id)
        except Exception as e:
            print(f"An error occurred: {e}")
            print("Ensure you have the necessary IAM permissions (e.g., 'orgpolicy.policyViewer') and your organization ID is correct.")

view raw JSON →