aws-cdk icon indicating copy to clipboard operation
aws-cdk copied to clipboard

Multiple Stack - Reference Lambda function in Stack1 from Stack2

Open sacag opened this issue 6 years ago • 2 comments

This is in regards to .NET CDK. Say if I have 2 stacks(Stack1 and Stack2) defined in my App. If I have to reference a Lambda Function defined in Stack1 from Stack2. How is that possible? Did not find much documentation on it. Any example in C# or explanation on how to solve it would be helpful.

Also, what if the 2 stacks are not really related anyhow? What if Stack2 inherits from Stack1?

sacag avatar Dec 18 '19 02:12 sacag

Hi @sacag!

Typically we like to keep our issue queue free for bugs/feature-requests, and other issues that must be addressed by the core team rather than community. We direct most other questions to our Gitter and StackOverflow as suggested in the issue template.

However, with regard to your question, I will break the answer down into two parts:

Cross Stack Resources

Resources can be shared between stacks using custom StackProps. These have to be explicitly declared. Below is a codesample demonstrating passing a Lambda function.

  • CustProps.cs
public class CustProps : IStackProps
{
    public IFunction Function { get; set; }
}
  • StackOne.cs
public class StackOne : Stack
{
    public IFunction CrossStackFunc { get; set; }

    internal StackOne(Construct scope, string id, IStackProps props = null) : base(scope, id)
    {
        CrossStackFunc = new Function(this, "CSFunc", new FunctionProps
        {
            //...
        });
    }
}
  • StackTwo.cs
...
public class StackTwo : Stack
{
    internal StackTwo(Construct scope, string id, CustProps props) : base(scope, id)
    {
...
  • Program.cs
...
var stackOne = new StackOne(app, "StackOne");
new StackTwo(app, "StackTwo", new CustProps 
{
    Function = stackOne.CrossStackFunc
});
...

Nested Stacks

It is possible to nest stacks in the CDK, however it does require you to directly use the Cloudformation construct. There is a good description (in typescript) in the README, and here is the docs link for the C# version.

Hope that helps! 😸

NGL321 avatar Dec 21 '19 00:12 NGL321

Thank you @NGL321 That helps.

sacag avatar Dec 21 '19 11:12 sacag