在 AWS Elastic Beanstalk 中使用 SSM 参数存储

问题描述 投票:0回答:2

我正在使用AWS Elastic beanstalk,想要为不同的环境配置不同的ENV var。我发现的唯一方法是使用 ebextensions,但是如果我将同一个数据包部署到多个环境,则在 ebextension 中设置的环境变量无法被覆盖。听说过 SSM 参数存储,但无法找到与 Elastic Beanstalk 一起使用的方法。

我发现 SSM 参数存储可以为 EC2 实例做到这一点。我不想每次更新一个环境变量时都重新启动 EC2 实例。还考虑编写一个脚本,从 SSM 获取值并更新 ebextentsions 中的环境变量。但这似乎只是一种黑客攻击,而不是正确的解决方案,需要检查可能失败的场景

amazon-elastic-beanstalk aws-parameter-store
2个回答
2
投票

我不会考虑你提出的解决方案。我们有多种服务遵循类似的模式,而且非常有效。

看看ssm-env。您应该在 ebextensions 中使用此工具,而不是尝试重建功能。


1
投票

我找到了一个使用钩子的解决方案,我创建了两个钩子,第一个钩子位于 hooks 文件夹中,另一个位于 hooksconfig 中(请参阅附图)。我在两个文件夹中添加相同的 bash 脚本的原因很简单,我们希望在新部署期间获取环境变量,并且如果更新了 configuration->software 环境变量,我们还需要获取这些变量(我们可以添加环境变量)参数存储和 EB 配置这两个地方的变量)。

这段代码的灵感来自于this articlehttps://www.fullstackerconsulting.com/2021/09/09/how-can-i-use-the-aws-systems-manager-parameter-store-with-an-aws-elastic-beanstalk-instance-to -管理环境变量/

map_parameters_to_env_vars.sh

Here is the code (the same for both files)



   #!/usr/bin/env bash
    
    ## https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/platforms-linux-extend.html

    readarray eb_env_vars < /opt/elasticbeanstalk/deployment/env

    # Check if parameter_store_path is an environment variable and get its value.

for i in ${eb_env_vars[@]}
do
  if [[ $i == *"parameter_store_path"* ]]; then
    parameter_store_path=$(echo $i | grep -Po "([^\=]*$)")
  fi
done

if [ -z ${parameter_store_path+x} ]; then
  echo "Error: parameter_store_path is unset on the Elastic Beanstalk environment properties.";
  echo "You must add a property named parameter_store_path with the path prefix to your SSM parameters.";
else
  echo "Success: parameter_store_path is set to '$parameter_store_path'";

  TOKEN=`curl -X PUT http://169.254.169.254/latest/api/token -H "X-aws-ec2-metadata-token-ttl-seconds:21600"`
  AWS_DEFAULT_REGION=`curl -H "X-aws-ec2-metadata-token:$TOKEN" -v http://169.254.169.254/latest/meta-data/placement/region`

  export AWS_DEFAULT_REGION

  #Create a copy of the environment variable file.
  cp /opt/elasticbeanstalk/deployment/env /opt/elasticbeanstalk/deployment/custom_env_var

  # Add values to the custom file
  echo "AWS_DEFAULT_REGION=$AWS_DEFAULT_REGION" >> /opt/elasticbeanstalk/deployment/custom_env_var

**## Change the region with the one you added your parameters.**

  aws ssm get-parameters-by-path \
  --path $parameter_store_path \
  --with-decryption \
  --region **eu-west-2** \
  | jq --arg path "$parameter_store_path" \
  -r  '.Parameters | .[] | "\(.Name | sub($path; ""))=\(.Value)"' >> /opt/elasticbeanstalk/deployment/custom_env_var

  cp /opt/elasticbeanstalk/deployment/custom_env_var /opt/elasticbeanstalk/deployment/env

  #Remove temporary working file.
  rm -f /opt/elasticbeanstalk/deployment/custom_env_var

  #Remove duplicate files upon deployment.
  rm -f /opt/elasticbeanstalk/deployment/*.bak

fi

我们还需要在 EB 环境中的configuration->software中添加一个环境变量。

© www.soinside.com 2019 - 2024. All rights reserved.