AWS CDK | 创建跨越多个 CDK 堆栈的 REST API

Viv*_*mar 5 aws-cdk

我们正在使用 AWS CDK 来创建我们的无服务器 REST API。但是,有大量端点,有时我们必须销毁和重新部署我们的堆栈。为了防止 REST API URL 随每次部署而更改,我计划在一个堆栈中创建 API GATEWAY,并在单独的堆栈中添加方法和资源。如何在单独的堆栈中引用创建的 rest API?

试图从https://github.com/aws/aws-cdk/issues/3705实现一些东西,但所有资源(API 网关、资源和方法)都被推送到一个堆栈中,而不是一个堆栈中的 API 网关以及其他堆栈中的资源。

相关代码片段如下:

bts-app-cdk.ts

const first = new FirstStack(app, 'FirstStack', {
    env: {
        region: 'us-east-1',
        account: '1234567890',
    }
    });

const second = new SecondStack(app, 'SecondStack', {
    apiGateway: first.apiGateway,
    env: {
        region: 'us-east-1',
        account: '1234567890',
    }
});

second.addDependency(first)
Run Code Online (Sandbox Code Playgroud)

第一个stack.ts

export class FirstStack extends cdk.Stack {

    public readonly apiGateway: apig.IResource;

    constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
        super(scope, id, props);

        const apiGateway = new apig.RestApi(this, 'BooksAPI', {
            restApiName:'Books API',
        })
        apiGateway.root.addMethod('GET');

        this.apiGateway = apiGateway.root;
    }
}
Run Code Online (Sandbox Code Playgroud)

第二堆

export interface SecondStackProps extends cdk.StackProps {
    readonly apiGateway: apig.IResource;
}

export class SecondStack extends cdk.Stack {
    constructor(scope: cdk.Construct, id: string, props: SecondStackProps) {
        super(scope, id, props);

        props.apiGateway.addMethod('ANY')

    }
}
Run Code Online (Sandbox Code Playgroud)

Gaa*_*far 1

目前似乎除了使用 Cfn 构造之外没有其他办法,这是 github 问题来跟踪https://github.com/aws/aws-cdk/issues/1477