如何使用 cli 更新云端分发中的 lambda@edge arn

How to update lambda@edge arn in cloudfront distribution using cli

我想使用 CLI 使用最新的 lambda@edge 函数更新云端分发。

我看到了这个文档https://docs.aws.amazon.com/cli/latest/reference/cloudfront/update-distribution.html

但无法弄清楚如何仅更新 lambda arn。

谁能帮忙

could not figure out how to update the lambda arn only.

您提供的link说明了过程:

The update process includes getting the current distribution configuration, updating the XML document that is returned to make your changes, and then submitting an UpdateDistribution request to make the updates.

这意味着您不能直接更新 lambda arn。你有:

  1. 调用get-distribution-config获取完整的当前配置。

  2. 更改获取的配置数据中的lambda arn。

  3. 使用 update-distribution 上传整个新配置。

该过程需要额外注意,文档中也有解释 under 警告:

You must strip out the ETag parameter that is returned.

Additional fields are required when you update a distribution.

等等。

过程确实复杂。因此,如果可以的话,我建议您在某些 test/dummy CloudFront 发行版上进行尝试,而不是直接在生产版本上进行尝试。

像这样:

#!/bin/bash
set -x
TEMPDIR=$(mktemp -d)
CONFIG=$(aws cloudfront get-distribution-config --id CGSKSKLSLSM)
ETAG=$(echo "${CONFIG}" | jq -r '.ETag')
echo "${CONFIG}" | jq '.DistributionConfig' > ${TEMPDIR}/orig.json
echo "${CONFIG}" | jq '.DistributionConfig | .DefaultCacheBehavior.LambdaFunctionAssociations.Items[0].LambdaFunctionARN= "arn:aws:lambda:us-east-1:xxxxx:function:test-func:3"' > ${TEMPDIR}/updated.json
aws cloudfront update-distribution --id CGSKSKLSLSM --distribution-config file://${TEMPDIR}/updated.json --if-match "${ETAG}"

这是脚本,正是这样做的。它是基于@cloudbud answer实现的。没有参数检查。它将像这样执行:./script QF234ASD342FG my-lambda-at-edge-function us-east-1。在我的例子中,执行时间少于 10 秒。有关详细信息,请参阅 update-distribution

#!/bin/bash

set -xeuo pipefail
export PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin

distribution_id=""
function_name=""
region=""

readonly lambda_arn=$(
  aws lambda list-versions-by-function \
    --function-name "$function_name" \
    --region "$region" \
    --query "max_by(Versions, &to_number(to_number(Version) || '0'))" \
  | jq -r '.FunctionArn'
)

readonly tmp1=$(mktemp)
readonly tmp2=$(mktemp)

aws cloudfront get-distribution-config \
  --id "$distribution_id" \
> "$tmp1"

readonly etag=$(jq -r '.ETag' < "$tmp1")

cat "$tmp1" \
| jq '(.DistributionConfig.CacheBehaviors.Items[] | select(.PathPattern=="dist/sxf/*") | .LambdaFunctionAssociations.Items[] | select(.EventType=="origin-request") | .LambdaFunctionARN ) |= "'"$lambda_arn"'"' \
| jq '.DistributionConfig' \
> "$tmp2"

# the dist config has to be in the file
# and be referred in specific way.
aws cloudfront update-distribution \
  --id "$distribution_id" \
  --distribution-config "file://$tmp2" \
  --if-match "$etag"

rm -f "$tmp1" "$tmp2"