Connormcwood
Connormcwood

Reputation: 111

Is it possible to retrieve existing resource identifiers within AWS SAM?

I have several services split up where serveral of these services are a lambda + api gateway which I decided to use the Serverless Application Model (SAM) tool that AWS provides so I can make use of local start-api while I am working locally on these services.

However, my main infrastructure is not written within SAM, and instead is written in Terraform. I know that if I wrote directly in SAM or Cloudformation my infrastructure would be built as a stack which would allow me to reference resources within the service's SAM template so that I can build those services making use of resource properties I wish to use. Is there a way within the SAM template to retrieve resource parameters (that already exist) for example subnet_id's, vpc_names ect?

The solution I have at the moment is to use the CLI to retrieve the properties I wish and pass them into SAM template as variables, is there a more elegant solution?

Upvotes: 0

Views: 947

Answers (2)

Clark
Clark

Reputation: 51

In Terraform, you could store the values you need in SSM parameters and then reference them using dynamic references in CloudFormation/SAM templates.

Terraform:

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_ssm_parameter" "vpc_id" {
  name  = "/main/vpc_id"
  type  = "String"
  value = aws_vpc.main.id
}

Reference from a CloudFormation/SAM template:

ExampleSubnet:
  Type: AWS::EC2::Subnet
  Properties:
    VpcId: '{{resolve:ssm:/main/vpc_id}}'
    CidrBlock: 10.0.0.0/24
    AvailabilityZone: us-east-1a

I know the question is from 2020, so just providing an updated answer for posterity because I landed here when searching for the solution to this.

Upvotes: 0

Paul Michalik
Paul Michalik

Reputation: 4381

I don't think so. This is probably the best option given you insist on using this combination of technologies. You could of course switch to a unified tech stack, i. e. Terraform OR CloudFormation. I am in the same situation by the way and my approach is exactly the one you have described. I have negotiated an API written in Terraform and whenever I need to use the infrastructure resources I am parsing out the names out of Json outputs and forwarding them to CDK or CloudFormation via command line parameters.

Upvotes: 1

Related Questions