amazon-web-servicesaws-cloudformationsam

How can I use Fn::GetAttr only when the resource exist?


I'm making one main stack and two nested stack. The first nested stack is a stack which creates Lambda. And the second nested stack creates Apigateway.

When making the Apigateway I send some Lambda outputs to the Apigateway template. But some Lambda Outputs don't get created in some conditions.

So when I use Fn::GetAttr to send some outputs to the Apigateway template. I get an error because the output doesn't exist.

[Lambda Template (Nested Stack)]

Because of the condition conditionNeedMock the MockServerArn output wasn't created.

...
Outputs:
  MockServerArn:
    Condition: conditionNeedMock
    Description: lambdaMock function Arn
    Value: !GetAttr lambdaMock.Arn
...

[Main Template]

LambdaStack.Ouputs.MockserverArn wasn't created so I get an error when using !GetAttr.

...
Resources:
  LambdaStack:
    Type: AWS::CloudFormation::Stack
    ...

  ApiGatewayStack:
    Type: AWS::CloudFormation::Stack
    DependsOn: LambdaStack
    Properties:
      TemplateURL: apigateway.yml
      TimeoutInMinutes: 20
      Parameters:
        paramMockServerArn: !GetAtt LambdaStack.Outputs.MockServerArn
...

Solution

  • The only way that could possibly work (without introducing custom resources) is if conditionNeedMock is also in the root stack:

    paramMockServerArn: !If [conditionNeedMock, !GetAtt LambdaStack.Outputs.MockServerArn, !Ref "AWS::NoValue"]