如何在模板中引用数据源资源(DataSource)输出变量

数据源资源(DataSource)用于查询云服务资源数据。数据源资源输出属性有两种类型,一种是查询结果为单个资源,另一种是查询结果为多个资源,其中多个资源以列表的结果输出。本文为你介绍如何在模板中引用数据源资源(DataSource)输出变量。

查询结果为单个资源

查询单个RDS实例(DATASOURCE::RDS::DBInstance),获取RDS实例的内网连接端口Port,并为其申请一条外网连接地址为例。

ROSTemplateFormatVersion: '2015-09-01'
Parameters:
  DBInstanceId:
    Type: String
    AssociationProperty: ALIYUN::RDS::Instance::InstanceId
Resources:
  ExtensionDataSource:
    Properties:
      DBInstanceId:
        Ref: DBInstanceId
    Type: DATASOURCE::RDS::DBInstance
  Connection:
    Type: ALIYUN::RDS::Connection
    Properties:
      DBInstanceId:
        Ref: DBInstanceId
      ConnectionStringPrefix: test1
      Port:
        Fn::GetAtt:
          - ExtensionDataSource
          - Port
Outputs:
  Port:
    Description: The port that is used to connect to the instance over an internal network.
    Value:
      Fn::GetAtt:
        - ExtensionDataSource
        - Port
  ConnectionString:
    Description: Connection string
    Value:
      Fn::GetAtt:
        - Connection
        - ConnectionString

查询结果为多个资源

查询已创建的交换机(DATASOURCE::VPC::VSwitches),并为查询到的交换机的CidrBlock创建安全组入方向的访问规则。其中使用内部函数Fn::Jq用于获取输出结果vSwitches中第一个交换机的CidrBlock,Jq功能详情请参见Jq文档

ROSTemplateFormatVersion: '2015-09-01'
Parameters:
  VpcId:
    Type: String
    AssociationProperty: ALIYUN::ECS::VPC::VPCId
    Description: Please search the ID starts with (vpc-xxx)from console-Virtual Private Cloud
    Label: Existing VPC Instance ID
  SecurityGroupId:
    Type: String
    AssociationProperty: ALIYUN::ECS::SecurityGroup::SecurityGroupId
    AssociationPropertyMetadata:
      VpcId: ${VpcId}
    Default: ''
Resources:
  ExtensionDataSource:
    Type: DATASOURCE::VPC::VSwitches
    Properties:
      VpcId:
        Ref: VpcId
  SecurityGroupIngress:
    Type: ALIYUN::ECS::SecurityGroupIngress
    Properties:
      IpProtocol: all
      SecurityGroupId:
        Ref: SecurityGroupId
      NicType: intranet
      SourceCidrIp:
        Fn::Jq:
          - First
          - .[0].CidrBlock
          - Fn::GetAtt:
              - ExtensionDataSource
              - VSwitches
      PortRange: '-1/-1'
Outputs:
  CidrBlock:
    Description: Cidr Block.
    Value:
      Fn::Jq:
        - First
        - .[0].CidrBlock
        - Fn::GetAtt:
            - ExtensionDataSource
            - VSwitches