简体   繁体   中英

Solving resource interdependencies in AWS Cloudformation, using AWS CDK

I've a situation here, where two AWS resources are interdependent. How could we resolve or what's the best solution in the below mentioned situation?

There are two constructs, one for creating SNS topic and other for Lambda function. The SNS requires lambda function ARN for adding a subscription, whereas lambda function requires SNS topic ARN for adding it to an environment variable. How can this dependency be resolved with CDK (preferably in .NET)?

Code:

public class AllStacks : Stack
{
   public AllStacks(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
   {
      var lambdaFn = new LambdaFnConstruct(this, "LambdaFunction");
      new SNSConstruct(this, "SnsTopic", lambdaFn.lambdaARN);      
   }
} 

Lambda Construct:

internal LambdaFnConstruct(Construct scope, string id, Role role) : base(scope, id)
{
    var lambdaFn = new Function(this, "LambdaCDK", new FunctionProps()
    {
        //Some code here...
        Environment = new Dictionary<string, string>()
        {
           {"SNS_ARN", /* Need to provide SNS ARN here */ },
        },
    });
}

SNS Construct:

public SNSConstruct(Construct scope, string id, string lambdaARN) : base(scope, id)
{
    Topic topic = new Topic(this, "Messaging", new TopicProps()
    {
        TopicName = "Messaging"
    });
    Subscription subscription = new Subscription(this, "Topic subscription", new SubscriptionProps()
    {
        Topic = topic,
        Protocol = SubscriptionProtocol.LAMBDA,
        Endpoint = lambdaARN, //<----Lambda ARN goes here
    });
}

Lambda function streaming message to AWS Connect:

public async Task EnableMessageStreamingAsync(string channel, string contactID)
{
   try
   {
     StartContactStreamingRequest startContactStreamingRequest = new StartContactStreamingRequest()
      {
        ContactId = contactID,
        InstanceId = instanceID,
        ChatStreamingConfiguration = new ChatStreamingConfiguration()
        {
          StreamingEndpointArn = streamEndpointARN //<--- Here goes the SNS ARN
        }
      };

  await connectClient.StartContactStreamingAsync(startContactStreamingRequest);
  }
  catch (Exception ex)
  {
    LambdaLogger.Log($"Error messgae: {ex.Message}");
    LambdaLogger.Log($"Stack trace: {ex.StackTrace}");
  }
}

Found a solution, I can add environment variable post the creation of Lambda using this method:

public virtual Function AddEnvironment (string key, string value, IEnvironmentOptions? options = null)

So once SNS topic is created (which is Lambda dependent), I can add a variable later.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM