Prashant Singh
Prashant Singh

Reputation: 41

How to get existing VPC cidr inside cloudformation stack

I'm creating a CloudFormation stack, which creates additional subnets in a vpc. I get VPCId (existing VPC) as parameter to the stack. How to get the VPC cidr inside the CF stack?

Upvotes: 3

Views: 3332

Answers (3)

Paulo Merson
Paulo Merson

Reputation: 14457

An alternative is to define the VPC and the VPC Cidr block as parameters in the CF template. Example:

Parameters:
  VpcId:
    Description: Select an existing VPC
    Type: 'AWS::EC2::VPC::Id'
  VPCCidrBlock:
    Description: CIDR block of the existing VPC"
    Type: String

Then you can simply reference the parameters. Example:

  MySecurityGroup:
    Type: AWS::EC2::SecurityGroup
    Properties:
      GroupDescription: security group allowing HTTPS traffic from within VPC
      VpcId: !Ref VpcId
      SecurityGroupIngress:
        - IpProtocol: tcp
          FromPort: 443
          ToPort: 443
          CidrIp: !Ref VPCCidrBlock    

(BTW, notice the Type of the VpcId parameter. If you're creating the stack via the AWS console, there's the benefit of getting a list of visible VPCs to click.)

Upvotes: 0

Prateek Mishra
Prateek Mishra

Reputation: 11

Yes @John is right. You cannot use Fn:GetAtt on stack parameters as is given here - "For resources created by CloudFormation, you can use the GetAtt intrinsic function to look up information. For stack parameters, you need a different approach."

Refer this doc by AWS to know more about how you can get information about stack parameters.

Upvotes: 1

John Rotenstein
John Rotenstein

Reputation: 269101

From AWS::EC2::VPC - AWS CloudFormation:

Fn::GetAtt returns a value for a specified attribute of this type. The following are the available attributes and sample return values:

CidrBlock: The set of IP addresses for the VPC. For example, 10.0.0.0/16.

However, I suspect this only works on a VPC that was created within the CloudFormation template.

Since you want to refer to an existing VPC, you will need to write a CloudFormation custom resource using AWS Lambda.

It's a bit tricky, but there are some good sample templates at: stelligent/cloudformation-custom-resources

Upvotes: 6

Related Questions