我在AWS控制台上为我的一个EC2实例创建了一个标记。
但是,当我查看服务器时,没有设置这样的环境变量。
同样的事情也适用于弹性豆茎。env
显示我在控制台上创建的标签。
$ env
[...]
DB_PORT=5432
如何在Amazon EC2中设置环境变量?
您可以从元数据中检索此信息,然后运行您自己的设置环境命令。
您可以从元数据中获取instent-id(详细信息请参见此处:http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-metadata.html#instancedata-data-retrieval)
curl http://169.254.169.254/latest/meta-data/instance-id
然后,您可以使用预装的AWSCLI(或将其安装在AMI上)调用描述标签
aws ec2 describe-tags --filters "Name=resource-id,Values=i-5f4e3d2a" "Name=Value,Values=DB_PORT"
然后可以使用OS设置环境变量命令
export DB_PORT=/what/you/got/from/the/previous/call
您可以在用户数据脚本中运行所有这些。有关详细信息,请参见此处:http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html
最近,似乎AWS参数存储是一个更好的解决方案。
现在甚至有一个秘密管理器,可以自动管理敏感配置,如数据库密钥等。
请参阅此脚本,该脚本使用基于Guy和PJ Bergeron之前解决方案的SSM参数存储。
https://github.com/lezavala/ec2-ssm-env
我使用了以下工具的组合:
下面是代码的要点,以防我将来更新它:https://gist.github.com/marcellodesales/a890b8ca240403187269
######
# Author: Marcello de Sales (marcello.desales@gmail.com)
# Description: Create Create Environment Variables in EC2 Hosts from EC2 Host Tags
#
### Requirements:
# * Install jq library (sudo apt-get install -y jq)
# * Install the EC2 Instance Metadata Query Tool (http://aws.amazon.com/code/1825)
#
### Installation:
# * Add the Policy EC2:DescribeTags to a User
# * aws configure
# * Souce it to the user's ~/.profile that has permissions
####
# REboot and verify the result of $(env).
# Loads the Tags from the current instance
getInstanceTags () {
# http://aws.amazon.com/code/1825 EC2 Instance Metadata Query Tool
INSTANCE_ID=$(./ec2-metadata | grep instance-id | awk '{print $2}')
# Describe the tags of this instance
aws ec2 describe-tags --region sa-east-1 --filters "Name=resource-id,Values=$INSTANCE_ID"
}
# Convert the tags to environment variables.
# Based on https://github.com/berpj/ec2-tags-env/pull/1
tags_to_env () {
tags=$1
for key in $(echo $tags | /usr/bin/jq -r ".[][].Key"); do
value=$(echo $tags | /usr/bin/jq -r ".[][] | select(.Key==\"$key\") | .Value")
key=$(echo $key | /usr/bin/tr '-' '_' | /usr/bin/tr '[:lower:]' '[:upper:]')
echo "Exporting $key=$value"
export $key="$value"
done
}
# Execute the commands
instanceTags=$(getInstanceTags)
tags_to_env "$instanceTags"