Home > Net >  AWS CDK: Is it possible to get a variable which points the person who deployed the stack?
AWS CDK: Is it possible to get a variable which points the person who deployed the stack?

Time:06-20

Is there a variable I can retrieve to point automatically to the person who have done the cdk deploy ?

Maybe with intrinsic functions ?

The idea is to set a tag to my resources like this:

Tags.of(resource).add("owner",<the_deployer>);

I'm using the CDK v2 with TypeScript.

CodePudding user response:

No, because the CDK itself only Synths no matter who pushes the Deploy button, the actual user is 'AWSCloudFormation'

However, you can leverage some help for yourself if you are using version control (and if your not, well you should be)

For instance, we tag all of our resources deployed through cdk with commit sha of the commit and the github username of the person who pushed that commit. In a CodePipeline these are available environment variables - if you are just using CDK Deploy from your local computer then you can reference them using any of the numerous Git SDKs for various languages:

For example, in Python (because I am more familiar, but all of this is possible with Typescript as well of course:

import git

def create_tags()->dict:
    repo = git.Repo(search_parent_directories=True)
    return {
        branch: repo.active_branch.name,
        commit: repo.head.commit.hexsha,
        author: repo.head.commit.author.name
    }

... in your app.py after instantiating your stack...

for key, value in create_tags().items():
    cdk.Tags.of(YourStack).add(key, value)

Alternatively, again from your local, wrap your cdk deploy in a bash script. use $whoami and pass that into your stack as a context varibale

$ bash deploy_cdk.sh
   > cdk deploy Stack\* -c user=${whoami}

and in your stack itself:

  user = self.node.try_get_context("user")
  cdk.Tags.of(self).add("User", user)

Here is the page on try_get_context and how to use context variables like this:

https://docs.aws.amazon.com/cdk/v2/guide/context.html

Quick Note: If you tag a stack, it propagates automatically to each resource, saving you a lot of duplicated code

  • Related