You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python CDK-v2:如何获取add_product()后台生成的关联对象?

AWS CDK v2 Python:获取ServiceCatalog add_product自动创建的关联对象

可以直接获取add_product()方法后台生成的PortfolioProductAssociation对象——调用该方法时,它本身就会返回对应的关联实例,你只需要把返回值保存下来即可直接引用。

解决示例代码

from aws_cdk import aws_servicecatalog as servicecatalog
from constructs import Construct
from aws_cdk import Stack

class MyServiceCatalogStack(Stack):
    def __init__(self, scope: Construct, construct_id: str, **kwargs) -> None:
        super().__init__(scope, construct_id, **kwargs)

        # 创建Portfolio和Product实例(示例)
        portfolio = servicecatalog.Portfolio(
            self, "MyPortfolio",
            display_name="My Portfolio",
            provider_name="My Org"
        )
        product = servicecatalog.CloudFormationProduct(
            self, "MyProduct",
            product_name="My CFN Product",
            owner="My Team",
            product_versions=[
                servicecatalog.CloudFormationProductVersion(
                    product_version_name="v1",
                    cloud_formation_template=servicecatalog.CloudFormationTemplate.from_product_stack(MyProductStack(self, "ProductStack"))
                )
            ]
        )

        # 调用add_product并保存返回的关联对象
        product_association = portfolio.add_product(product)

        # 创建现有角色的LaunchRoleConstraint,并添加依赖
        launch_role_constraint = servicecatalog.CfnLaunchRoleConstraint(
            self, "ExistingRoleLaunchConstraint",
            portfolio_id=portfolio.portfolio_id,
            product_id=product.product_id,
            role_arn="arn:aws:iam::123456789012:role/MyPreCreatedLaunchRole"
        )

        # 约束依赖于关联对象,避免ResourceNotFoundException
        launch_role_constraint.node.add_dependency(product_association)

补充说明

如果之前已经调用了add_product()但未保存返回值,也可以通过遍历Portfolio节点的子元素来查找对应的关联对象,但这种方式不够直观且容易出错,最可靠的方式是在调用add_product()时直接保存返回的关联实例。

内容的提问来源于stack exchange,提问作者ZabielskiGabriel

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:27:37