Search code examples
aws-cdk

AWS CDK Check if Service Linked Role Already Exists


We have a CDK project with several stacks, one of them is going to deploy OpenSearch and it needs "AWSServiceRoleForAmazonOpenSearchService" to exists before the actual resource being deployed. We deploy this project to many fresh accounts and as a multi region deployment (active active in us-east-1 and ap-northeast-2). Below is our code

if region == "us-east-1":
            slr = iam.CfnServiceLinkedRole(
                self,
                f"{props.customer}-{region}-Service Linked Role",
                aws_service_name="es.amazonaws.com",
            )

domain = opensearchservice.Domain(...)

So far this code works, but in the future we might be deploying it in regions that are not us-east-1 or ap-northeast-2 and this will break our code, or if the stack deployment is ap-northeast-2 first then us-east-1, this will also break the logic because the role will only be deployed us-east-1 but the stack will deploy OS domain in ap-northeast-2.

The best logic is not to check based on the region, but based on role's existance

if slr.alreadyExists
   continue
else
   create slr role

However, i dont see this mentioned in AWS CDK docs or other posts, is it possible, or is there another alternative method that will work?


Solution

  • Another approach is to use a custom resource to determine if you should create a new service linked role or not on deployment time. Sometimes it isn't desirable to determine it on synth time because it makes the synthesis process less deterministic.

    There is a CDK library to easily realize the deploy-time decision of creating a SLR: upsert-slr.

    You can install it via pip: pip install upsert-slr

    And create a role if it's missing, or do nothing otherwise.

    import upsert_slr
    
    upsert_slr.ServiceLinkedRole(stack, "ServiceLinkedRole",
        aws_service_name="es.amazonaws.com",
    )