


在開發上,很多時候我們必須為不同的環境給予不同的 configure。如果使用第三方 api,還需要設定對應的 credentials。
以往貪圖方便,通常會直接在 code base 裡面指定,或是另外給定一個 .env 檔來切換不同環境所需的變數。但這會有一個缺點,假如今天有一個設定值必須修改,因為我們把設定 hard code 的情況下,變成必須重新上一版才能解決,耗時又費工。同時如果把 credentials 也寫入檔案上 git 的話,也會有資安上的風險。
如果是使用 kubernetes 來做管理的話,可以使用它提供的 config map 和 secrets 來解決。但如果還沒導入 kubernets,有別的通用解決方案嗎?他就是今天要討論的 AWS Paremeter Store。
建立 Parameter
AWS Parameter Store 的 console 頁面歸類在 AWS System Manager 下



點入後就可以使用右上角的按鈕 Create parameter






首先必須為此變數取名字,這邊我推薦使用 slash 間隔的方式來取名。 比如說,我要為 dev 環境下的 koding-work-service 設定他的 db name,就可以使用以下的格式設定:
/dev/microservice/koding-work-service/db/db_name/
每個人的命名方式不同,精神上只要清晰明瞭即可。
往下看有三種不同的 type,主要注意的是 String 和 SecureString。一般 configure 等不需要加密的設定可以使用 String type。但如果是 api token 等 credentials 需要加密,就必須選擇 Secure String type。
假如點選 Secure String type,會跳出 KMS key store 設定,保留使用 My current account 即可。



最後就在 value 中填入對應值,點擊 Create Parameter 即可。
給予 Parameter 權限
要讓 Application 能夠讀取 Parameter Store,我們必須給予適當的權限。首先到 IAM 中,建立一個 Parameter Store read only 的 Policy。其中 Resource 欄位依需求給定。
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "VisualEditor0",
"Effect": "Allow",
"Action": [
"ssm:GetParameters",
"ssm:GetParameter"
],
"Resource": "arn:aws:ssm:ap-southeast-1:xxxxxx:parameter/*"
}
]
}
假設 application 跑在 EC2 上面,我們只需要到對應機器的 EC2 role 中 attach 剛剛新建立好的 Policiy 即可。
透過 boto3 取得 parameter
透過 boto3 中的 ssm client 呼叫 get_parameter() 即可取得參數值。因為在抓參數時通常會同時抓 String 或者是 Secure String,為了方便我會直接給定 WithDecryption=True,這樣兩種 type 都可以順利抓取不出錯。
import boto3
ssm = boto3.client('ssm', region_name=’xxxx’)
param = ssm.get_parameter(Name=’<key_name>’’, WithDecryption=True)['Parameter']['Value']
如此即完成參數外置!趕快試試看吧!
延伸閱讀:
AWS CloudWatch logs 攻略
拯救脆弱系統 – 使用 CloudFront 轉址