0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

AWS Systems ManagerのParameter StoreからLambdaでパラメータ取得

Last updated at Posted at 2021-10-03

#パラメータの作成
パラメータの作成ボタンからパラメータを2つ作成します。
image.png


今回サンプルとして作ったパラメータの値は、テキスト型の架空のURLです。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/7195f374-0777-6d22-7080-ee26d10364ab.png)

#Lambdaの作成
①関数名とランタイムだけ変更し関数を作成します。
image.png


②設定タブ→アクセス権限→ロール名をクリックします。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/44a159b5-ac45-c892-1c01-f5e860e80f21.png)
③ポリシーをアタッチしますボタンを押します。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/7d962382-03b0-e9cc-1d74-1e390db57837.png)
④ポリシーの作成ボタンを押します。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/dd181622-3fab-c328-87e3-45f5e57a5c30.png)
⑤JSONタブを押下し下記のコードに変更し、次のステップボタンからそのまま完了まで進みます。
policy.json
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "ssm:GetParameters"
            ],
            "Resource": "*"
        }
    ]
}

⑥先ほどの③のロール画面に戻り、再びポリシーをアタッチしますボタンを押します。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/08ac543a-e217-f446-c34e-00f9aa44961b.png)
⑦先ほどの⑤で作成したポリシー名を検索し、チェックを付けポリシーのアタッチボタンを押します。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/418a804b-b775-3443-e87a-eda50eee5b1b.png)
⑧関数の画面に戻り、コードを修正します。
lambda_function.py
import json
import boto3
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)


def get_ssm_params(*keys, region='ap-northeast-1'):
    result = {}
    ssm = boto3.client('ssm', region)
    response = ssm.get_parameters(
        Names=keys,
        WithDecryption=True,
    )
    
    for p in response['Parameters']:
        result[p['Name']] = p['Value']
    
    return result


def lambda_handler(event, context):
    parameters = get_ssm_params('sample-url', 'sample-url2')
    logger.info(parameters['sample-url'])
    logger.info(parameters['sample-url2'])

⑨deployボタンを押してtestボタンを押すと、logでパラメータの値が取れているのが確認できます。 ![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/630191/8e5f3146-1765-718a-80a9-8f5c1bf451a9.png)
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?