Search code examples
amazon-web-servicesterraformserverless

How can I import resources to serverless managed project?


I am using serverless to deploy AWS resources. And sometimes I get an error about how there is an existing resources so the deploy failed. This could be caused by another developer in the team deploy the resources which have a conflict name. I wonder how I should handle this in serverless?

I used terraform before and it supports import command which is used to import existing resource to my project. Is there anything similar in serverless? If not, what is the best practise to solve this issue? I don't want to manually delete the resources on AWS.


Solution

  • TL;DR: Importing CloudFormation resources is not supported by the serverless framework. But there are ways to solve the problem in question.

    Serverless allows you to use values of existing CloudFormation resources. A pre-requisite is that your colleague or at least the CloudFormation stack describes the resource you depend on as "output".

    // in your colleagues serverless.yaml to export a VPC
    resources:
       // ...
       Outputs:
         StackVPC:
           Description: The ID of the VPC
           Value: !Ref MyVPC
           Export:
             Name: !Sub "${AWS::StackName}-VPCID"
    

    In your serverless.yaml you can import/reference the existing VPC. There are a few ways to import the resource into your stack.

    var1: 'Fn::ImportValue': '${refSackName}-VPCID'
    var2: ${cf:${refSackName}-VPCID}
    

    For me, I mostly use Fn::ImportValue

    Pros and cons about this approach are listed here https://dev.to/lambdasharp/dynamic-bindings-for-cloudformation-stacks-15l6