繁体   English   中英

使用 AWS CDK 解决 AWS Cloudformation 中的资源相互依赖性

[英]Solving resource interdependencies in AWS Cloudformation, using AWS CDK

我这里有一种情况,两个 AWS 资源相互依赖。 在下面提到的情况下,我们如何解决或最佳解决方案是什么?

有两种构造,一种用于创建 SNS 主题,另一种用于 Lambda function。SNS 需要 lambda function ARN 来添加订阅,而 lambda function 需要将其添加到 SNS 主题 ARN 的环境变量。 如何使用 CDK(最好是在 .NET 中)解决这种依赖关系?

代码:

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 构建:

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 构建:

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 将消息流式传输到 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}");
  }
}

找到了解决方案,我可以使用此方法在创建 Lambda 后添加环境变量:

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

因此,一旦创建了 SNS 主题(依赖于 Lambda),我可以稍后添加一个变量。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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