9

I have created a CDK stack that will be deployed in multiple regions. One of the constructs shall only be deployed in one region. In Cloudformation I'd simply add a Condition to the resource, but I haven't found a way to do something similar with CDK constructs.

It is possible to define a CfnCondition and add it to CfnResources, but I how do I add conditions to constructs like lambda functions?

Lukas
  • 178
  • 1
  • 1
  • 11

2 Answers2

13

Here is a example on how to achieve this for a iam.User:

// Create a CloudFormation condition on the region
const regionCondition = new cdk.CfnCondition(this, 'RegionCondition', {
  expression: cdk.Fn.conditionEquals(cdk.Stack.of(this).region, 'eu-west-1'),
});

// Create the user using the L2 construct
const user = new iam.User(this, 'User');

// Add the condition on the underlying AWS::IAM::User
(user.node.defaultChild as iam.CfnUser).cfnOptions.condition = regionCondition
jogold
  • 6,667
  • 23
  • 41
  • Thank you, that did the trick. Do you know where I can find this in the documentation? – Lukas Dec 19 '19 at 16:00
  • 4
    You have examples here https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html#intrinsic-functions-and-condition-expressions and https://docs.aws.amazon.com/cdk/api/latest/docs/core-readme.html#resource-options (the last one is missing a `cfnOptions`, just opened a PR to fix this https://github.com/aws/aws-cdk/pull/5490) – jogold Dec 19 '19 at 16:03
  • How could I have missed that? Sometimes the answers hide in plain sight... Thank you! – Lukas Dec 19 '19 at 16:41
0

Here is a example on how to achieve this for a iam.Role:

const role = new iam.Role(this, "TestRole", {...});

const conditionKey = "AssumeRolePolicyDocument.Statement.0.Condition.ForAnyValue:StringLike";


const conditionValue = {
      "aws:userid": [
        "user1@company.com",
        "user2@company.com",
      ],
    };

const roleRef = role.node.defaultChild as iam.CfnRole;
roleRef.addPropertyOverride(conditionKey, conditionValue);
Jorge López
  • 1,649
  • 1
  • 10
  • 7