Sub topic 17
Bringing existing resources under management
This chapter assumes you can write a template with Parameters, Resources and Outputs, and that you have created and updated stacks from the CLI. It covers three ways to extend CloudFormation: adopting resources that already exist, rewriting templates with transforms, and running your own code as a resource.
Importing existing resources
A resource created in the console or CLI is not part of any stack. A resource import adopts it without recreating it. The steps are:
- Add the resource to your template with its real configuration. Set
DeletionPolicy: Retainon it. - Create a change set with type
IMPORT, naming each resource's logical ID and its physical identifier. - Review the change set, then execute it.
aws cloudformation create-change-set \
--stack-name demo \
--change-set-name import-bucket \
--change-set-type IMPORT \
--template-body file://template.yaml \
--resources-to-import '[{"ResourceType":"AWS::S3::Bucket","LogicalResourceId":"LegacyBucket","ResourceIdentifier":{"BucketName":"amzn-s3-demo-legacy"}}]'
aws cloudformation execute-change-set \
--stack-name demo \
--change-set-name import-bucketAn import changes nothing on the resource. If the template differs from the real configuration, the stack starts out drifted. Run drift detection right after an import.
Transforms and macros
A transform tells CloudFormation to process your template before it creates anything. You declare it with the top-level Transform key. The best-known transform is AWS::Serverless-2016-10-31, which is the AWS Serverless Application Model (SAM). It expands short AWS::Serverless::* types into the full set of resources.
AWSTemplateFormatVersion: "2010-09-09"
Transform: AWS::Serverless-2016-10-31
Resources:
HelloFunction:
Type: AWS::Serverless::Function
Properties:
Runtime: python3.12
Handler: index.handler
InlineCode: |
def handler(event, context):
return {"statusCode": 200, "body": "hello"}
Events:
Api:
Type: Api
Properties:
Path: /hello
Method: getThis one function becomes a Lambda function, an IAM role, an API Gateway API and a permission. CloudFormation shows the expanded result in the change set. AWS::Include is a smaller transform that pulls in a snippet stored in S3.
A macro is a transform you write yourself. You register a Lambda function with an AWS::CloudFormation::Macro resource. CloudFormation then sends it the template, or a fragment called through Fn::Transform, and uses the template the function returns. Macros suit organization-wide conventions, such as adding standard tags to every resource.
Custom resources
A custom resource lets a stack run your code during create, update and delete. Use one for something CloudFormation does not support, such as looking up a value or calling an external API. CloudFormation sends your Lambda function an event whose RequestType is Create, Update or Delete. The function must send a response to the event's ResponseURL.
Resources:
FnRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
GreetFunction:
Type: AWS::Lambda::Function
Properties:
Runtime: python3.12
Handler: index.handler
Role: !GetAtt FnRole.Arn
Code:
ZipFile: |
import cfnresponse
def handler(event, context):
try:
data = {}
if event["RequestType"] != "Delete":
data["Message"] = "Hello, " + event["ResourceProperties"]["Name"]
cfnresponse.send(event, context, cfnresponse.SUCCESS, data)
except Exception:
cfnresponse.send(event, context, cfnresponse.FAILED, {})
Greeting:
Type: Custom::Greeting
Properties:
ServiceToken: !GetAtt GreetFunction.Arn
Name: World
Outputs:
Message:
Value: !GetAtt Greeting.MessageExercise
You imported a bucket, and drift detection now reports differences. What caused this, and what should you do?
Show answer
The template's properties did not match the bucket's real configuration, and an import does not change the resource. Edit the template to match the real settings, or update the stack so the template's values are applied to the bucket.