You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过CDK获取AppSync自动生成的子域名并存为SSM参数

提取AppSync API子域名并保存为SSM参数

你可以通过CloudFormation内置的字符串处理函数,直接在CDK中对令牌值进行拆分提取,无需等待合成完成。具体实现步骤如下:

  • 拆分GraphQL URL获取子域名
    使用CDK封装的Fn.split函数,分两次拆分api.graphqlUrl:

    // 第一步:移除https://前缀,取拆分后的第二部分
    const urlWithoutProtocol = cdk.Fn.split("https://", api.graphqlUrl)[1];
    // 第二步:以.appsync-api为分隔符,取第一部分即目标子域名
    const appSyncSubdomain = cdk.Fn.split(".appsync-api", urlWithoutProtocol)[0];
    
  • 将子域名存入SSM参数
    实例化ssm.StringParameter,把提取出的子域名作为参数值保存:

    new ssm.StringParameter(this, "AppSyncSubdomainParam", {
      parameterName: "/your/custom/path/appsync-subdomain",
      stringValue: appSyncSubdomain,
      description: "AppSync API的子域名XXXXX部分",
    });
    

完整的Stack示例代码:

import * as cdk from "aws-cdk-lib";
import * as appsync from "aws-cdk-lib/aws-appsync";
import * as ssm from "aws-cdk-lib/aws-ssm";
import { Construct } from "constructs";

export class AppSyncSubdomainStack extends cdk.Stack {
  constructor(scope: Construct, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // 创建AppSync API实例
    const api = new appsync.GraphqlApi(this, "DemoApi", {
      name: "DemoAppSyncApi",
      schema: appsync.SchemaFile.fromAsset("./schema.graphql"),
      authorizationConfig: {
        defaultAuthorization: {
          authorizationType: appsync.AuthorizationType.API_KEY,
        },
      },
    });

    // 提取子域名
    const urlWithoutProtocol = cdk.Fn.split("https://", api.graphqlUrl)[1];
    const appSyncSubdomain = cdk.Fn.split(".appsync-api", urlWithoutProtocol)[0];

    // 保存到SSM
    new ssm.StringParameter(this, "AppSyncSubdomain", {
      parameterName: "/appsync/demo/subdomain",
      stringValue: appSyncSubdomain,
    });
  }
}

原理说明

CDK令牌对应CloudFormation的动态参数引用,使用Fn.split这类内置函数可以在模板合成阶段完成字符串解析,生成的CloudFormation模板会自动在部署时解析出真实的子域名值并存入SSM,不需要额外的后置处理。

内容的提问来源于stack exchange,提问作者adrian oviedo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 02:30:39