简体   繁体   中英

Using the CfnOutput created inside a LambdaRestApi in AWS CDK

I'm creating a LambdaRestApi as follows

        this.gateway = new apigw.LambdaRestApi(this, "Endpoint", {
            handler: hello,
            endpointExportName: "MainURL"
        })

and I'd like to get to the CfnOutput it generates, is it possible? I want to pass it to other functions and I want to avoid creating a new one.

Assuming you are using the following code for your LambdaRestApi:

this.gateway = new apigw.LambdaRestApi(this, "Endpoint", {
    handler: hello,
    endpointExportName: "MainURL"
});

Referencing in same stack as LambdaRestApi

const outputValue = this.gateway.urlForPath("/");

Looking at the source code , the output value is just a call to urlForPath. The method is public, so you can use it directly.

Referencing from another stack

You can use cross stack references to get a reference to the output value of the stack.

import { Fn } from 'aws-cdk-lib';
const outputValue = Fn.importValue("MainURL");

If you try to use the first method in another stack, CDK will just generate a cross stack reference dynamically by adding extra outputs, so it is better to import the value directly.

I'd like to get to the CfnOutput it generates, is it possible?

Yes. Use the escape hatch syntax to get a reference to the CfnOutput that RestApi creates for the endpointExportName :

const urlCfnOutput = this.gateway.node.findChild('Endpoint') as cdk.CfnOutput;

console.log(urlCfnOutput.exportName);
// MainURL

console.log(urlCfnOutput.value);
// https://${Token[TOKEN.258]}.execute-api.us-east-1.${Token[AWS.URLSuffix.3]}/${Token[TOKEN.277]}/

Prefer standard CDK

As their name suggests, "escape hatches" are for "emergencies" when the CDK's standard solutions fail. Your use case may be one such instance, I don't know. But as @Kaustubh Khavnekar points out, you don't need the CfnOutput to get the url token value.

console.log(this.gateway.url)
// https://${Token[TOKEN.258]}.execute-api.us-east-1.${Token[AWS.URLSuffix.3]}/${Token[TOKEN.277]}/

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