python - 如何创建有条件的组织政策约束? - GCP

标签 python google-cloud-platform google-cloud-resource-manager

我正在用 python 开发一个小项目,用它我可以将组织策略 gcp.disableSerialPortAccess 创建为“未强制执行”组织策略,条件为“tagValues/776487819778”。

我觉得这很简单,但我不明白如何创建请求......

我尝试使用此请求 https://github.com/googleapis/python-org-policy/blob/main/samples/generated_samples/orgpolicy_v2_generated_org_policy_create_policy_sync.py ,但我不知道如何构建它。

这就是我尝试结束的方式: https://cloud.google.com/resource-manager/docs/organization-policy/tags-organization-policy#boolean_policy_example

规范:规则强制执行,条件为“tagValues/776487819778”

有人可以帮忙吗?

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()

最佳答案

Exp 是一个字典(键/值)。

复制 link 中的示例使用以下代码:

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

关于python - 如何创建有条件的组织政策约束? - GCP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71530226/

相关文章:

google-app-engine - CRMint 部署问题 - IndexError : tuple index out of range

google-cloud-platform - 如何在谷歌云平台 (GCP) 中跨服务 (API)、资源类型和项目列出、查找或搜索 iam 策略?

google-cloud-platform - 如何在 Google Cloud Platform 中跨服务 (API) 和项目查找、列出或搜索资源?

python - 从文本文件中获取一定长度的所有数字的好方法

python - 用 Python 抓取网站的第二页不起作用

适合初学者的 Python 追溯模块

node.js - 带有 node.js 的 GQL

google-cloud-platform - 使用云函数将数据加载到大查询表中,它正在附加到表中,我需要它来替换

java - Google Cloud 资源管理 Java Api 项目列表

Python:尝试使用刷新的凭据创建辅助日历时,googleapiclient 返回 "insufficient authentication scopes"