How do I get the AccountId as a variable in a serverless.yml file?

justin.m.chase picture justin.m.chase · Mar 5, 2017 · Viewed 16.9k times · Source

I want to build an ARN in my file dynamically, but I need to get my current AccountId. How can I access it as a variable?

For example:

example: arn:aws:states:${region}:${accountId}:stateMachine:${self:service}-${self:custom.stage}-example

What is the proper way to reference the current region and accountId?

Edit: (solution)

I'm not super happy with this solution due to the ugliness and verbosity of the Fn::Join solution but what I ended up doing is making an arns.yml file which has all of these in only this one place then reference then by variable elsewhere.

# arns.yml
example:
  Fn::Join:
    - ":"
    - - arn
      - aws
      - states
      - Ref: AWS::Region
      - Ref: AWS::AccountId
      - stateMachine
      - ${self:service}-${self:custom.stage}-example

Then:

# serverless.yml
custom:
  stage: "${opt:stage, self:provider.stage}"


functions:
  foo:
    handler: handler.foo
    environment:
      example_arn: ${file(arns.yml):example}

Edit 2: (Better Solution)

This may sound lame but the solution I ended up going with is to just hard code it into my custom variables. I actually have two accounts and I use a custom build step to copy the two files with account specific settings like so:

account.stag.yml
account.prod.yml

Each file may look like this:

# account.stag.yml
account: 123456789
region: ${opt:region, "us-east-1"}
domain: mycompany.qa

When I build I specify an account and I use gulp to do all of my building:

gulp build --account stag

Then that renames my account specific settings to

build/account.yml

And I can reference it in my serverless.yml like so:

# build/serverless.yml
custom: ${file(account.yml)}
functions:
  foo:
    handler: handler.foo
    environment:
      example_arn: arn:aws:states:${self:custom.region}:${self:custom.account}:${self:service}-${opt:stage}-example

Answer

Sam J picture Sam J · Jun 15, 2017

There's a handy serverless plugin https://www.npmjs.com/package/serverless-pseudo-parameters that adds the ability to reference aws parameters such as region and account id that i've just started using to much success.