💸

【AWS】タグ漏れを許さない!AWS Configによる自動修正の魔法

に公開

こんにちは、EDUCOMの新卒3年目、とよだです! 前回、IAMポリシーで「タグなしリソースは作らせない」設定を紹介しましたが……実は、導入後に 「設定のすり抜け」 が見つかりました...。

今回は、その失敗をどう乗り越えたかをお話しします!

1. 発覚した「すり抜け」の正体

コスト管理も万全!と思ってCost Explorerを眺めていたら、衝撃の光景が。 「タグなし(No TagKey: Owner)」の課金がガッツリ残っている……!

特に多かったのが、APN1-EBS:VolumeUsage.gp2(EBSボリューム)でした。 原因は、EC2起動時(RunInstances)にボリューム側の指定が漏れていたこと。

「入り口で防げないなら、 中に入った後に自動で捕まえて直せばいいじゃない! 」

というわけで、今回はAWS Configを使った自動修正にチャレンジしました。 (せっかくなので触ったことない機能を触ってみたいという下心も半分です(笑))

EC2起動時(RunInstances)に作成されるVolumeへのタグ付けも強制する場合はこちら

Ownerタグをつけることを強制

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "DenyRunInstancesWithVolumeWithoutOwnerTagOnInstance",
            "Effect": "Deny",
            "Action": "ec2:RunInstances",
            "Resource": "arn:aws:ec2:*:*:volume/*",
            "Condition": {
                "Null": {
                    "aws:RequestTag/Owner": "true"
                }
            }
        }
    ]
}

2. AWS Config × Automation で「自動検知・即修正」

「タグがない」という非準拠リソースを見つけ、即座にタグを付与する仕組みです。

構成図

構成イメージ

1. AWS Configが required-tags ルールで、タグのないEBSを検知。

2. Systems Manager (SSM) Automation を自動修復アクションとして呼び出し。

3. Automation Document がインスタンスのタグを読み取って、ボリュームへコピー!

Automation Document は aws:executeAwsApi と aws:executeScript を使用して、以下の処理(※)を実行します。

  • EBS ボリュームに関する情報を取得
  • EBS ボリュームがアタッチされているインスタンスからタグ情報を取得
  • 取得したタグをEBS ボリュームへつける
  • 正しいタグが付いたかを確認する
※処理の構成と内容(YAML)

schemaVersion: '0.3'
description: |
  Attach the 'Owner' tag to an EBS volume based on the attached EC2 instance's Owner tag.
assumeRole: '{{ AutomationAssumeRole }}'
parameters:
  VolumeId:
    type: String
    description: The ID of the EBS volume to tag.
  AutomationAssumeRole:
    type: String
    description: (Optional) The IAM role that allows Automation to perform the actions.
    default: ''
mainSteps:
  - description: Get the EC2 instance ID attached to the volume.
    name: GetInstanceId
    action: aws:executeAwsApi
    nextStep: GetOwnerTagFromInstance
    isEnd: false
    inputs:
      Service: ec2
      Api: DescribeVolumes
      VolumeIds:
        - '{{ VolumeId }}'
    outputs:
      - Name: InstanceId
        Selector: $.Volumes[0].Attachments[0].InstanceId
        Type: String
  - description: Get the 'Owner' tag from the attached EC2 instance.
    name: GetOwnerTagFromInstance
    action: aws:executeAwsApi
    nextStep: TagVolume
    isEnd: false
    inputs:
      Service: ec2
      Api: DescribeTags
      Filters:
        - Name: resource-id
          Values:
            - '{{ GetInstanceId.InstanceId }}'
        - Name: key
          Values:
            - Owner
    outputs:
      - Name: OwnerTagValue
        Selector: $.Tags[0].Value
        Type: String
  - description: Apply the retrieved Owner tag to the EBS volume.
    name: TagVolume
    action: aws:executeAwsApi
    nextStep: VerifyTag
    isEnd: false
    inputs:
      Service: ec2
      Api: CreateTags
      Resources:
        - '{{ VolumeId }}'
      Tags:
        - Key: Owner
          Value: '{{ GetOwnerTagFromInstance.OwnerTagValue }}'
  - description: Verify that the Owner tag was successfully applied.
    name: VerifyTag
    action: aws:executeScript
    isEnd: true
    inputs:
      Runtime: python3.11
      Handler: script_handler
      InputPayload:
        volume_id: '{{ VolumeId }}'
      Script: |
        import boto3

        def script_handler(event, context):
            ec2 = boto3.client('ec2')
            res = ec2.describe_tags(
                Filters=[
                    {'Name': 'resource-id', 'Values': [event['volume_id']]},
                    {'Name': 'key', 'Values': ['Owner']}
                ]
            )

            tags = res.get('Tags', [])
            if not tags:
                raise Exception("Owner tag was not applied correctly.")

            return {
                "status": "success",
                "volume_id": event['volume_id'],
                "owner_tag": tags[0]['Value']
            }

やっていること:

  • GetInstanceId: ボリュームの接続先インスタンスIDを特定
  • GetOwnerTagFromInstance: インスタンスからOwnerタグの値を取得
  • TagVolume: 取得した値をボリュームに書き込み
  • VerifyTag: Pythonスクリプトで正しく付与されたか最終確認

3. Configの設定手順

設定はマネジメントコンソールから数ステップで完了します。

①Configルール

まず、required-tags ルールを追加します。

  • リソースタイプ: AWS EC2 Volume を選択。
  • パラメータ: tag1Key に Owner を指定。ルールを追加

details CLI上で確認

~ $ aws configservice describe-config-rules --output yaml
ConfigRules:
- ConfigRuleArn: arn:aws:config:ap-northeast-1:XXXXXXXXXXX:config-rule/config-rule-nbm5cv
  ConfigRuleId: config-rule-nbm5cv
  ConfigRuleName: required-tags
  ConfigRuleState: ACTIVE
  Description: Checks whether your resources have the tags that you specify.
  EvaluationModes:
  - Mode: DETECTIVE
  InputParameters: '{"tag1Key":"Owner"}'
  Scope:
    ComplianceResourceTypes:
    - AWS::EC2::Volume
    - AWS::Events::Rule
  Source:
    Owner: AWS
    SourceIdentifier: REQUIRED_TAGS

:::

②自動タグ付け用Automation Document を作成

SystemManagerのドキュメントから任意の名前でドキュメントを作成してください

Automation Document用のYAMLファイル
schemaVersion: '0.3'
description: |
  Attach the 'Owner' tag to an EBS volume based on the attached EC2 instance's Owner tag.
assumeRole: '{{ AutomationAssumeRole }}'
parameters:
  VolumeId:
    type: String
    description: The ID of the EBS volume to tag.
  AutomationAssumeRole:
    type: String
    description: (Optional) The IAM role that allows Automation to perform the actions.
    default: ''
mainSteps:
  - description: Get the EC2 instance ID attached to the volume.
    name: GetInstanceId
    action: aws:executeAwsApi
    nextStep: GetOwnerTagFromInstance
    isEnd: false
    inputs:
      Service: ec2
      Api: DescribeVolumes
      VolumeIds:
        - '{{ VolumeId }}'
    outputs:
      - Name: InstanceId
        Selector: $.Volumes[0].Attachments[0].InstanceId
        Type: String
  - description: Get the 'Owner' tag from the attached EC2 instance.
    name: GetOwnerTagFromInstance
    action: aws:executeAwsApi
    nextStep: TagVolume
    isEnd: false
    inputs:
      Service: ec2
      Api: DescribeTags
      Filters:
        - Name: resource-id
          Values:
            - '{{ GetInstanceId.InstanceId }}'
        - Name: key
          Values:
            - Owner
    outputs:
      - Name: OwnerTagValue
        Selector: $.Tags[0].Value
        Type: String
  - description: Apply the retrieved Owner tag to the EBS volume.
    name: TagVolume
    action: aws:executeAwsApi
    nextStep: VerifyTag
    isEnd: false
    inputs:
      Service: ec2
      Api: CreateTags
      Resources:
        - '{{ VolumeId }}'
      Tags:
        - Key: Owner
          Value: '{{ GetOwnerTagFromInstance.OwnerTagValue }}'
  - description: Verify that the Owner tag was successfully applied.
    name: VerifyTag
    action: aws:executeScript
    isEnd: true
    inputs:
      Runtime: python3.11
      Handler: script_handler
      InputPayload:
        volume_id: '{{ VolumeId }}'
      Script: |
        import boto3

        def script_handler(event, context):
            ec2 = boto3.client('ec2')
            res = ec2.describe_tags(
                Filters=[
                    {'Name': 'resource-id', 'Values': [event['volume_id']]},
                    {'Name': 'key', 'Values': ['Owner']}
                ]
            )

            tags = res.get('Tags', [])
            if not tags:
                raise Exception("Owner tag was not applied correctly.")

            return {
                "status": "success",
                "volume_id": event['volume_id'],
                "owner_tag": tags[0]['Value']
            }

③ 修復アクションの設定

Configルールの「アクション」から「修復の管理」を選択します。 ここで、作成した Automation Document を紐付ければ準備完了! これで「タグなしボリューム」が見つかるたびに、裏側でこっそり直してくれるようになります。

💡 ハマりポイント:IAMロールの「信頼関係」

Automationを実行するロールには、ポリシーだけでなく「信頼関係」の設定も忘れずに!
ssm.amazonaws.com がこのロールを引き受けられる(AssumeRole)ように設定しておく必要があります。

AssumeRole

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "",
            "Effect": "Allow",
            "Principal": {
                "Service": "ssm.amazonaws.com"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

許可Policy

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeVolumes",
                "ec2:DescribeTags",
                "ec2:CreateTags"
            ],
            "Resource": "*"
        }
    ]
}

動作確認

Config設定後に非準拠のリソース(指定したタグがないVolume)を確認

Automation Document が実行されていることを確認

成功!! Configにて非準拠から準拠に代わっていることを確認

まとめ:仕組みで解決するのが一番!

実際に導入したところ、これまで手動で直していたのが嘘のように、Cost Explorerから「タグなしボリューム」のグラフが消えていきました。

「ルールを守ってもらう」努力も大事ですが、「システムがそっと助けてくれる」 仕組みがあると、運用が本当に楽になりますね。

EDUCOM Tech Blog

Discussion