0
2

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.

Python で parameter store を使う

Posted at

はじめに

以前、仕事で使った Parameter Store(AWS Systems Manager) をまた使うことになったので思い出しました。

今回もPoetry + Dockerを開発環境にしています。
ソースは Github にあげてあります。

Parameter Store を設定する

/aaa で始まるように作成
スクリーンショット 2020-10-19 16.58.17.png

ファイル

mainとライブラリとしてファイルを分けています。

main.py

from src.ssm_manager import SsmManager

print("start")

ssm_manager = SsmManager(region_name="ap-northeast-1")
ssm_manager.load_parameter(base_ssm_path="/aaa")
print(ssm_manager.parameters)
ssm_manager.py
from typing import List, Dict

import boto3


class SsmManager:
    def __init__(self, region_name: str):
        self.__ssm = boto3.client('ssm', region_name=region_name)
        self.__parameters = []
        self.__base_ssm_path = None

    @property
    def parameters(self) -> List[Dict[str, any]]:
        return [{
            'name': item['Name'].replace(f'{self.__base_ssm_path}/', ''),
            'value': item['Value']
        } for item in self.__parameters]

    def load_parameter(self, base_ssm_path: str) -> None:
        self.__base_ssm_path = base_ssm_path
        result = []
        next_token = None
        while True:
            dict_parameter = {
                'Path': base_ssm_path,
                'Recursive': True,
                'WithDecryption': True,
            }
            if next_token is not None:
                dict_parameter['NextToken'] = next_token
            response = self.__ssm.get_parameters_by_path(**dict_parameter)
            parameters = response['Parameters']
            result.extend(parameters)
            if 'NextToken' not in response:
                break
            next_token = response['NextToken']
        self.__parameters = result

終わりに

これで、環境変数などに入れていたRDSのパスワードなどを保存できます。

0
2
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
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?