1
votes

I would like to use the same CloudFormation template for existing stacks (UPDATE) and also for new stacks (CREATE). I'm using the Public SSM parameter store to get the latest AMI:

Parameters:
  LatestAmiId:
    Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: /aws/service/ami-windows-latest/Windows_Server-2019-English-Full-Base

Resources:
  Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
    ImageId: !Ref LatestAmiId

The problem is: When a new AMI released I can't update the exinsting stack, because it will try to replace an EC2 resource, also I can't pass an AMI which is used into LatestAmiId parameter.

I'm looking for a solution for using the same AMI in the case of stack UPDATE and to get the latest one in the case of stack CREATE.

1
You can't do this without custom resource.Marcin

1 Answers

1
votes

As a workaround the two ImageId parameters: InstanceImageId, InstanceImageIdLatest and one condition HasInstanceImageId can be used:

Parameters:
  InstanceImageId:
    Type : String
    Default: ''
  InstanceImageIdLatest:
    Type : 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
    Default: /aws/service/ami-windows-latest/Windows_Server-2019-English-Full-Base
Conditions:
  HasInstanceImageId: !Not [!Equals [!Ref 'InstanceImageId', '']]
Resources:
  Instance:
    Type: 'AWS::EC2::Instance'
    Properties:
    ImageId: !If [ HasInstanceImageId, !Ref InstanceImageId, !Ref InstanceImageIdLatest]

In the case of stack CREATE the InstanceImageId parameter should be blank and Instance will use the InstanceImageIdLatest parameter witch resolving the latest AMI.

In the case of stack UPDATE the InstanceImageId parameter should have an AMI which is currently in use.