CodePipelineのDeploy行程で「PermissionError The provided role does not have sufficient permissions to access ECS」エラーが出る時の対応メモ

概要

CodePipelineのDeployでデプロイメントプロバイダにAmazon ECSを選択して実施し、失敗した時に「PermissionError The provided role does not have sufficient permissions to access ECS」エラーとなった

原因

CodePipelineに設定していたサービスロールに権限が足りていなかった

対応

CodePipeline用のサービスロールにiam:PassRoleを付けていたがConditionによってサービスを制限しており、その中に「ecs-tasks.amazonaws.com」を含める必要があった
具体的は下記の「ecs-tasks.amazonaws.com」が無かったので追加した

  CodePipelineServiceRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: mytestServiceRole
      Policies:
        - PolicyName: mytestServiceRolePolicy
          PolicyDocument:
            Statement:
              - Action:
                  - iam:PassRole
                Resource: "*"
                Effect: Allow
                Condition:
                  StringEqualsIfExists:
                    iam:PassedToService:
                      - cloudformation.amazonaws.com
                      - elasticbeanstalk.amazonaws.com
                      - ec2.amazonaws.com
                      - ecs-tasks.amazonaws.com

※上記はCloudFormationの記述で、一部抜粋である点に注意

公式ページに書いてある内容がより詳細なのでメモ
docs.aws.amazon.com

メモ

どこに何をしたら良いか分からなくなった時、CloudTrailを使って背後で動いている処理を確認できる

  • CloudTrailを設定しておく(特に制限せずに全体をウォッチしておく)
  • エラーが起きる処理(今回であればCodePipelineでのリリース動作)を実施してエラーさせる
    • この時、だいたいの日時をメモしておく
  • CloudTrailの出力がS3に入るので最終更新日時から大体の予測を付けて中を確認する
    • S3への反映には数分かかる、最終更新日時が前述でメモした日時を含むファイルの1個後のファイルで出ている事が多い
  • jsonの「eventTime」から前述でメモした日時に近いものを探す
    • 「errorMessage」と合わせて探すと効率が良い
  • 該当の処理を見つけたら「userIdentity」が実際に処理を行った主体と思われるので、このロールなどを判断材料に使う
    • 今回のケースでは「errorMessage」に「User: arn:aws:sts::xxx:assumed-role/xxxRole/xxx is not authorized to perform: iam:PassRole on resource: arn:aws:iam::xxx:role/xxxPolicy」が出ていた