EmptyArsenal
EmptyArsenal

Reputation: 7464

Programmatically utilize resources created with CloudFormation

I'm creating a bunch of application resources with AWS CloudFormation, and when the resources are created, CloudFormation adds a hash at the end of the name to make it unique.

i.e. If you wanted to create a Kinesis stream names MyStream, the actually name would be something like my-stack-MyStream-1F8ISNCLP0W4O.

I want to be able to programmatically access the resources without having to know the hash, without having to query AWS for my resources to match the names myself, and without manual steps. Does anybody know a convenient way to use AWS resources in your application programmatically and predictably?

Here are the less ideal options I can think of:

  1. Set a tag on the resource (i.e. name -> MyStream) and query AWS to get the actual resource name.
  2. Query AWS for a list of resources names and look for a partial match on the expected name.
  3. After you create your resources, manually copy the actual names into your config file (probably the sanest of these options)

Upvotes: 2

Views: 462

Answers (1)

ataylor
ataylor

Reputation: 66059

You can use the CloudFormation API to get a list of resources in your stack. This will give you a list of logical ids (i.e. the name in your CloudFormation template without the hash) and matching physical ids (with the stack name and hash). Using the AWS CLI, this will show a mapping between the two ids:

aws cloudformation describe-stack-resources
    --query StackResources[].[LogicalResourceId,PhysicalResourceId]
    --stack-name <my-stack>

CloudFormation APIs to do the same query are provided in all the various language SDKs provided by Amazon.

You can use this as an alternative to #1, by querying CloudFormation at runtime, or #3, by querying CloudFormation at buildtime and embedding the results in a config file. I don't see any advantage to using your own tags over simply querying the CF API. #2 will cause problems if you want two or more stacks from the same template to coexist.

I've used both the runtime and build time approaches. The build time approach lets you remove the dependency on or knowledge of CloudFormation, but needs stack specific information in your config file. I like the runtime approach to allow the same build to be deployed to multiple stacks and all it needs is the stack name to find all the related resources.

Upvotes: 2

Related Questions