CloudFormation - Outputs

Outputs in CloudFormation allows you to view Outputs through the Console or CLI. For example, displaying the PublicIP of an instance provisioned though CF templates.

AWSTemplateFormatVersion: 2010-09-09

Parameters: 
    env:
      Description: "Enter Environment: (dev/prod)"
      Type: String

Mappings: 
    environmentMap:
        dev:
          instype : "t2.micro"
          ami: "ami-0c6120f461d6b39e9"
        prod:
          instype: "t2.small"
          ami: "ami-0a443decce6d88dc2"

Resources: 
    AppServer:
      Type: 'AWS::EC2::Instance'
      Properties:
       ImageId: !FindInMap [environmentMap, !Ref env, ami]
       InstanceType: !FindInMap [environmentMap, !Ref env, instype]
       SecurityGroups: 
          - "sshSG"
       Tags:
         -  Key: "Name"
            Value: !Sub 
                    - '${environment}_server'
                    - environment: !Ref env
Outputs:
  PublicIp:
    Description: Server Public IP
    Value: !GetAtt AppServer.PublicIp
    Export:
      Name: !Sub "${AWS::StackName}-PublicIp"

For example:In the above template, the servers public IP is exported.

2022-06-07 09_28_04-54.66.203.169 (ec2-user).png

Outputs also allows you to export values that can be imported in another CF stack. For example, use a separate template that provisions ec2-instances and export the public IP's, which could be referenced in another template. To import values, use Fn::ImportValue

AWSTemplateFormatVersion: 2010-09-09
Description: Template to demo importing value from another CF teamplate
Resources: 
    secGroupName:
      Type: AWS::EC2::SecurityGroup
      Properties:
        GroupName: SSHJUMPSERVER
        GroupDescription: Open SSH from JumpServer
        SecurityGroupIngress:
          - IpProtocol: "tcp"
            FromPort: 22
            ToPort: 22
            CidrIp: !Sub 
                    - '${ec2_ipaddress}/32'
                    - ec2_ipaddress: !ImportValue myteststack1-PublicIp
        Tags:
          - Key: "Project"
            Value: "CF Demo"
          - Key: "Name"
            Value: SSHJUMPSERVER

2022-06-07 18_26_07-54.66.203.169 (ec2-user).png

The above example template is to create a Security Group that allows ingress traffic on port 22 from a particular IP address - which is actually imported from another CF stack (myteststack1).

2022-06-07 18_33_16-EC2 Management Console.png