LoginSignup
2
0

More than 3 years have passed since last update.

CloudFormationでECSへSSMから機密情報の受け渡しをする

Posted at

Infomation Source

ちょっと前のリリースですが1年経ってないので一応どういうアップデートか書いておきます

CloudFormationリリース一覧 2019/6/13 リリースの機能

AWS::ECS::TaskDefinition
ContainerDefinition プロパティタイプでは、次のプロパティを使用できます。
- Secrets プロパティを使用して、コンテナに渡すシークレットを指定します。
Tags プロパティを使用して、メタデータを分類して整理しやすくするために、タスク定義に適用します。

What's new?

ECSのタスク定義で、機密情報をSecrets Manager secretやSSM Parameter Storeから取得する方法のアップデート

Before

JSONやWebコンソールからのみ設定可能だった

After

CloudFormationでも設定可能となった

↓つまり

クラスターやサービスの定義だけでなく、タスク定義含めてCloudFormationで完結する

\うれしい/

How

該当箇所だけ抜き出すとこんなかんじ

sample1.yml
Resources:
  taskDefinition:
    Properties:
      ContainerDefinitions:
          Secrets:
            - Name: HOGE
              ValueFrom: hoge

タスク定義全体だとこんなかんじ

sample2.yml
AWSTemplateFormatVersion: 2010-09-09
Parameters:
  

Resources:
  TaskDefinition:
    Type: AWS::ECS::TaskDefinition
    Properties:
      RequiresCompatibilities:
        - FARGATE
      Cpu: 256
      Memory: 512
      ExecutionRoleArn: ecsTaskExecutionRole
      Family: !Ref TaskFamilyName
      NetworkMode: awsvpc
      ContainerDefinitions:
        - Name: !Ref TaskFamilyName
          Image: !Sub ${AWS::AccountId}.dkr.ecr.ap-northeast-1.amazonaws.com/hoge
          Command: !Ref TaskCommand
          MemoryReservation: 128
          ReadonlyRootFilesystem: true
          Secrets:
            - Name: SECURE_TEST_STRING
              ValueFrom: secure_test_string
          LogConfiguration:
            LogDriver: awslogs
            Options:
              awslogs-group: !Ref TaskLogsGroup
              awslogs-region: ap-northeast-1
              awslogs-stream-prefix: ecs

Try

SSMパラメータストアに secure_test_string とその値を登録しておきます。
image.png

そして例えばECS上で実行するpythonコードとかにこんなかんじで書いておけば値が受け取れます。

sample3.py
from logging import getLogger
from os import environ as env

logger = getLogger(__name__)

logger.info('hoge / ' + env['SECURE_TEST_STRING'])

デプロイして実行した結果↓
image.png

とれてますね :tada:

FYI

https://aws.amazon.com/jp/blogs/news/securing-credentials-using-aws-secrets-manager-with-aws-fargate/
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-properties-ecs-taskdefinition-secret.html

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