簡體   English   中英

如何在 Amazon EC2 中設置環境變量

[英]How to set an environment variable in Amazon EC2

我在 AWS 控制台上為我的一個 EC2 實例創建了一個標簽。

在此處輸入圖片說明

但是,當我查看服務器時,沒有設置這樣的環境變量。

同樣的事情適用於彈性豆莖。 env顯示我在控制台上創建的標簽。

$ env
 [...]
 DB_PORT=5432

如何在 Amazon EC2 中設置環境變量?

您可以從元數據中檢索此信息,然后運行您自己的設置環境命令。

您可以從元數據中獲取實例 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

然后您可以使用預安裝的 AWS CLI 調用 describe-tags(或將其安裝在您的 AMI 上)

aws ec2 describe-tags --filters "Name=resource-id,Values=i-5f4e3d2a" "Name=Value,Values=DB_PORT"

然后你可以使用操作系統設置環境變量命令

export DB_PORT=/what/you/got/from/the/previous/call

您可以在用戶數據腳本中運行所有這些。 有關詳細信息,請參見此處: http : //docs.aws.amazon.com/AWSEC2/latest/UserGuide/user-data.html

我使用了以下工具的組合:

  • 安裝 jq 庫(sudo apt-get install -y jq)
  • 安裝 EC2 實例元數據查詢工具

這是下面代碼的要點,以防我將來更新它: 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"

最近,AWS Parameter Store 似乎是一個更好的解決方案。

現在甚至還有一個秘密管理器,它可以自動管理敏感配置,如數據庫密鑰等。

請參閱使用基於GuyPJ Bergeron先前解決方案的 SSM 參數存儲的腳本。

https://github.com/lezavala/ec2-ssm-env

按照Guy給出的說明,我編寫了一個小的 shell 腳本。 此腳本使用 AWS CLI 和jq 它允許您將 AWS 實例和 AMI 標簽作為 shell 環境變量導入。

我希望它可以幫助一些人。

https://github.com/12moons/ec2-tags-env

我通常通過運行UserData腳本在啟動時將標記加載為環境變量。 根據實例,我將--query--filter參數更改為describe-instances調用,否則腳本保持不變。 注意 :以下示例排除標記Name和包含以下內容的標記: - 更改此行為以滿足您的需要。

#!/bin/bash -v
apt-get update
apt-get -y install awscli

# add boot script which loads environment variables
cat > /etc/profile.d/export_instance_tags.sh << 'EndOfMessage'
# fetch instance info
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
INSTANCE_AZ=$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone)
INSTANCE_REGION="`echo \"$INSTANCE_AZ\" | sed -e 's:\([0-9][0-9]*\)[a-z]*\$:\\1:'`"

# export instance tags
export_statement=$(aws ec2 describe-tags --region "$INSTANCE_REGION" --filters "Name=resource-id,Values=$INSTANCE_ID" --query 'Tags[?!contains(Key, `Name`) && !contains(Key, `:`)].[Key,Value]' --output text | sed -E 's/^([^\s\t]+)[\s\t]+([^\n]+)$/export \1="\2"/g')
eval $export_statement

# export instance info
export INSTANCE_ID
export INSTANCE_AZ
export INSTANCE_REGION
EndOfMessage

它運行describe-tags列出所有標簽,使用sed將輸出重新格式化為一系列導出語句,然后使用eval運行結果

如果您的 ec2 實例使用的是 linux 或 mac os,那么,

轉到您的根目錄並寫入命令:

vim .bash_profile

你可以看到你的 bash_profile 文件,現在按“i”插入一行,然后添加

export DB_PORT="5432"

添加此行后,您需要保存文件,因此按“Esc”按鈕然后按“:”,在冒號寫入“w”后,它將保存文件而不退出。

對於退出,再次按 ':',然后寫 'quit',現在您從文件中退出。 要檢查您的環境變量是否已設置,請編寫以下命令:

python
>>>import os
>>>os.environ.get('DB_PORT')
>>>5432 

有兩種方法可以做到這一點,這對每個人來說都更容易理解。

===== 1. 持久化存儲環境變量的方式 ======

重新啟動 EC2 實例后,這些環境變量也將保留(持續存在)。

每當進入 bash 登錄 shell 時(例如從控制台或通過 ssh 登錄時),就會執行/etc/profile.d目錄中帶有 .sh 擴展名的/etc/profile.d ,並在桌面會話加載時由 DisplayManager 執行。

例如,您可以使用以下命令創建文件/etc/profile.d/my_env_vars.sh

  1. cd / - 進入根目錄

  2. cd etc/profile.d/ - 進入 profile.d 目錄

  3. sudo touch my_env_vars.sh - 創建你自己的文件來存儲沒有sudo環境變量你不能在這個目錄中創建文件

  4. sudo vi techflare_env.sh - 編輯文件以打開

    • 現在按i鍵進入INSERT模式
    • 粘貼您的環境變量,如下所示

    export MONGODB_URI=mongodb+srv://hello:easy.lqyny.mongodbnet/mydb
    export PORT=5000

    • 現在按Esc鍵並輸入:wq保存並退出
    • 最后按Enter完成。
  5. 您可以using cat my_env_vars.sh命令查看文件。

  6. 要激活環境變量,您需要一個 Reboot(Restarting) 實例。

  7. 重新啟動(重新啟動)后,您可以使用printenv命令查看所有環境變量。

===== 2. 使用shell的臨時環境變量 =====

  • 重新啟動實例后,這些都消失了。
  • 只需輸入終端並export PORT=5000Enter
  • 重啟后這些環境變量會丟失。

我從這篇文章here中找到了這個。 閱讀本文並提高您的知識...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM