Using different IAM roles depending on stage

Hi,
My serverless deployments use this statement for configuring the IAM Role permissions:

iamRoleStatements:
$ref: ./iamRoleStatements.json

The json file contains these permissions:

[
  {
    "Effect": "Allow",
    "Action": [
      "dynamodb:BatchGetItem",
      "dynamodb:BatchWriteItem",
      "dynamodb:DeleteItem",
      "dynamodb:GetItem",
      "dynamodb:GetRecords",
      "dynamodb:GetShardIterator",
      "dynamodb:PutItem",
      "dynamodb:Query",
      "dynamodb:Scan",
      "dynamodb:UpdateItem"
    ],
    "Resource": "arn:aws:dynamodb:*:222222222222:*"
  },
  {
    "Effect": "Allow",
    "Action": [
        "cognito-identity:GetOpenIdTokenForDeveloperIdentity",
        "cognito-identity:LookupDeveloperIdentity",
        "cognito-identity:MergeDeveloperIdentities",
        "cognito-identity:UnlinkDeveloperIdentity"
      ],
      "Resource": "arn:aws:cognito-identity:eu-central-1:222222222222:*"
  },
  {
    "Effect": "Allow",
    "Action": [
        "ec2:CreateNetworkInterface",
        "ec2:DescribeNetworkInterfaces",
        "ec2:DeleteNetworkInterface"
    ],
    "Resource": "*"
  }
]

Currently we are using eu-central-1 as development environment but we will use another zone for production.

Basically I need to configure the cognito resource like this:
dev stage: “Resource”: “arn:aws:cognito-identity:eu-central-1:222222222222:"
prod stage: “Resource”: "arn:aws:cognito-identity:eu-west-1:222222222222:
”

How can I achieve this?

Thank you in advance

You could make the Resource (or just the region part of it) a variable. I can’t recall off the top of my head if you can put Serverless Variables in an external file that you load - you can definitely do it by moving your policy in to your serverless.yml and doing something like ${env:${opt:stage}_resource}.

You can use Serverless variable inside external files (the YAML files at least). I’ve done it using external YAML files to define environment variables. I’d convert it to a YAML file then use ${self:provider.region} inside your definition.

This is un-tested but should work.

"Resource": "arn:aws:cognito-identity:${self:provider.region}:222222222222:*"

2 Likes

Same solution here. Variables interpolated into the resource names.