0
votes

I have cloudformation template for provisioning EC2,VPC,S3 resources but I want to create stack for specific resource type (e.g for EC2 only) from that template. I have used aws cli and mentioned --resource-types "AWS::EC2::Instance" but I am getting error "An error occurred (ValidationError) when calling the CreateStack operation: Resource type AWS::S3::Bucket is not allowed by parameter ResourceTypes [AWS::EC2::Instance]" . Could you please let me know how can I create stack resource wise ?

1

1 Answers

0
votes

Method 1:

Add an Input parameter called ResourceType as shown below. Pass the Resource-Type which you want to create as an input to the CFN template.

Parameters:
  ResourceType:
    Description: Resource Types
    Type: String
    AllowedValues:
      - EC2
      - RDS
      - VPC
      - S3

Add corresponding conditions:

Conditions:
  CheckCreateEC2: 
    Fn::Equals: [ Ref: ResourceType, "EC2" ]
  CheckCreateRDS: 
    Fn::Equals: [ Ref: ResourceType, "RDS" ]
  CheckCreateVPC: 
    Fn::Equals: [ Ref: ResourceType, "VPC" ]
  CheckCreateS3: 
    Fn::Equals: [ Ref: ResourceType, "S3" ]

Then create the resource-type accordingly and the corressponding condition checks into it.

Resources:
  MyEC2Instance:
    Type: AWS::EC2::Instance
    Condition: CheckCreateEC
    Properties:
      .
      .
      .


  MyRDSInstance:
    Type: AWS::RDS::DBInstance
    Condition: CheckCreateRDS
    Properties:
      .
      .
      .   

  MyS3Bucket:
    Type: AWS::S3::Bucket
    Condition: CheckCreateS3
    Properties:
      .
      .
      .   

This way only the resources corresponding to the resource-type which you pass as InputParameter will be created.

Method 2:

You can AWS Nested Stacks. Using this, You can maintain an individual common templates for each resource types, but still maintain dependency between them so that entire Stack is created.

This Method is more apt, if you can maintain separate templates for each resource-type. This provides more flexibility as well as isolation(If you need to modify condition/parameters of a particular resource-Type, You just need to update that specific template) and will reduce human errors in other section of the templates.