Outputs

在本实验中将了解 Outputs 。Outputs使您能够访问堆栈中资源的信息, 例如,可以在创建EC2实例后将其Public IP输出到CloudFormation控制台。

此外可以将输出值导入其他堆栈, 称为跨栈引用(cross-stack references),但要注意,如果一个stack被另一个stack引用,那么它不能被删除,必须先把依赖的stack全删掉。

YAML 语法
Outputs:
  Logical ID:
    Description: Information about the value
    Value: Value to return
    Export:
      Name: Value to export

CloudFormation模板中最多可以声明60个Outputs

Outputs实验

将以下代码保存为lab05-Outputs.yaml :

AWSTemplateFormatVersion: '2010-09-09'

Description: CFN 101 Workshop - Lab 05 Outputs.

Metadata:
  AWS::CloudFormation::Interface:
    ParameterGroups:
      - Label:
          default: 'Amazon EC2 Configuration'
        Parameters:
          - AmiID

    ParameterLabels:
      AmiID:
        default: 'Amazon Machine Image ID'

Parameters:
  EnvironmentType:
    Description: 'Specify the Environment type of the stack.'
    Type: String
    Default: Test
    AllowedValues:
      - Dev
      - Test
      - Prod
    ConstraintDescription: 'Specify either Dev, Test or Prod.'

  AmiID:
    Type: AWS::EC2::Image::Id
    Description: 'The ID of the AMI.'

Mappings:
  EnvironmentToInstanceType:
    Dev:
      InstanceType: t2.nano
    Test:
      InstanceType: t2.micro
    Prod:
      InstanceType: t2.small

Resources:
  WebServerInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !Ref AmiID
      InstanceType: !FindInMap [EnvironmentToInstanceType, !Ref EnvironmentType, InstanceType]
      Tags:
        - Key: Name
          Value: !Join [ '-', [ !Ref EnvironmentType, webserver ] ]

  WebServerEIP:
    Type: 'AWS::EC2::EIP'
    Properties:
      Domain: vpc
      InstanceId: !Ref WebServerInstance

Outputs:
  WebServerPublicDNS:
    Description: 'Public DNS of EC2 instance'
    Value: !GetAtt WebServerInstance.PublicDnsName

  WebServerElasticIP:
    Description: 'Elastic IP assigned to EC2'
    Value: !Ref WebServerEIP

为了获得实例的PublicDnsName,需要使用Fn::GetAtt函数( 可以查看AWS文档 以获取可用属性, 可以看到PublicDnsNameFn::GetAtt函数的有效返回值):

Outputs:
  EC2PublicDNS:
    Description: 'Public DNS of EC2 instance'
    Value: !GetAtt WebServerInstance.PublicDnsName

部署CloudFormation。在上一节的堆栈中更新:

img

选择上传lab05-Outputs.yaml :

image-20210522215431792

一直点击Next,直至更新完成。


在更新完成后,怎么查看Outputs值呢?

outputs-gif

cross stack reference

使用Fn::ImportValue函数,能够引用Outputs中Export的值。

例如,在Stack A中Export SSH安全组:

image-20221023094859662

在Stack B中引用这个安全组:

image-20221023094851240