cdk api gateway route53 лямбда-пользовательское доменное имя не работает - PullRequest
0 голосов
/ 02 августа 2020

Были заданы похожие вопросы, но ни один из них не смог помочь мне решить проблему, с которой я столкнулся. Я пытаюсь подключить мою функцию api-gateway / lamnda к пользовательскому доменному имени, и по какой-то причине при вызове api / domain не возвращается то, что я ожидал.

cdk version: 1.53.0

    const lambdaFunction = new lambda.Function(this, 'LambdaApi', {
      functionName: 'lambda-api',
      handler: 'lambda.handler',
      runtime: lambda.Runtime.NODEJS_12_X,
      code: new lambda.AssetCode(join(process.cwd(), '../api/dist')),
      memorySize: 128,
      timeout: cdk.Duration.seconds(5),
    })

    const zone = route53.HostedZone.fromLookup(scope, 'Zone', {
     'example.com',
     privateZone: false,
    })

    const certificate = certificatemanager.Certificate.fromCertificateArn(
     this,
     'Certificate',
     CERT_ARN,
    )

    const api = new apigateway.LambdaRestApi(this, 'LambdaApiGateway', {
      handler: lambdaFunction,
      proxy: true,
      endpointTypes: [apigateway.EndpointType.EDGE],
      defaultCorsPreflightOptions: {
        allowOrigins: apigateway.Cors.ALL_ORIGINS,
      },
      options: {
        restApiName: 'gateway-api',
        domainName: {
          domainName: 'api.example.com',
          certificate,
        },
        deployOptions: {
          stageName: 'prod',
          metricsEnabled: true,
          loggingLevel: apigateway.MethodLoggingLevel.INFO,
          dataTraceEnabled: true,
        },
      },
    })

    new route53.ARecord(this, 'CustomDomainAliasRecord', {
      zone,
      recordName: 'api',
      target: route53.RecordTarget.fromAlias(new targets.ApiGateway(api)),
    })

Процесс развертывания работает нормально, ARecord создается на route53, который указывает на доменное имя api-gateway, создаются сопоставления api, также указывающие на prod, как указано в stageName, но когда вызов имени домена не работает, но при вызове конечной точки api-gateway он работает.

api.example.com/ping возвращает healthy

{id}.execute-api.us-east-1.amazonaws.com/prod/ping возвращает текущую дату

Изучал, но я не могу понять, почему api.example.com/ping не работает

Ответы [ 2 ]

1 голос
/ 27 августа 2020

По большей части мы сделали то, что вы там делаете, но после создания зоны и сертификата у нас получилось что-то вроде этого:

const customDomain = new DomainName(this, 'customDomain', {
    domainName: 'api.example.com',
    certificate: certificate,
    endpointType: EndpointType.REGIONAL // yours may be Edge here
})

Мы также используем basePathMapping, поэтому мы не необходимо использовать "dev | stg | prod" в конце домена.

new BasePathMapping(this, 'CustomBasePathMapping', {
    domainName: customDomain,
    restApi: api // again yours may differ here
})
0 голосов
/ 31 августа 2020

Я исправил облачным распределением, вот код.

const api = new apigateway.LambdaRestApi(
  this,
  'lambda-api-gateway',
  {
    handler: lambdaFunction,
    proxy: true,
    endpointTypes: [apigateway.EndpointType.EDGE],
    defaultCorsPreflightOptions: {
      allowOrigins: apigateway.Cors.ALL_ORIGINS,
      allowMethods: apigateway.Cors.ALL_METHODS,
    },
    options: {
      restApiName: 'gateway-api',
      domainName: {
        domainName,
        certificate,
      },
      deployOptions: {
        stageName: props.stageName,
        metricsEnabled: true,
        loggingLevel: apigateway.MethodLoggingLevel.INFO,
        dataTraceEnabled: true,
      },
    },
  },
)

const distribution = new cloudfront.CloudFrontWebDistribution(
  this,
  'api-cloudfront-distribution',
  {
    defaultRootObject: '/',
    originConfigs: [
      {
        customOriginSource: {
          domainName: `${api.restApiId}.execute-api.${this.region}.${this.urlSuffix}`,
        },
        originPath: `/${props.stageName}`,
        behaviors: [
          {
            allowedMethods: cloudfront.CloudFrontAllowedMethods.ALL,
            isDefaultBehavior: true,
            forwardedValues: {
              cookies: {
                forward: 'all',
              },
              queryString: true,
            },
          },
        ],
      },
    ],
    enableIpV6: true,
    viewerCertificate: cloudfront.ViewerCertificate.fromAcmCertificate(
      certificate,
      {
        aliases: [domainName],
        securityPolicy: cloudfront.SecurityPolicyProtocol.TLS_V1,
        sslMethod: cloudfront.SSLMethod.SNI,
      },
    ),
  },
)

const zone = zoneFromLookUp(this, props.zoneDomainName)
const target = route53.RecordTarget.fromAlias(
  new targets.CloudFrontTarget(distribution),
)

new route53.ARecord(this, 'arecord-api', {
  zone,
  recordName: domainName,
  target,
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...