AWS SAM: can we use a already existing api in aws sam template?

Viewed 1629

I have a lambda function that needs to be triggered via Amazon API Gateway. Is there a way to include an already existing API (created using the AWS console) into AWS SAM template?

1 Answers

SAM doesn't support the !ImportValue in the template yet.

Issue on Github

On the GitHub of the aws/serverless-application-model there's an open PR for that feature

See here

If you want you could help and contribute to that PR so then you could start using !ImportValue in your SAM template.yml

Else, I suggest you go with the old way, you create a CI/CD with a CloudFormation template that can use the !ImportValue and is linked to an S3 bucket where your lambda function code lives.

Examples of Cloudformation Templates

Update

SAM CLI now support the !ImportValue, the issue on Github is closed.

You can use it as follow

# You need to export the resource that you want to use in another template first

# This goes at the end of your template.yml file, after the Resources

# template.yml in the first repo
Outputs:
    myExportedResource:
        Value: !Ref TheResource
        Export:
            Name: !Sub "{environment}-nice-export-name"


# template.yml in the second repo (This obviously goes in Resources)
    MyLambda:
        Type: AWS::Serverless::Function
        Properties:
            FunctionName: awesome-lambda
            CodeUri: ./dist
            Handler: this-file.handler
            Role: !GetAtt LambdaRole.Arn
            VpcConfig:
                SecurityGroupIds:
                    - !GetAtt SecurityGroup.GroupId
                SubnetIds:
                    - Fn::ImportValue: !Sub "${environment}-nice-export-name"

You can use it exactly as a normal cloudformation template

https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html

Note that here I used Fn:ImportValue because I needed to use !Sub but if you don't need to reference a parameter in your import value simply use !ImportValue

Related