ROS CDK功能简介

本文为您介绍ROS CDK的相关功能。

参数

ROS支持使用参数(Parameters)提高模板的灵活性和可复用性,您可以通过以下代码在ROS CDK中设置参数。

关于参数(Parameters)的更多信息,请参见概览

TypeScript示例

import * as ros from '@alicloud/ros-cdk-core';
import * as ecs from '@alicloud/ros-cdk-ecs';

export class DemoStack extends ros.Stack {
    constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here

        const VpcCidrBlock = new ros.RosParameter(this, 'VpcCidrBlock', {
            description: 'The CIDR block of the VPC.',
            type: ros.RosParameterType.STRING,
            associationProperty: ros.RosParameter.AssociationProperty.VPC_CIDR_BLOCK
        });
        
        const VSwitchCidrBlock = new ros.RosParameter(this, 'VSwitchCidrBlock', {
            description: 'The CIDR block of the VSwitch.',
            type: ros.RosParameterType.STRING,
            associationProperty: ros.RosParameter.AssociationProperty.VSWITCH_CIDR_BLOCK
        });

        const ZoneId = new ros.RosParameter(this, 'ZoneId', {
            description: 'Availability Zone ID.',
            type: ros.RosParameterType.STRING,
            associationProperty: ros.RosParameter.AssociationProperty.ZONE_ID
        });

        const Vpc = new ecs.Vpc(this, 'vpc', {
            cidrBlock: VpcCidrBlock,
            vpcName: "demo001"
        });

        const VSwitch = new ecs.VSwitch(this, 'vswitch', {
            vpcId: Vpc.attrVpcId,
            cidrBlock: VSwitchCidrBlock,
            zoneId: ZoneId
        });
    }

Java示例

package com.myorg;

import com.aliyun.ros.cdk.core.*;

import com.aliyun.ros.cdk.ecs.*;

public class DemoStack extends Stack {
    public DemoStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public DemoStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // The code that defines your stack goes here
        RosParameter VpcCidrBlock = RosParameter.Builder.create(this, "VpcCidrBlock").
                description("The CIDR block of the VPC.").type(RosParameterType.STRING).
                associationProperty(RosParameter.AssociationProperty.VPC_CIDR_BLOCK).build();
        RosParameter VSwitchCidrBlock = RosParameter.Builder.create(this, "VSwitchCidrBlock").
                description("The CIDR block of the VSwitch.").type(RosParameterType.STRING).
                associationProperty(RosParameter.AssociationProperty.VSWITCH_CIDR_BLOCK).build();
        RosParameter ZoneId = RosParameter.Builder.create(this, "ZoneId").
                description("Availability Zone ID.").type(RosParameterType.STRING).
                associationProperty(RosParameter.AssociationProperty.ZONE_ID).build();
        Vpc vpc = Vpc.Builder.create(this, "vpc").vpcName("demo001").
                cidrBlock(VpcCidrBlock.getValue()).build();
        VSwitch vswitch = VSwitch.Builder.create(this, "vswitch").vpcId(vpc.getAttrVpcId()).
                cidrBlock(VSwitchCidrBlock.getValue()).zoneId(ZoneId.getValue()).build();
    }
}

Python示例

import ros_cdk_core as core
import ros_cdk_ecs as ecs


class DemoStack(core.Stack):

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

        # The code that defines your stack goes here
        vpc_cidr_block = core.RosParameter(self, "VpcCidrBlock", description="The CIDR block of the VPC.",
                                           type=core.RosParameterType.STRING,
                                           association_property=core.RosParameter.AssociationProperty.VPC_CIDR_BLOCK)

        vswitch_cidr_block = core.RosParameter(self, "VSwitchCidrBlock", description="The CIDR block of the VSwitch.",
                                               type=core.RosParameterType.STRING,
                                               association_property=core.RosParameter.AssociationProperty.VSWITCH_CIDR_BLOCK)

        zone_id = core.RosParameter(self, "ZoneId", description="Availability Zone ID.",
                                    type=core.RosParameterType.STRING,
                                    association_property=core.RosParameter.AssociationProperty.ZONE_ID)

        vpc = ecs.Vpc(self, "vpc", ecs.VPCProps(
            cidr_block=vpc_cidr_block,
            vpc_name="demo001"
        ))

        vswitch = ecs.VSwitch(self, "vswitch", ecs.VSwitchProps(
            cidr_block=vswitch_cidr_block,
            zone_id=zone_id,
            vpc_id=vpc.attr_vpc_id
        ))

C#示例

using AlibabaCloud.SDK.ROS.CDK.Core;
using AlibabaCloud.SDK.ROS.CDK.Ecs;

namespace Demo
{
    public class DemoStack : Stack
    {
        public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // The code that defines your stack goes here
            var VpcCidrBlock = new RosParameter(this, "VpcCidrBlock", new RosParameterProps
            {
                Description = "The CIDR block of the VPC.",
                Type = RosParameterType.STRING,
                AssociationProperty = RosParameter.AssociationProperty.VPC_CIDR_BLOCK
            });
            
            var VSwitchCidrBlock = new RosParameter(this, "VSwitchCidrBlock", new RosParameterProps
            {
                Description = "The CIDR block of the VSwitch.",
                Type = RosParameterType.STRING,
                AssociationProperty = RosParameter.AssociationProperty.VSWITCH_CIDR_BLOCK
            });
            
            var ZoneId = new RosParameter(this, "ZoneId", new RosParameterProps
            {
                Description = "Availability Zone ID.",
                Type = RosParameterType.STRING,
                AssociationProperty = RosParameter.AssociationProperty.ZONE_ID
            });

            var Vpc = new Vpc(this, "vpc", new VPCProps
            {
                CidrBlock = VpcCidrBlock.Value,
                VpcName = "demo001"
            });
            
            var VSwitch = new VSwitch(this, "vswitch", new VSwitchProps
            {
                CidrBlock = VSwitchCidrBlock.Value,
                ZoneId = ZoneId.Value,
                VpcId = Vpc.AttrVpcId
            });
        }
    }
}

您可以解析ROS CDK代码,生成如下ROS模板:

{
  "Description": "This is the simple ros cdk app example.",
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "TemplateTags": [
        "Create by ROS CDK"
      ]
    }
  },
  "ROSTemplateFormatVersion": "2015-09-01",
  "Parameters": {
    "VpcCidrBlock": {
      "Type": "String",
      "Description": "The CIDR block of the VPC.",
      "AssociationProperty": "ALIYUN::VPC::VPC::CidrBlock"
    },
    "VSwitchCidrBlock": {
      "Type": "String",
      "Description": "The CIDR block of the VSwitch.",
      "AssociationProperty": "ALIYUN::VPC::VSwitch::CidrBlock"
    },
    "ZoneId": {
      "Type": "String",
      "Description": "Availability Zone ID.",
      "AssociationProperty": "ZoneId"
    }
  },
  "Resources": {
    "vpc": {
      "Type": "ALIYUN::ECS::VPC",
      "Properties": {
        "CidrBlock": {
          "Ref": "VpcCidrBlock"
        },
        "EnableIpv6": false,
        "VpcName": "demo001"
      }
    },
    "vswitch": {
      "Type": "ALIYUN::ECS::VSwitch",
      "Properties": {
        "CidrBlock": {
          "Ref": "VSwitchCidrBlock"
        },
        "VpcId": {
          "Fn::GetAtt": [
            "vpc",
            "VpcId"
          ]
        },
        "ZoneId": {
          "Ref": "ZoneId"
        }
      }
    }
  }
}

资源

ROS支持为模板中的资源设置DependsOn、Count和Condition属性,具体如下:

  • DependsOn

    设置DependsOn属性,可以指定特定资源紧跟着另一个资源后创建。为某个资源添加DependsOn属性后,该资源仅在DependsOn属性中指定的资源之后创建。您可以通过以下代码在ROS CDK中设置DependsOn属性。

    TypeScript示例

    import * as ros from '@alicloud/ros-cdk-core';
    import * as ecs from '@alicloud/ros-cdk-ecs';
    
    export class DemoStack extends ros.Stack {
      constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here
        const vpc = new ecs.Vpc(this, 'ROS-VPC', {
          vpcName: 'VPC_Name',
          cidrBlock: '10.0.0.0/8',
          enableIpv6: false,
          description: 'This is the description of VPC',
        });
    
        const vswitch = new ecs.VSwitch(this, 'ROS-VSwitch', {
          vpcId: vpc.getAtt('VpcId'),
          zoneId: 'cn-beijing-h',
          vSwitchName: 'VSwitch_Name',
          cidrBlock: '10.0.0.0/20'
        });
    
        vswitch.addDependency(vpc);
      }
    }

    Java示例

    package com.myorg;
    
    import com.aliyun.ros.cdk.core.*;
    
    import com.aliyun.ros.cdk.ecs.*;
    
    public class DemoStack extends Stack {
        public DemoStack(final Construct scope, final String id) {
            this(scope, id, null);
        }
    
        public DemoStack(final Construct scope, final String id, final StackProps props) {
            super(scope, id, props);
    
            // The code that defines your stack goes here
            Vpc vpc = Vpc.Builder.create(this, "ROS-VPC").vpcName("VPC_Name").
                    description("This is the description of VPC").cidrBlock("10.0.0.0/8").enableIpv6(false).build();
            VSwitch vswitch = VSwitch.Builder.create(this, "ROS-VSwitch").vpcId(vpc.getAttrVpcId()).
                    cidrBlock("10.0.0.0/20").zoneId("cn-beijing-h").vSwitchName("VSwitch_Name").build();
            vswitch.addDependency(vpc);
        }
    }

    Python示例

    import ros_cdk_core as core
    import ros_cdk_ecs as ecs
    
    
    class DemoStack(core.Stack):
    
        def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
            super().__init__(scope, construct_id, **kwargs)
    
            # The code that defines your stack goes here
    
            vpc = ecs.Vpc(self, "ROS-VPC", ecs.VPCProps(
                cidr_block="10.0.0.0/8",
                vpc_name="VPC_Name",
                description="This is the description of VPC",
                enable_ipv6=False
            ))
    
            vswitch = ecs.VSwitch(self, "ROS-VSwitch", ecs.VSwitchProps(
                cidr_block="10.0.0.0/20",
                zone_id="cn-beijing-h",
                vpc_id=vpc.attr_vpc_id,
                v_switch_name="VSwitch_Name"
            ))
            vswitch.add_dependency(vpc)

    C#示例

    using AlibabaCloud.SDK.ROS.CDK.Core;
    using AlibabaCloud.SDK.ROS.CDK.Ecs;
    
    namespace Demo
    {
        public class DemoStack : Stack
        {
            public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
            {
                // The code that defines your stack goes here
    
                var Vpc = new Vpc(this, "ROS-VPC", new VPCProps
                {
                    CidrBlock = "10.0.0.0/8",
                    VpcName = "VPC_Name",
                    Description = "This is the description of VPC",
                    EnableIpv6 = false
                });
                
                var VSwitch = new VSwitch(this, "ROS-VSwitch", new VSwitchProps
                {
                    CidrBlock = "10.0.0.0/20",
                    ZoneId = "cn-beijing-h",
                    VpcId = Vpc.AttrVpcId,
                    VSwitchName = "VSwitch_Name"
                });
                VSwitch.AddDependency(Vpc);
            }
        }
    }

    您可以解析ROS CDK代码,生成如下ROS模板:

    {
      "Description": "This is the simple ros cdk app example.",
      "Metadata": {
        "ALIYUN::ROS::Interface": {
          "TemplateTags": [
            "Create by ROS CDK"
          ]
        }
      },
      "ROSTemplateFormatVersion": "2015-09-01",
      "Resources": {
        "ROS-VPC": {
          "Type": "ALIYUN::ECS::VPC",
          "Properties": {
            "CidrBlock": "10.0.0.0/8",
            "Description": "This is the description of VPC",
            "EnableIpv6": false,
            "VpcName": "VPC_Name"
          }
        },
        "ROS-VSwitch": {
          "Type": "ALIYUN::ECS::VSwitch",
          "Properties": {
            "CidrBlock": "10.0.0.0/20",
            "VpcId": {
              "Fn::GetAtt": [
                "ROS-VPC",
                "VpcId"
              ]
            },
            "ZoneId": "cn-beijing-h",
            "VSwitchName": "VSwitch_Name"
          },
          "DependsOn": [
            "ROS-VPC"
          ]
        }
      }
    }
  • Count

    为资源指定Count属性后,ROS会对模板进行预处理,把该资源展开成多个资源。 操作资源栈时使用处理后的模板。您可以通过以下代码在ROS CDK中设置Count属性。

    TypeScript示例

    import * as ros from '@alicloud/ros-cdk-core';
    import * as ecs from '@alicloud/ros-cdk-ecs';
    
    export class DemoStack extends ros.Stack {
        constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
            super(scope, id, props);
            new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
            // The code that defines your stack goes here
            const vpc = new ecs.Vpc(this, 'ROS-VPC', {
                cidrBlock: '10.0.0.0/8',
                enableIpv6: false,
            });
            vpc.addCount(2)
            const vsw =new ecs.VSwitch(this, `vsw-from-ros-cdk`, {
                vpcId: ros.Fn.select(ros.RosPseudo.index, vpc.attrVpcId),
                zoneId: ros.Fn.select(ros.RosPseudo.index, ros.Fn.getAzs(ros.RosPseudo.region)),
                cidrBlock: '10.0.0.0/16',
            });
            vsw.addCount(2)
        }
    }

    Java示例

    package com.myorg;
    
    import com.aliyun.ros.cdk.core.*;
    
    import com.aliyun.ros.cdk.ecs.*;
    
    public class DemoStack extends Stack {
        public DemoStack(final Construct scope, final String id) {
            this(scope, id, null);
        }
    
        public DemoStack(final Construct scope, final String id, final StackProps props) {
            super(scope, id, props);
    
            // The code that defines your stack goes here
            Vpc vpc = Vpc.Builder.create(this, "ROS-VPC").cidrBlock("10.0.0.0/8").enableIpv6(false).build();
            vpc.addCount(2);
            VSwitch vswitch = VSwitch.Builder.create(this, "vsw-from-ros-cdk").
                    vpcId(Fn.select(RosPseudo.getIndex(), vpc.getAttrVpcId())).
                    cidrBlock("10.0.0.0/16").
                    zoneId(Fn.select(RosPseudo.getIndex(), Fn.getAzs(RosPseudo.getRegion()))).build();
            vswitch.addCount(2);
        }
    }

    Python示例

    import ros_cdk_core as core
    import ros_cdk_ecs as ecs
    
    
    class DemoStack(core.Stack):
    
        def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
            super().__init__(scope, construct_id, **kwargs)
    
            # The code that defines your stack goes here
    
            vpc = ecs.Vpc(self, "ROS-VPC", ecs.VPCProps(
                cidr_block="10.0.0.0/8",
                enable_ipv6=False
            ))
            vpc.add_count(2)
            vswitch = ecs.VSwitch(self, "vsw-from-ros-cdk", ecs.VSwitchProps(
                cidr_block="10.0.0.0/16",
                zone_id=core.Fn.select(core.RosPseudo.index, core.Fn.get_azs(core.RosPseudo.region)),
                vpc_id=core.Fn.select(core.RosPseudo.index, vpc.attr_vpc_id)
            ))
            vswitch.add_count(2)

    C#示例

    using AlibabaCloud.SDK.ROS.CDK.Core;
    using AlibabaCloud.SDK.ROS.CDK.Ecs;
    
    namespace Demo
    {
        public class DemoStack : Stack
        {
            public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
            {
                // The code that defines your stack goes here
    
                var Vpc = new Vpc(this, "ROS-VPC", new VPCProps
                {
                    CidrBlock = "10.0.0.0/8",
                    EnableIpv6 = false
                });
                Vpc.AddCount(2);
                var VSwitch = new VSwitch(this, "vsw-from-ros-cdk", new VSwitchProps
                {
                    CidrBlock = "10.0.0.0/16",
                    ZoneId = Fn.Select(RosPseudo.Index, Fn.GetAzs(RosPseudo.Region)),
                    VpcId = Fn.Select(RosPseudo.Index, Vpc.AttrVpcId)
                });
                VSwitch.AddCount(2);
            }
        }
    }

    您可以解析ROS CDK代码,生成如下ROS模板:

    {
      "Description": "This is the simple ros cdk app example.",
      "Metadata": {
        "ALIYUN::ROS::Interface": {
          "TemplateTags": [
            "Create by ROS CDK"
          ]
        }
      },
      "ROSTemplateFormatVersion": "2015-09-01",
      "Resources": {
        "ROS-VPC": {
          "Type": "ALIYUN::ECS::VPC",
          "Properties": {
            "CidrBlock": "10.0.0.0/8",
            "EnableIpv6": false
          },
          "Count": 2
        },
        "vsw-from-ros-cdk": {
          "Type": "ALIYUN::ECS::VSwitch",
          "Properties": {
            "CidrBlock": "10.0.0.0/16",
            "VpcId": {
              "Fn::Select": [
                {
                  "Ref": "ALIYUN::Index"
                },
                {
                  "Fn::GetAtt": [
                    "ROS-VPC",
                    "VpcId"
                  ]
                }
              ]
            },
            "ZoneId": {
              "Fn::Select": [
                {
                  "Ref": "ALIYUN::Index"
                },
                {
                  "Fn::GetAZs": {
                    "Ref": "ALIYUN::Region"
                  }
                }
              ]
            }
          },
          "Count": 2
        }
      }
    }
  • Condition

    使用Condition属性可以指定是否需要创建资源。只有Condition所指定的条件值为True时,才会创建此资源。您可以通过以下代码在ROS CDK中设置Condition属性。

    TypeScript示例

    import * as ros from '@alicloud/ros-cdk-core';
    import * as ecs from '@alicloud/ros-cdk-ecs';
    
    export class DemoStack extends ros.Stack {
        constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
            super(scope, id, props);
            new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
            // The code that defines your stack goes here
            const createVPC = new ros.RosParameter(this, 'CreateVPC', {
                type: ros.RosParameterType.BOOLEAN,
                defaultValue: true,
            });
    
            const isCreateVPC = new ros.RosCondition(this, 'IsCreateVPC', {
                expression: ros.Fn.conditionEquals(true, createVPC.valueAsBoolean),
            });
            const vpc = new ecs.Vpc(this, 'ROS-VPC', {
                vpcName: 'VPC_Name',
                cidrBlock: '10.0.0.0/8',
                enableIpv6: false,
                description: 'This is the description of VPC',
            });
            vpc.addCondition(isCreateVPC)
        }
    }

    Java示例

    package com.myorg;
    
    import com.aliyun.ros.cdk.core.*;
    
    import com.aliyun.ros.cdk.ecs.*;
    
    public class DemoStack extends Stack {
        public DemoStack(final Construct scope, final String id) {
            this(scope, id, null);
        }
    
        public DemoStack(final Construct scope, final String id, final StackProps props) {
            super(scope, id, props);
    
            // The code that defines your stack goes here
            RosParameter CreateVpc = RosParameter.Builder.create(this, "CreateVpc")
                    .type(RosParameterType.BOOLEAN).
                    defaultValue(true).build();
            RosCondition IsCreateVpc = RosCondition.Builder.create(this, "IsCreateVpc").expression(Fn.conditionEquals(true, CreateVpc.getValueAsBoolean())).build();
            Vpc vpc = Vpc.Builder.create(this, "ROS-VPC").vpcName("VPC_Name").description("This is the description of VPC").
                    cidrBlock("10.0.0.0/8").enableIpv6(false).build();
            vpc.addCondition(IsCreateVpc);
        }
    }

    Python示例

    import ros_cdk_core as core
    import ros_cdk_ecs as ecs
    
    
    class DemoStack(core.Stack):
    
        def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
            super().__init__(scope, construct_id, **kwargs)
    
            # The code that defines your stack goes here
            create_vpc = core.RosParameter(self, "CreateVPC",
                                           type=core.RosParameterType.BOOLEAN,
                                           default_value=True)
            is_create_vpc = core.RosCondition(self, "IsCreateVPC",
                                              expression=core.Fn.condition_equals(True, create_vpc.value_as_boolean))
            vpc = ecs.Vpc(self, "ROS-VPC", ecs.VPCProps(
                cidr_block="10.0.0.0/8",
                vpc_name="VPC_Name",
                description="This is the description of VPC",
                enable_ipv6=False
            ))
            vpc.add_condition(is_create_vpc)

    C#示例

    using AlibabaCloud.SDK.ROS.CDK.Core;
    using AlibabaCloud.SDK.ROS.CDK.Ecs;
    
    namespace Demo
    {
        public class DemoStack : Stack
        {
            public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
            {
                // The code that defines your stack goes here
                
                var CreateVpc = new RosParameter(this, "CreateVpc", new RosParameterProps
                {
                    Type = RosParameterType.BOOLEAN,
                    DefaultValue = true
                });
    
                var IsCreateVpc = new RosCondition(this, "IsCreateVpc", new RosConditionProps
                {
                    Expression = Fn.ConditionEquals(true, CreateVpc.ValueAsBoolean)
                });
    
                var Vpc = new Vpc(this, "ROS-VPC", new VPCProps
                {
                    CidrBlock = "10.0.0.0/8",
                    EnableIpv6 = false,
                    Description = "This is the description of VPC",
                    VpcName = "VPC_Name"
                });
                Vpc.AddCondition(IsCreateVpc);
            }
        }
    }

    您可以解析ROS CDK代码,生成如下ROS模板:

    {
      "Description": "This is the simple ros cdk app example.",
      "Metadata": {
        "ALIYUN::ROS::Interface": {
          "TemplateTags": [
            "Create by ROS CDK"
          ]
        }
      },
      "ROSTemplateFormatVersion": "2015-09-01",
      "Parameters": {
        "CreateVPC": {
          "Type": "Boolean",
          "Default": true
        }
      },
      "Conditions": {
        "IsCreateVPC": {
          "Fn::Equals": [
            true,
            {
              "Ref": "CreateVPC"
            }
          ]
        }
      },
      "Resources": {
        "ROS-VPC": {
          "Type": "ALIYUN::ECS::VPC",
          "Properties": {
            "CidrBlock": "10.0.0.0/8",
            "Description": "This is the description of VPC",
            "EnableIpv6": false,
            "VpcName": "VPC_Name"
          },
          "Condition": "IsCreateVPC"
        }
      }
    }
  • 获取资源属性

    ROS CDK支持获取资源属性,并支持使用内部函数ref获取指定资源的值,如下以多种开发语言示例展示。

    TypeScript示例

    import * as ros from '@alicloud/ros-cdk-core';
    import * as ecs from '@alicloud/ros-cdk-ecs';
    
    export class DemoStack extends ros.Stack {
      constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here
        const vpc = new ecs.Vpc(this, 'vpc-from-ros-cdk', {
          vpcName: 'test-ros-cdk',
          cidrBlock: '10.0.0.0/8',
          description: 'This is ros cdk test'
        });
        const vsw1 = new ecs.VSwitch(this, 'vsw-from-ros-cdk-1', {
          cidrBlock: '10.0.1.0/16',
          zoneId: 'cn-beijing-g',
          vpcId: ros.Token.asString(vpc?.ref)
        });
        const vsw2 = new ecs.VSwitch(this, 'vsw-from-ros-cdk-2', {
          cidrBlock: '10.0.2.0/16',
          zoneId: 'cn-beijing-h',
          vpcId: vpc.attrVpcId
        });
      }
    }
    

    Java示例

    package com.myorg;
    
    import com.aliyun.ros.cdk.core.*;
    import com.aliyun.ros.cdk.ecs.Vpc;
    import com.aliyun.ros.cdk.ecs.VSwitch;
    
    public class DemoStack extends Stack {
        public DemoStack(final Construct scope, final String id) {
            this(scope, id, null);
        }
    
        public DemoStack(final Construct scope, final String id, final StackProps props) {
            super(scope, id, props);
    
            // The code that defines your stack goes here
    
            Vpc vpc1 = Vpc.Builder.create(this, "vpc-from-ros-cdk").vpcName("test-ros-cdk").description("This is ros cdk test").
                    cidrBlock("10.0.0.0/8").build();
    
            VSwitch vsw1 = VSwitch.Builder.create(this, "vsw-from-ros-cdk-1").vpcId(vpc1.getRef()).zoneId("cn-beijing-g").
                    cidrBlock("10.0.1.0/16").build();
            VSwitch vsw2 = VSwitch.Builder.create(this, "vsw-from-ros-cdk-2").vpcId(vpc1.getAttrVpcId()).zoneId("cn-beijing-h").
                    cidrBlock("10.0.2.0/16").build();
        }
    }
    

    Python示例

    import ros_cdk_core as core
    import ros_cdk_ecs as ecs
    
    
    class DemoStack(core.Stack):
    
        def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
            super().__init__(scope, construct_id, **kwargs)
    
            # The code that defines your stack goes here
            vpc = ecs.Vpc(self, "vpc-from-ros-cdk", ecs.VPCProps(
                cidr_block='10.0.0.0/8',
                vpc_name='test-ros-cdk',
                description='This is ros cdk test'
            ))
    
            vsw1 = ecs.VSwitch(self, "vsw-from-ros-cdk-1", ecs.VSwitchProps(
                cidr_block='10.0.1.0/16',
                vpc_id=vpc.ref,
                zone_id='cn-beijing-g'
            ))
    
            vsw2 = ecs.VSwitch(self, "vsw-from-ros-cdk-2", ecs.VSwitchProps(
                cidr_block='10.0.2.0/16',
                vpc_id=vpc.attr_vpc_id,
                zone_id='cn-beijing-h'
            ))
    

    C#示例

    using AlibabaCloud.SDK.ROS.CDK.Core;
    using AlibabaCloud.SDK.ROS.CDK.Ecs;
    
    namespace Demo
    {
        public class DemoStack : Stack
        {
            public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
            {
                var vpc = new Vpc(this, "vpc-from-ros-cdk", new VPCProps
                {
                    VpcName = "test-ros-cdk",
                    CidrBlock = "10.0.0.0/8",
                    Description = "This is ros cdk test"
                });
                var vsw1 = new VSwitch(this, "vsw-from-ros-cdk-1", new VSwitchProps
                    {
                        VpcId = vpc.Ref,
                        CidrBlock = "10.0.1.0/16",
                        ZoneId = "cn-beijing-g"
                    }
                );
                var vsw2 = new VSwitch(this, "vsw-from-ros-cdk-2", new VSwitchProps
                    {
                        VpcId = vpc.AttrVpcId,
                        CidrBlock = "10.0.2.0/16",
                        ZoneId = "cn-beijing-h"
                    }
                );
            }
        }
    }

    您可以解析ROS CDK代码,生成如下ROS模板:

    {
      "Description": "This is the simple ros cdk app example.",
      "Metadata": {
        "ALIYUN::ROS::Interface": {
          "TemplateTags": [
            "Create by ROS CDK"
          ]
        }
      },
      "ROSTemplateFormatVersion": "2015-09-01",
      "Resources": {
        "vpc-from-ros-cdk": {
          "Type": "ALIYUN::ECS::VPC",
          "Properties": {
            "CidrBlock": "10.0.0.0/8",
            "Description": "This is ros cdk test",
            "EnableIpv6": false,
            "VpcName": "test-ros-cdk"
          }
        },
        "vsw-from-ros-cdk-1": {
          "Type": "ALIYUN::ECS::VSwitch",
          "Properties": {
            "CidrBlock": "10.0.1.0/16",
            "VpcId": {
              "Ref": "vpc-from-ros-cdk"
            },
            "ZoneId": "cn-beijing-g"
          }
        },
        "vsw-from-ros-cdk-2": {
          "Type": "ALIYUN::ECS::VSwitch",
          "Properties": {
            "CidrBlock": "10.0.2.0/16",
            "VpcId": {
              "Fn::GetAtt": [
                "vpc-from-ros-cdk",
                "VpcId"
              ]
            },
            "ZoneId": "cn-beijing-h"
          }
        }
      }
    }
  • DataSource资源

    ROS CDK支持使用DataSource资源类型查询对应资源需要使用的资源信息,如下以多种开发语言示例展示。

    TypeScript示例

    import * as ros from '@alicloud/ros-cdk-core';
    import * as vpc from '@alicloud/ros-cdk-vpc';
    
    export class DemoStack extends ros.Stack {
      constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here
        const eip = new vpc.Eip(this, 'eip-from-ros-cdk' ,{
          name: 'demo001'
        })
        const eips = new vpc.datasource.Addresses(this, 'ds-eip-from-ros-cdk',{
          ipAddress: eip.attrEipAddress
        })
        const eipAddresses = new ros.RosOutput(this, 'eipAddresses', {
          value:  eips.attrAddresses,
          description: 'eipAddresses',
        });
        const eipStatus = new ros.RosOutput(this, 'eipStatus', {
          value: ros.Fn.getJsonValue('Status', ros.Fn.select(0, eips.attrAddresses)),
          description: 'eipStatus',
        });
      }
    }

    Java示例

    package com.myorg;
    
    import com.aliyun.ros.cdk.core.*;
    import com.aliyun.ros.cdk.vpc.Eip;
    import com.aliyun.ros.cdk.vpc.datasource.Addresses;
    
    
    public class DemoStack extends Stack {
        public DemoStack(final Construct scope, final String id) {
            this(scope, id, null);
        }
    
        public DemoStack(final Construct scope, final String id, final StackProps props) {
            super(scope, id, props);
    
            // The code that defines your stack goes here
    
            Eip eip1 = Eip.Builder.create(this, "Eip").name("demo001").build();
    
    
            Addresses eipAddresses = Addresses.Builder.create(this,"DataSourceAddresses").ipAddress(eip1.getAttrEipAddress()).build();
    
            RosOutput.Builder.create(this,"EipAddresses").value(eipAddresses.getAttrAddresses()).build();
            RosOutput.Builder.create(this,"EipStatus").value(Fn.getJsonValue("Status", Fn.select(0,eipAddresses.getAttrAddresses()))).build();
        }
    }

    Python示例

    import ros_cdk_core as core
    import ros_cdk_vpc as vpc
    
    
    class DemoStack(core.Stack):
    
        def __init__(self, scope: core.Construct, construct_id: str, **kwargs) -> None:
            super().__init__(scope, construct_id, **kwargs)
    
            # The code that defines your stack goes here
    
            eip1 = vpc.Eip(self, "Eip", vpc.EIPProps(
                name="demo001"
            ))
    
            ds_eip = vpc.datasource.Addresses(self, "ds_eip", vpc.datasource.AddressesProps(
                ip_address=eip1.attr_eip_address
            ))
    
            core.RosOutput(self, "eips_addresses", value=ds_eip.attr_addresses)
            core.RosOutput(self, "eip_status",
                           value=core.Fn.get_json_value('Status', core.Fn.select(0, ds_eip.attr_addresses)))
    

    C#示例

    using AlibabaCloud.SDK.ROS.CDK.Core;
    using AlibabaCloud.SDK.ROS.CDK.Vpc;
    using AlibabaCloud.SDK.ROS.CDK.Vpc.Datasource;
    
    namespace Demo
    {
        public class DemoStack : Stack
        {
            public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
            {
    
                var Eip = new Eip(this, "eip-from-ros-cdk", new EIPProps
                {
                    Name = "demo003"
                });
    
                var DataSourceEip = new Addresses(this, "ds-eip-from-ros-cdk", new AddressesProps
                {
                    IpAddress = Eip.AttrEipAddress
                });
                new RosOutput(this, "EipsAddresses", new RosOutputProps
                {
                    Value = DataSourceEip.AttrAddresses
                });
                new RosOutput(this, "EipStatus", new RosOutputProps
                {
                    Value = Fn.GetJsonValue("Status", Fn.Select(0, DataSourceEip.AttrAddresses))
                });
            }
        }
    }

    您可以解析ROS CDK代码,生成如下ROS模板:

    {
      "Description": "This is the simple ros cdk app example.",
      "Metadata": {
        "ALIYUN::ROS::Interface": {
          "TemplateTags": [
            "Create by ROS CDK"
          ]
        }
      },
      "ROSTemplateFormatVersion": "2015-09-01",
      "Resources": {
        "eip-from-ros-cdk": {
          "Type": "ALIYUN::VPC::EIP",
          "Properties": {
            "AutoPay": true,
            "Bandwidth": 5,
            "DeletionProtection": false,
            "InstanceChargeType": "Postpaid",
            "InternetChargeType": "PayByBandwidth",
            "Name": "demo001",
            "Period": 1,
            "PricingCycle": "Month"
          }
        },
        "ds-eip-from-ros-cdk": {
          "Type": "DATASOURCE::EIP::Addresses",
          "Properties": {
            "IpAddress": {
              "Fn::GetAtt": [
                "eip-from-ros-cdk",
                "EipAddress"
              ]
            }
          }
        }
      },
      "Outputs": {
        "eipAddresses": {
          "Description": "eipAddresses",
          "Value": {
            "Fn::GetAtt": [
              "ds-eip-from-ros-cdk",
              "Addresses"
            ]
          }
        },
        "eipStatus": {
          "Description": "eipStatus",
          "Value": {
            "Fn::GetJsonValue": [
              "Status",
              {
                "Fn::Select": [
                  0,
                  {
                    "Fn::GetAtt": [
                      "ds-eip-from-ros-cdk",
                      "Addresses"
                    ]
                  }
                ]
              }
            ]
          }
        }
      }
    }

函数

ROS支持使用函数(Functions)管理资源栈,您可以通过以下代码在ROS CDK中设置函数。

关于函数(Functions)的更多信息,请参见函数(Functions)

TypeScript示例

import * as ros from '@alicloud/ros-cdk-core';
import * as ecs from '@alicloud/ros-cdk-ecs';

export class DemoStack extends ros.Stack {
    constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here
        const vpcName = new ros.RosParameter(this, 'VpcName', {
            type: ros.RosParameterType.STRING,
            defaultValue:"VPC1,VPC2,VPC3"
        });
        const vswName = new ros.RosParameter(this, 'VSWName', {
            type: ros.RosParameterType.JSON,
            defaultValue: {"VSWName": "VSW1"}
        });
        const vpc = new ecs.Vpc(this, 'ROS-VPC', {
            vpcName: ros.Fn.select(0, ros.Fn.split(',', vpcName.valueAsString)),
            cidrBlock: '10.0.0.0/8',
            enableIpv6: false,
            description: 'This is the description of VPC',
        });
        const vswitch = new ecs.VSwitch(this, 'ROS-VSwitch', {
            vpcId: vpc.getAtt('VpcId'),
            vSwitchName: ros.Fn.getJsonValue('VSWName', vswName.valueAsAny),
            cidrBlock: '10.0.0.0/20',
            zoneId: ros.Fn.select(0, ros.Fn.getAzs(ros.Fn.ref('ALIYUN::Region'))),
        });
        vswitch.addDependency(vpc);
        const SubResultOutput = new ros.RosOutput(this, 'result', {
            value: ros.Fn.sub('Var1: ${Var1}, Var2: ${Var2}, StackName: ${ALIYUN::StackName}, Region: ${ALIYUN::Region}', {
                Var1: 'Var1Value',
                Var2: 'Var2Value',
            }),
            description: 'test Sub function result',
        });
        const maxResultOutput = new ros.RosOutput(this, 'maxVal', {
            value: ros.Fn.max([1, 777]),
            description: 'test max function',
        });

        const minResultOutput = new ros.RosOutput(this, 'minVal', {
            value: ros.Fn.min([1, 777]),
            description: 'test min function',
        });
        const addResultOutput = new ros.RosOutput(this, 'testFunction1', {
            value: ros.Fn.add([3.14, 8.4]),
            description: 'number type add',
        });
    }
}

Java示例

package com.myorg;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.aliyun.ros.cdk.core.*;

import com.aliyun.ros.cdk.ecs.*;

import java.util.HashMap;
import java.util.List;
import java.util.Arrays;

public class DemoStack extends Stack {
    public DemoStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public DemoStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // The code that defines your stack goes here
        ObjectNode VSWNameValue = new ObjectMapper().createObjectNode();
        VSWNameValue.put("VSWName", "VSW1");

        HashMap<String, Object> ResultOutputJson = new HashMap<>();
        ResultOutputJson.put("Var1", "Var1Value");
        ResultOutputJson.put("Var2", "Var2Value");
        List<Number> list1 = Arrays.asList(1, 777);
        List<Number> list2 = Arrays.asList(3.14, 8.4);
        RosParameter VpcName = RosParameter.Builder.create(this, "VpcName").type(RosParameterType.STRING).
                defaultValue("VPC1,VPC2,VPC3").build();
        RosParameter VSWName = RosParameter.Builder.create(this, "VSWName").type(RosParameterType.JSON).
                defaultValue(VSWNameValue).build();
        Vpc vpc = Vpc.Builder.create(this, "ROS-VPC").vpcName(Fn.select(0, Fn.split(",", VpcName.getValueAsString()))).
                cidrBlock("10.0.0.0/8").enableIpv6(false).description("This is the description of VPC").build();
        VSwitch vswitch = VSwitch.Builder.create(this, "ROS-VSwitch").vpcId(vpc.getAttrVpcId()).vSwitchName(Fn.getJsonValue("VSWName", VSWName.getValueAsAny())).
                cidrBlock("10.0.0.0/20").zoneId(Fn.select(0, Fn.getAzs(Fn.ref("ALIYUN::Region")))).build();
        vswitch.addDependency(vpc);
        RosOutput SubResultOutput = RosOutput.Builder.create(this, "result").value(
                Fn.sub("Var1: ${Var1}, Var2: ${Var2}, StackName: ${ALIYUN::StackName}, Region: ${ALIYUN::Region}", ResultOutputJson)
        ).description("test Sub function result").build();

        RosOutput MaxResultOutput = RosOutput.Builder.create(this, "maxVal").value(Fn.max(list1)).description("test max function").build();
        RosOutput MinResultOutput = RosOutput.Builder.create(this, "minVal").value(Fn.min(list1)).description("test min function").build();
        RosOutput AddResultOutput = RosOutput.Builder.create(this, "testFunction1").value(Fn.add(list2)).description("number type add").build();
    }
}

Python示例

import ros_cdk_core as core
import ros_cdk_ecs as ecs


class DemoStack(core.Stack):

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

        # The code that defines your stack goes here
        vpc_name = core.RosParameter(self, "VpcName",
                                     type=core.RosParameterType.STRING,
                                     default_value="VPC1,VPC2,VPC3")
        vsw_name = core.RosParameter(self, "VSWName",
                                     type=core.RosParameterType.JSON,
                                     default_value={"VSWName": "VSW1"})
        vpc = ecs.Vpc(self, "ROS-VPC", ecs.VPCProps(
            cidr_block="10.0.0.0/8",
            vpc_name=core.Fn.select(0, core.Fn.split(',', vpc_name.value_as_string)),
            description="This is the description of VPC",
            enable_ipv6=False
        ))

        vswitch = ecs.VSwitch(self, "ROS-VSwitch", ecs.VSwitchProps(
            cidr_block="10.0.0.0/20",
            v_switch_name=core.Fn.get_json_value('VSWName', vsw_name.value_as_any),
            vpc_id=vpc.attr_vpc_id,
            zone_id=core.Fn.select(0, core.Fn.get_azs(core.Fn.ref('ALIYUN::Region')))
        ))
        vswitch.add_dependency(vpc)
        sub_result_output = core.RosOutput(self, "result", value=core.Fn.sub(
            "Var1: ${Var1}, Var2: ${Var2}, StackName: ${ALIYUN::StackName}, Region: ${ALIYUN::Region}", {
                "Var1": "Var1Value",
                "Var2": "Var2Value"
            }), description="test Sub function result")
        max_result_output = core.RosOutput(self, "maxVal", value=core.Fn.max([1.777]), description="test max function")
        min_result_output = core.RosOutput(self, "minVal", value=core.Fn.min([1, 777]), description="test min function")
        add_result_output = core.RosOutput(self, "testFunction1", value=core.Fn.add([3.14, 8.4]),
                                           description="number type add")

C#示例

using AlibabaCloud.SDK.ROS.CDK.Core;
using AlibabaCloud.SDK.ROS.CDK.Ecs;
using Newtonsoft.Json.Linq;
using System.Collections.Generic;
namespace Demo
{
    public class DemoStack : Stack
    {
        public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // The code that defines your stack goes here
            
            JObject VSWNameObj = new JObject();
            VSWNameObj.Add("VSWName", "VSW1");
            
            Dictionary<string, object> ResultOutputObj = new Dictionary<string, object>();
            ResultOutputObj.Add("Var1", "Var1Value");
            ResultOutputObj.Add("Var2", "Var2Value");

            double[] maxAndMinOutputArray = new double[2] {1, 777};

            object[] testFunction1Array = new object[2] {3.14, 8.4};

            var VpcName = new RosParameter(this, "VpcName", new RosParameterProps
            {
                Type = RosParameterType.STRING,
                DefaultValue = "VPC1,VPC2,VPC3"
            });
            
            var VSWName = new RosParameter(this, "VSWName", new RosParameterProps
            {
                Type = RosParameterType.JSON,
                DefaultValue = VSWNameObj
            });

            var Vpc = new Vpc(this, "ROS-VPC", new VPCProps
            {
                CidrBlock = "10.0.0.0/8",
                VpcName = Fn.Select(0, Fn.Split(",", VpcName.ValueAsString)),
                Description = "This is the description of VPC",
                EnableIpv6 = false
            });
            
            var VSwitch = new VSwitch(this, "ROS-VSwitch", new VSwitchProps
            {
                CidrBlock = "10.0.0.0/20",
                ZoneId = Fn.Select(0, Fn.GetAzs(Fn.Ref("ALIYUN::Region"))),
                VpcId = Vpc.AttrVpcId,
                VSwitchName = Fn.GetJsonValue("VSWName", VSWName.ValueAsAny)
            });
            VSwitch.AddDependency(Vpc);
            var SubResultOutput = new RosOutput(this, "result", new RosOutputProps
            {
                Value = Fn.Sub("Var1: ${Var1}, Var2: ${Var2}, StackName: ${ALIYUN::StackName}, Region: ${ALIYUN::Region}", ResultOutputObj),
                Description = "test Sub function result"
            });
            var maxResultOutput = new RosOutput(this, "maxVal" ,new RosOutputProps
            {
                Value = Fn.Max(maxAndMinOutputArray),
                Description = "test max function"
            });
            var minResultOutput = new RosOutput(this, "minVal" ,new RosOutputProps
            {
                Value = Fn.Min(maxAndMinOutputArray),
                Description = "test min function"
            });
            var addResultOutput = new RosOutput(this, "testFunction1" ,new RosOutputProps
            {
                Value = Fn.Add(testFunction1Array),
                Description = "number type add"
            });
        }
    }
}

您可以解析ROS CDK代码,生成如下ROS模板:

{
  "Description": "This is the simple ros cdk app example.",
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "TemplateTags": [
        "Create by ROS CDK"
      ]
    }
  },
  "ROSTemplateFormatVersion": "2015-09-01",
  "Parameters": {
    "VpcName": {
      "Type": "String",
      "Default": "VPC1,VPC2,VPC3"
    },
    "VSWName": {
      "Type": "Json",
      "Default": {
        "VSWName": "VSW1"
      }
    }
  },
  "Resources": {
    "ROS-VPC": {
      "Type": "ALIYUN::ECS::VPC",
      "Properties": {
        "CidrBlock": "10.0.0.0/8",
        "Description": "This is the description of VPC",
        "EnableIpv6": false,
        "VpcName": {
          "Fn::Select": [
            0,
            {
              "Fn::Split": [
                ",",
                {
                  "Ref": "VpcName"
                }
              ]
            }
          ]
        }
      }
    },
    "ROS-VSwitch": {
      "Type": "ALIYUN::ECS::VSwitch",
      "Properties": {
        "CidrBlock": "10.0.0.0/20",
        "VpcId": {
          "Fn::GetAtt": [
            "ROS-VPC",
            "VpcId"
          ]
        },
        "ZoneId": {
          "Fn::Select": [
            0,
            {
              "Fn::GetAZs": {
                "Ref": "ALIYUN::Region"
              }
            }
          ]
        },
        "VSwitchName": {
          "Fn::GetJsonValue": [
            "VSWName",
            {
              "Ref": "VSWName"
            }
          ]
        }
      },
      "DependsOn": [
        "ROS-VPC"
      ]
    }
  },
  "Outputs": {
    "result": {
      "Description": "test Sub function result",
      "Value": {
        "Fn::Sub": [
          "Var1: ${Var1}, Var2: ${Var2}, StackName: ${ALIYUN::StackName}, Region: ${ALIYUN::Region}",
          {
            "Var1": "Var1Value",
            "Var2": "Var2Value"
          }
        ]
      }
    },
    "maxVal": {
      "Description": "test max function",
      "Value": {
        "Fn::Max": [
          1,
          777
        ]
      }
    },
    "minVal": {
      "Description": "test min function",
      "Value": {
        "Fn::Min": [
          1,
          777
        ]
      }
    },
    "testFunction1": {
      "Description": "number type add",
      "Value": {
        "Fn::Add": [
          3.14,
          8.4
        ]
      }
    }
  }
}

条件

ROS支持在模板中定义条件(Conditions),根据您在创建或更新资源栈时,指定的输入参数值进行计算。在每个条件中,都可以引用其他条件、参数值或映射。您可以通过以下代码在ROS CDK中设置条件。

关于条件(Conditions)的更多信息,请参见条件(Conditions)

TypeScript示例

import * as ros from '@alicloud/ros-cdk-core';
import * as rds from '@alicloud/ros-cdk-rds';

export class DemoStack extends ros.Stack {
    constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here
        const rdsDBInstanceEngineType = new ros.RosParameter(this, 'RdsDBInstanceEngineType', {
            type: ros.RosParameterType.STRING,
            defaultValue: 'sqlserver',
            allowedValues: [
                'sqlserver',
                'mysql'
            ]
        });

        const rdsDBInstanceId = new ros.RosParameter(this, 'RdsDBInstanceId', {
            type: ros.RosParameterType.STRING,
        });

        const rdsDBName = new ros.RosParameter(this, 'RdsDBName', {
            type: ros.RosParameterType.STRING,
        });

        const rdsEngineTypeConditions = new ros.RosCondition(this, 'RdsEngineTypeConditions', {
            expression: ros.Fn.conditionEquals('mysql', rdsDBInstanceEngineType.valueAsString),
        });
        const rdsDataBase = new rds.Database(this, 'Database', {
            dbInstanceId: rdsDBInstanceId.valueAsString,
            dbName: rdsDBName.valueAsString,
            characterSetName: ros.Fn.conditionIf(rdsEngineTypeConditions.node.id, 'utf8', 'Chinese_PRC_CI_AS')
        })
    }
}

Java示例

package com.myorg;

import com.aliyun.ros.cdk.core.*;

import com.aliyun.ros.cdk.rds.*;

import java.util.Arrays;
import java.util.List;

public class DemoStack extends Stack {
    public DemoStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public DemoStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // The code that defines your stack goes here
        List<String> list1 = Arrays.asList("sqlserver", "mysql");
        RosParameter rdsDBInstanceEngineType = RosParameter.Builder.create(this, "RdsDBInstanceEngineType")
                .type(RosParameterType.STRING).
                defaultValue("sqlserver").allowedValues(list1).build();
        RosParameter rdsDBInstanceId = RosParameter.Builder.create(this, "RdsDBInstanceId")
                .type(RosParameterType.STRING).build();
        RosParameter rdsDBName = RosParameter.Builder.create(this, "RdsDBName")
                .type(RosParameterType.STRING).build();
        RosCondition rdsEngineTypeConditions = RosCondition.Builder.create(this, "RdsEngineTypeConditions").expression(Fn.conditionEquals("mysql", rdsDBInstanceEngineType.getValueAsString())).build();
        Database rdsDataBase = Database.Builder.create(this, "Database").dbName(rdsDBName.getValueAsString()).dbInstanceId(rdsDBInstanceId.getValueAsString()).characterSetName(Fn.conditionIf(rdsEngineTypeConditions.getNode().getId(), "utf8", "Chinese_PRC_CI_AS").toString()).build();
    }
}

Python示例

import ros_cdk_core as core
import ros_cdk_rds as rds


class DemoStack(core.Stack):

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

        # The code that defines your stack goes here
        rds_db_instance_engine_type = core.RosParameter(self, "RdsDBInstanceEngineType",
                                                        type=core.RosParameterType.STRING,
                                                        default_value="sqlserver",
                                                        allowed_values=["sqlserver", "mysql"])
        rds_db_instance_id = core.RosParameter(self, "RdsDBInstanceId",
                                               type=core.RosParameterType.STRING)
        rds_db_name = core.RosParameter(self, "RdsDBName",
                                        type=core.RosParameterType.STRING)
        rds_engine_type_conditions = core.RosCondition(self, "RdsEngineTypeConditions",
                          expression=core.Fn.condition_equals("mysql", rds_db_instance_engine_type.value_as_string))
        database = rds.Database(self, "Database", rds.DatabaseProps(
            db_name=rds_db_name.value_as_string,
            db_instance_id=rds_db_instance_id.value_as_string,
            character_set_name=core.Fn.condition_if(rds_engine_type_conditions.node.id, "utf8", "Chinese_PRC_CI_AS")
        ))

C#示例

using AlibabaCloud.SDK.ROS.CDK.Core;
using AlibabaCloud.SDK.ROS.CDK.Rds;
namespace Demo
{
    public class DemoStack : Stack
    {
        public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // The code that defines your stack goes here
            
            object[] RdsDBInstanceEngineTypeArray = new object[2] {"sqlserver", "mysql"};
            
            var rdsDBInstanceEngineType = new RosParameter(this, "RdsDBInstanceEngineType", new RosParameterProps
            {
                Type = RosParameterType.STRING,
                DefaultValue = "sqlserver",
                AllowedValues = RdsDBInstanceEngineTypeArray
            });

            var rdsDBInstanceId = new RosParameter(this, "RdsDBInstanceId", new RosParameterProps
            {
                Type = RosParameterType.STRING
            });
            
            var rdsDBName = new RosParameter(this, "RdsDBName", new RosParameterProps
            {
                Type = RosParameterType.STRING
            });
            
            
            var rdsEngineTypeConditions = new RosCondition(this, "RdsEngineTypeConditions", new RosConditionProps
            {
                Expression = Fn.ConditionEquals("mysql", rdsDBInstanceEngineType.ValueAsString)
            });
            var Database = new Database(this, "Database", new DatabaseProps
            {
                DbName = rdsDBName.ValueAsString,
                DbInstanceId = rdsDBInstanceId.ValueAsString,
                CharacterSetName = Fn.ConditionIf(rdsEngineTypeConditions.Node.Id, "utf8", "Chinese_PRC_CI_AS")
            });
        }
    }
}

您可以解析ROS CDK代码,生成如下ROS模板:

{
  "Description": "This is the simple ros cdk app example.",
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "TemplateTags": [
        "Create by ROS CDK"
      ]
    }
  },
  "ROSTemplateFormatVersion": "2015-09-01",
  "Parameters": {
    "RdsDBInstanceEngineType": {
      "Type": "String",
      "Default": "sqlserver",
      "AllowedValues": [
        "sqlserver",
        "mysql"
      ]
    },
    "RdsDBInstanceId": {
      "Type": "String"
    },
    "RdsDBName": {
      "Type": "String"
    }
  },
  "Conditions": {
    "RdsEngineTypeConditions": {
      "Fn::Equals": [
        "mysql",
        {
          "Ref": "RdsDBInstanceEngineType"
        }
      ]
    }
  },
  "Resources": {
    "Database": {
      "Type": "ALIYUN::RDS::Database",
      "Properties": {
        "CharacterSetName": {
          "Fn::If": [
            "RdsEngineTypeConditions",
            "utf8",
            "Chinese_PRC_CI_AS"
          ]
        },
        "DBInstanceId": {
          "Ref": "RdsDBInstanceId"
        },
        "DBName": {
          "Ref": "RdsDBName"
        }
      }
    }
  }
}

映射

ROS支持Key-Value形式的映射(Mappings)表,您可以指定Key从而获取映射表的Value。您可以通过以下代码在ROS CDK中设置映射。

关于映射(Mappings)的更多信息,请参见映射(Mappings)

TypeScript示例

import * as ros from '@alicloud/ros-cdk-core';
import * as ecs from '@alicloud/ros-cdk-ecs';

export class DemoStack extends ros.Stack {
    constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here
        const region = new ros.RosParameter(this, 'region', {
            type: ros.RosParameterType.STRING,
            allowedValues: ['cn-hangzhou', 'cn-beijing'],
        });
        const vpcId = new ros.RosParameter(this, 'VpcId', {
            type: ros.RosParameterType.STRING,
        });
        const vSwitchId = new ros.RosParameter(this, 'VSwitchId', {
            type: ros.RosParameterType.STRING,
        });
        const securityGroupId = new ros.RosParameter(this, 'SecurityGroupId', {
            type: ros.RosParameterType.STRING,
        });
        const ecsImageInfo = new ros.RosMapping(this, 'ECSImageInfo', {
            mapping: {
                "cn-hangzhou": {
                    "32": "m-25l0rcfjo",
                    "64": "m-25l0rcfj1"
                },
                "cn-beijing": {
                    "32": "m-25l0rcfj2",
                    "64": "m-25l0rcfj3"
                }
            },
        });
        const ecsGroups = new ecs.InstanceGroup(this,'ros-cdk-test-ecs',{
            vpcId: vpcId.valueAsString,
            vSwitchId: vSwitchId.valueAsString,
            imageId: ecsImageInfo.findInMap(region.valueAsString, '64'),
            maxAmount: 1,
            securityGroupId: securityGroupId.valueAsString,
            instanceType:'ecs.c6.large',
            instanceName: 'test-ros-cdk-ecs',
        });
    }
}

Java示例

package com.myorg;

import com.aliyun.ros.cdk.core.*;

import com.aliyun.ros.cdk.ecs.*;

import java.util.Arrays;
import java.util.Map;
import java.util.HashMap;
import java.util.List;

import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.ObjectMapper;

public class DemoStack extends Stack {
    public DemoStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public DemoStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // The code that defines your stack goes here
        List<String> list1 = Arrays.asList("cn-hangzhou", "cn-beijing");
        Map<String, Object> RegionHangzhou = new HashMap<>();
        Map<String, Object> RegionBeijing = new HashMap<>();
        RegionHangzhou.put("32", "m-25l0rcfjo");
        RegionHangzhou.put("64", "m-25l0rcfj1");
        RegionBeijing.put("32", "m-25l0rcfj2");
        RegionBeijing.put("64", "m-25l0rcfj3");
        Map<String, Map<String, Object>> mapping = new HashMap<>();
        mapping.put("cn-hangzhou", RegionHangzhou);
        mapping.put("cn-beijing", RegionBeijing);
        RosParameter region = RosParameter.Builder.create(this, "region").type(RosParameterType.STRING).allowedValues(list1).build();
        RosParameter VpcId = RosParameter.Builder.create(this, "VpcId").type(RosParameterType.STRING).build();
        RosParameter VSwitchId = RosParameter.Builder.create(this, "VSwitchId").type(RosParameterType.STRING).build();
        RosParameter SecurityGroupId = RosParameter.Builder.create(this, "SecurityGroupId").type(RosParameterType.STRING).build();

        RosMapping EcsImageInfo = RosMapping.Builder.create(this, "ECSImageInfo").mapping(mapping).build();

        InstanceGroup.Builder.create(this, "ros-cdk-test-ecs").vpcId(VpcId.getValueAsString()).
                vSwitchId(VSwitchId.getValueAsString()).maxAmount(1).securityGroupId(SecurityGroupId.getValueAsString()).
                instanceType("ecs.c6.large").instanceName("test-ros-cdk-ecs").imageId(EcsImageInfo.findInMap(region.getValueAsString(), "64")).build();

    }
}

Python示例

import ros_cdk_core as core
import ros_cdk_ecs as ecs


class DemoStack(core.Stack):

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

        # The code that defines your stack goes here
        region = core.RosParameter(self, "region",
                                   type=core.RosParameterType.STRING,
                                   allowed_values=["cn-hangzhou", "cn-beijing"])

        vpc_id = core.RosParameter(self, "VpcId", type=core.RosParameterType.STRING)

        vs_witch_id = core.RosParameter(self, "VSwitchId", type=core.RosParameterType.STRING)

        sg_id = core.RosParameter(self, "SecurityGroupId", type=core.RosParameterType.STRING)

        ecs_image_info = core.RosMapping(self, "ECSImageInfo", mapping={
            "cn-hangzhou": {
                "32": "m-25l0rcfjo",
                "64": "m-25l0rcfj1"
            },
            "cn-beijing": {
                "32": "m-25l0rcfj2",
                "64": "m-25l0rcfj3"
            }
        })

        ecs.InstanceGroup(self, "ros-cdk-test-ecs", ecs.InstanceGroupProps(
            vpc_id=vpc_id.value_as_string,
            v_switch_id=vs_witch_id.value_as_string,
            security_group_id=sg_id.value_as_string,
            max_amount=1,
            instance_type="ecs.c6.large",
            instance_name="test-ros-cdk-ecs",
            image_id=ecs_image_info.find_in_map(region.value_as_string, "64")
        ))

C#示例

using System.Collections;
using System.Collections.Generic;
using AlibabaCloud.SDK.ROS.CDK.Core;
using AlibabaCloud.SDK.ROS.CDK.Ecs;
using Stack = AlibabaCloud.SDK.ROS.CDK.Core.Stack;

namespace Demo
{
    public class DemoStack : Stack
    {
        public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // The code that defines your stack goes here

            IDictionary<string, IDictionary<string, object>> regionObj = new Dictionary<string, IDictionary<string, object>>();
            Dictionary<string, object> beijingObj = new Dictionary<string, object>();
            Dictionary<string, object> hangzhouObj = new Dictionary<string, object>();
            regionObj.Add("cn-beijing", beijingObj);
            regionObj.Add("cn-hangzhou", hangzhouObj);
            beijingObj.Add("32", "m-25l0rcfjo");
            beijingObj.Add("64", "m-25l0rcfj1");
            hangzhouObj.Add("64", "m-25l0rcfj3");
            hangzhouObj.Add("32", "m-25l0rcfj2");
            
            object[] RegionArray = new object[2] {"cn-hangzhou", "cn-beijing"};
            
            var VpcId = new RosParameter(this, "VpcId", new RosParameterProps
            {
                Type = RosParameterType.STRING,
            });

            var region = new RosParameter(this, "region", new RosParameterProps
            {
                Type = RosParameterType.STRING,
                AllowedValues = RegionArray
            });
            
            var VSwitchId = new RosParameter(this, "VSwitchId", new RosParameterProps
            {
                Type = RosParameterType.STRING
            });
            
            var SecurityGroupId = new RosParameter(this, "SecurityGroupId", new RosParameterProps
            {
                Type = RosParameterType.STRING
            });


            var ecsImageInfo = new RosMapping(this, "ECSImageInfo", new RosMappingProps
            {
                Mapping = regionObj
            });

            var ecs = new InstanceGroup(this, "ros-cdk-test-ecs", new InstanceGroupProps
            {
                VpcId = VpcId.ValueAsString,
                VSwitchId = VSwitchId.ValueAsString,
                SecurityGroupId = SecurityGroupId.ValueAsString,
                MaxAmount = 1,
                InstanceType = "ecs.c6.large",
                InstanceName = "test-ros-cdk-ecs",
                ImageId = ecsImageInfo.FindInMap(region.ValueAsString, "64")
            });
        }
    }
}

您可以解析ROS CDK代码,生成如下ROS模板:

{
  "Description": "This is the simple ros cdk app example.",
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "TemplateTags": [
        "Create by ROS CDK"
      ]
    }
  },
  "ROSTemplateFormatVersion": "2015-09-01",
  "Parameters": {
    "region": {
      "Type": "String",
      "AllowedValues": [
        "cn-hangzhou",
        "cn-beijing"
      ]
    },
    "VpcId": {
      "Type": "String"
    },
    "VSwitchId": {
      "Type": "String"
    },
    "SecurityGroupId": {
      "Type": "String"
    }
  },
  "Mappings": {
    "ECSImageInfo": {
      "cn-hangzhou": {
        "32": "m-25l0rcfjo",
        "64": "m-25l0rcfj1"
      },
      "cn-beijing": {
        "32": "m-25l0rcfj2",
        "64": "m-25l0rcfj3"
      }
    }
  },
  "Resources": {
    "ros-cdk-test-ecs": {
      "Type": "ALIYUN::ECS::InstanceGroup",
      "Properties": {
        "ImageId": {
          "Fn::FindInMap": [
            "ECSImageInfo",
            {
              "Ref": "region"
            },
            "64"
          ]
        },
        "InstanceType": "ecs.c6.large",
        "MaxAmount": 1,
        "AllocatePublicIP": true,
        "AutoRenew": "False",
        "AutoRenewPeriod": 1,
        "InstanceChargeType": "PostPaid",
        "InstanceName": "test-ros-cdk-ecs",
        "InternetChargeType": "PayByTraffic",
        "InternetMaxBandwidthIn": 200,
        "InternetMaxBandwidthOut": 1,
        "IoOptimized": "optimized",
        "Period": 1,
        "PeriodUnit": "Month",
        "SecurityGroupId": {
          "Ref": "SecurityGroupId"
        },
        "SystemDiskCategory": "cloud_efficiency",
        "VpcId": {
          "Ref": "VpcId"
        },
        "VSwitchId": {
          "Ref": "VSwitchId"
        }
      }
    }
  }
}

输出

ROS支持在输出(Outputs)中定义在调用查询资源栈接口时返回的值。您可以通过以下代码在ROS CDK中设置输出。

关于输出(Outputs)的更多信息,请参见输出(Outputs)

TypeScript示例

import * as ros from '@alicloud/ros-cdk-core';
import * as ecs from '@alicloud/ros-cdk-ecs';

export class DemoStack extends ros.Stack {
    constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here
        const vpc = new ecs.Vpc(this, 'vpc-from-ros-cdk', {
            vpcName: 'test-ros-cdk',
            cidrBlock: '10.0.0.0/8',
            description: 'This is ros cdk test'
        });
        const vpcId = new ros.RosOutput(this, 'vpcId', {
            value:  vpc.attrVpcId,
            description: 'VpcId',
        });
        const vRouterId = new ros.RosOutput(this, 'VRouterId', {
            value:  vpc.attrVRouterId,
            description: 'VRouterId',
        });
        const routeTableId = new ros.RosOutput(this, 'RouteTableId', {
            value:  vpc.attrRouteTableId,
            description: 'RouteTableId',
        });
    }
}

Java示例

package com.myorg;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.aliyun.ros.cdk.core.*;

import com.aliyun.ros.cdk.ecs.*;

import java.util.HashMap;
import java.util.List;
import java.util.Arrays;

public class DemoStack extends Stack {
    public DemoStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public DemoStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // The code that defines your stack goes here
        ObjectNode VSWNameValue = new ObjectMapper().createObjectNode();
        Vpc vpc = Vpc.Builder.create(this, "vpc-from-ros-cdk").vpcName("test-ros-cdk").
                cidrBlock("10.0.0.0/8").description("This is ros cdk test").build();

        RosOutput vpcId = RosOutput.Builder.create(this, "vpcId").value(vpc.getAttrVpcId()).description("VpcIdn").build();
        RosOutput VRouterId = RosOutput.Builder.create(this, "VRouterId").value(vpc.getAttrVRouterId()).description("VRouterId").build();
        RosOutput RouteTableId = RosOutput.Builder.create(this, "RouteTableId").value(vpc.getAttrRouteTableId()).description("RouteTableId").build();
    }
}

Python示例

import ros_cdk_core as core
import ros_cdk_ecs as ecs


class DemoStack(core.Stack):

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

        # The code that defines your stack goes here
        vpc = ecs.Vpc(self, "vpc-from-ros-cdk", ecs.VPCProps(
            cidr_block="10.0.0.0/8",
            vpc_name="test-ros-cdk",
            description="This is ros cdk test"
        ))
        vpc_id = core.RosOutput(self, "vpcId", value=vpc.attr_vpc_id, description="VpcId")
        vrouter_id = core.RosOutput(self, "VRouterId", value=vpc.attr_v_router_id, description="VRouterId")
        route_table_id = core.RosOutput(self, "RouteTableId", value=vpc.attr_route_table_id,
                                        description="RouteTableId")

C#示例

using AlibabaCloud.SDK.ROS.CDK.Core;
using AlibabaCloud.SDK.ROS.CDK.Ecs;
namespace Demo
{
    public class DemoStack : Stack
    {
        public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // The code that defines your stack goes here

            var Vpc = new Vpc(this, "vpc-from-ros-cdk", new VPCProps
            {
                CidrBlock = "10.0.0.0/8",
                VpcName = "test-ros-cdk",
                Description = "This is ros cdk test"
            });
            var vpcId = new RosOutput(this, "vpcId" ,new RosOutputProps
            {
                Value = Vpc.AttrVpcId,
                Description = "VpcId"
            });
            var VRouterId = new RosOutput(this, "VRouterId" ,new RosOutputProps
            {
                Value = Vpc.AttrVRouterId,
                Description = "VRouterId"
            });
            var RouteTableId = new RosOutput(this, "RouteTableId" ,new RosOutputProps
            {
                Value = Vpc.AttrRouteTableId,
                Description = "RouteTableId"
            });
        }
    }
}

您可以解析ROS CDK代码,生成如下ROS模板:

{
  "Description": "This is the simple ros cdk app example.",
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "TemplateTags": [
        "Create by ROS CDK"
      ]
    }
  },
  "ROSTemplateFormatVersion": "2015-09-01",
  "Resources": {
    "vpc-from-ros-cdk": {
      "Type": "ALIYUN::ECS::VPC",
      "Properties": {
        "CidrBlock": "10.0.0.0/8",
        "Description": "This is ros cdk test",
        "EnableIpv6": false,
        "VpcName": "test-ros-cdk"
      }
    }
  },
  "Outputs": {
    "vpcId": {
      "Description": "VpcId",
      "Value": {
        "Fn::GetAtt": [
          "vpc-from-ros-cdk",
          "VpcId"
        ]
      }
    },
    "VRouterId": {
      "Description": "VRouterId",
      "Value": {
        "Fn::GetAtt": [
          "vpc-from-ros-cdk",
          "VRouterId"
        ]
      }
    },
    "RouteTableId": {
      "Description": "RouteTableId",
      "Value": {
        "Fn::GetAtt": [
          "vpc-from-ros-cdk",
          "RouteTableId"
        ]
      }
    }
  }
}

伪参数

ROS支持将伪参数(Pseudo parameters)作为模板的固定参数。它们可以和用户定义的参数一样被引用,其值在ROS运行时确定。您可以通过以下代码在ROS CDK中设置伪参数。

关于伪参数(Pseudo parameters)的更多信息,请参见伪参数(Pseudo parameters)

TypeScript示例

import * as ros from '@alicloud/ros-cdk-core';

export class DemoStack extends ros.Stack {
  constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
    super(scope, id, props);
    new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
    // The code that defines your stack goes here
    const StackName = new ros.RosOutput(this, 'StackName', {
      value:  ros.RosPseudo.stackName,
    });
    const accountId = new ros.RosOutput(this, 'accountId', {
      value:  ros.RosPseudo.accountId,
    });
    const region = new ros.RosOutput(this, 'region', {
      value:  ros.RosPseudo.region,
    });
    const stackId = new ros.RosOutput(this, 'stackId', {
      value:  ros.RosPseudo.stackId,
    });
    const tenantId = new ros.RosOutput(this, 'tenantId', {
      value:  ros.RosPseudo.tenantId,
    });
  }
}

Java示例

package com.myorg;

import com.aliyun.ros.cdk.core.*;

public class DemoStack extends Stack {
    public DemoStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public DemoStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);

        // The code that defines your stack goes here

        RosOutput StackName = RosOutput.Builder.create(this, "StackName").value(RosPseudo.getStackName()).build();
        RosOutput accountId = RosOutput.Builder.create(this, "accountId").value(RosPseudo.getAccountId()).build();
        RosOutput region = RosOutput.Builder.create(this, "region").value(RosPseudo.getRegion()).build();
        RosOutput stackId = RosOutput.Builder.create(this, "stackId").value(RosPseudo.getStackId()).build();
        RosOutput tenantId = RosOutput.Builder.create(this, "tenantId").value(RosPseudo.getTenantId()).build();
    }
}

Python示例

import ros_cdk_core as core


class DemoStack(core.Stack):

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

        # The code that defines your stack goes here
        stack_name = core.RosOutput(self, "StackName", value=core.RosPseudo.stack_name)
        account_id = core.RosOutput(self, "accountId", value=core.RosPseudo.account_id)
        region = core.RosOutput(self, "region", value=core.RosPseudo.region)
        stack_id = core.RosOutput(self, "stackId", value=core.RosPseudo.stack_id)
        tenant_id = core.RosOutput(self, "tenantId", value=core.RosPseudo.tenant_id)

C#示例

using AlibabaCloud.SDK.ROS.CDK.Core;
namespace Demo
{
    public class DemoStack : Stack
    {
        public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // The code that defines your stack goes here
            var StackName = new RosOutput(this, "StackName" ,new RosOutputProps
            {
                Value = RosPseudo.StackName
            });
            var accountId = new RosOutput(this, "accountId" ,new RosOutputProps
            {
                Value = RosPseudo.AccountId
            });
            var region = new RosOutput(this, "region" ,new RosOutputProps
            {
                Value = RosPseudo.Region
            });
            var stackId = new RosOutput(this, "stackId" ,new RosOutputProps
            {
                Value = RosPseudo.StackId
            });
            var tenantId = new RosOutput(this, "tenantId" ,new RosOutputProps
            {
                Value = RosPseudo.TenantId
            });
        }
    }
}

您可以解析ROS CDK代码,生成如下ROS模板:

{
  "Description": "This is the simple ros cdk app example.",
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "TemplateTags": [
        "Create by ROS CDK"
      ]
    }
  },
  "ROSTemplateFormatVersion": "2015-09-01",
  "Outputs": {
    "StackName": {
      "Value": {
        "Ref": "ALIYUN::StackName"
      }
    },
    "accountId": {
      "Value": {
        "Ref": "ALIYUN::AccountId"
      }
    },
    "region": {
      "Value": {
        "Ref": "ALIYUN::Region"
      }
    },
    "stackId": {
      "Value": {
        "Ref": "ALIYUN::StackId"
      }
    },
    "tenantId": {
      "Value": {
        "Ref": "ALIYUN::TenantId"
      }
    }
  }
}

元数据

ROS支持使用元数据(Metadata)对Parameters中定义的参数进行分组,并且为每一组分别定义标签。您可以通过以下代码在ROS CDK中设置元数据。

关于元数据(Metadata)的更多信息,请参见元数据(Metadata)

TypeScript示例

import * as ros from '@alicloud/ros-cdk-core';

export class DemoStack extends ros.Stack {
    constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
        super(scope, id, props);
        new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
        // The code that defines your stack goes here
        const vpcId = new ros.RosParameter(this, 'VpcId', {
            type: ros.RosParameterType.STRING,
        });
        const metaData = new ros.RosInfo(this, ros.RosInfo.metadata, {
            'ALIYUN::ROS::Interface': {
                'ParameterGroups': {
                    "Parameters": [
                        vpcId.node.id
                    ],
                    "Label": {
                        "default": {
                            "zh-cn": "基础资源配置",
                            "en": "Infrastructure Configuration"
                        }
                    }
                },
                'TemplateTags': ['Demo Template']
            }
        });
    }
}

Java示例

package com.myorg;

import com.aliyun.ros.cdk.core.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;

public class DemoStack extends Stack {
    public DemoStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public DemoStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);
        RosParameter VpcId = RosParameter.Builder.create(this, "VpcId").type(RosParameterType.STRING).build();

        Map<String, Object> MetadataObj = new HashMap<>();
        Map<String, Object> InterfaceObj = new HashMap<>();
        Map<String, Object> ParameterGroupsObj = new HashMap<>();
        ArrayList<String> TemplateTagsArray = new ArrayList<>();
        ArrayList<String> ParametersArray = new ArrayList<>();
        Map<String, Object> LabelObj = new HashMap<>();
        Map<String, String> defaultObj = new HashMap<>();
        TemplateTagsArray.add("Demo Template");
        TemplateTagsArray.add("Create by ROS CDK");
        ParametersArray.add(VpcId.getNode().getId());
        MetadataObj.put("ALIYUN::ROS::Interface", InterfaceObj);
        InterfaceObj.put("ParameterGroups", ParameterGroupsObj);
        InterfaceObj.put("TemplateTags", TemplateTagsArray);
        ParameterGroupsObj.put("Parameters", ParametersArray);
        ParameterGroupsObj.put("Label", LabelObj);
        LabelObj.put("default", defaultObj);
        defaultObj.put("zh-cn", "基础资源配置");
        defaultObj.put("en", "Infrastructure Configuration");
        this.getTemplateOptions().setMetadata(MetadataObj);
    }
}

Python示例

import ros_cdk_core as core


class DemoStack(core.Stack):

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

        # The code that defines your stack goes here

        vpc_id = core.RosParameter(self, "VpcId", type=core.RosParameterType.STRING)
        metadata = core.RosInfo(self, core.RosInfo.metadata, {
            'ALIYUN::ROS::Interface': {
                'ParameterGroups': {
                    "Parameters": [
                        vpc_id.node.id
                    ],
                    "Label": {
                        "default": {
                            "zh-cn": "基础资源配置",
                            "en": "Infrastructure Configuration"
                        }
                    }
                },
                'TemplateTags': ['Demo Template']
            }
        })

您可以解析ROS CDK代码,生成如下ROS模板:

{
  "Description": "This is the simple ros cdk app example.",
  "Metadata": {
    "ALIYUN::ROS::Interface": {
      "ParameterGroups": {
        "Parameters": [
          "VpcId"
        ],
        "Label": {
          "default": {
            "zh-cn": "基础资源配置",
            "en": "Infrastructure Configuration"
          }
        }
      },
      "TemplateTags": [
        "Demo Template",
        "Create by ROS CDK"
      ]
    }
  },
  "ROSTemplateFormatVersion": "2015-09-01",
  "Parameters": {
    "VpcId": {
      "Type": "String"
    }
  }
}

标签

ROS支持为创建的资源绑定标签。您可以通过以下代码在ROS CDK中设置标签。

TypeScript示例

import * as ros from '@alicloud/ros-cdk-core';
import * as ecs from '@alicloud/ros-cdk-ecs';

export class DemoStack extends ros.Stack {
  constructor(scope: ros.Construct, id: string, props?: ros.StackProps) {
    super(scope, id, props);
    new ros.RosInfo(this, ros.RosInfo.description, "This is the simple ros cdk app example.");
    // The code that defines your stack goes here
    new ecs.Vpc(this, 'vpc-from-ros-cdk', {
      vpcName: 'test-ros-cdk',
      cidrBlock: '10.0.0.0/8',
      description: 'This is ros cdk test'
    });
    this.tags.setTag("MySampleTag", "MyTagValue");
  }
}

Java示例

package com.myorg;

import com.aliyun.ros.cdk.core.*;
import com.aliyun.ros.cdk.ecs.Vpc;
public class DemoStack extends Stack {
    public DemoStack(final Construct scope, final String id) {
        this(scope, id, null);
    }

    public DemoStack(final Construct scope, final String id, final StackProps props) {
        super(scope, id, props);
        Vpc vpc1 = Vpc.Builder.create(this, "vpc-from-ros-cdk").vpcName("test-ros-cdk").description("This is ros cdk test").
                cidrBlock("10.0.0.0/8").build();
        this.getTags().setTag("MySampleTag", "MyTagValue");
    }
}

Python示例

import ros_cdk_core as core
import ros_cdk_ecs as ecs


class DemoStack(core.Stack):

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

        # The code that defines your stack goes here

        vpc = ecs.Vpc(self, "vpc-from-ros-cdk", ecs.VPCProps(
            cidr_block='10.0.0.0/8',
            vpc_name='test-ros-cdk',
            description='This is ros cdk test'
        ))

        self.tags.set_tag("MySampleTag", "MyTagValue")

C#示例

using AlibabaCloud.SDK.ROS.CDK.Core;
using AlibabaCloud.SDK.ROS.CDK.Ecs;

namespace Demo
{
    public class DemoStack : Stack
    {
        public DemoStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var vpc = new Vpc(this, "vpc-from-ros-cdk", new VPCProps
            {
                VpcName = "test-ros-cdk",
                CidrBlock = "10.0.0.0/8",
                Description = "This is ros cdk test"
            });
            this.Tags.SetTag("MySampleTag", "MyTagValue");
        }
    }
}

您可以执行以下命令,查询资源栈绑定的标签详情。

ros-cdk list-stacks

返回结果如下:

✅ The Stacks list is:
 [
	{
		"Status": "CREATE_COMPLETE",
		"StackType": "ROS",
		"ResourceGroupId": "rg-acfm2xw4X5w****",
		"StatusReason": "Stack CREATE completed successfully",
		"CreateTime": "2021-12-27T11:09:22",
		"RegionId": "cn-beijing",
		"DisableRollback": false,
		"StackName": "DemoStack",
		"Tags": [
			{
				"Value": "rg-acfm2xw4X5w****",
				"Key": "acs:rm:rgId"
			},
			{
				"Value": "MyTagValue",
				"Key": "MySampleTag"
			}
		],
		"TimeoutInMinutes": 20,
		"StackId": "7a2a9f34-ae88-41d0-aae0-51aeerE****"
	}
]