Serverless Step FunctionsでカスタムIAMロールを指定する方法


概要

Serverless Frameworkに Serverless Step Functions プラグインを利用した場面で、カスタムしたIAMロールをStep Functionsのロールとして指定する方法

環境

$ sls --version
Framework Core: 1.60.5

$ npm view serverless-step-functions version
2.17.0

ドキュメントを見る

  • https://serverless.com/plugins/serverless-step-functions/
  • 公式の IAM Role セクションに2つの記述パターンがあります
  • 1つは IAM roleのARNを直接記述する方法
  • もう1つは serverless.yml に記述したIAM Roleを参照指定する方法
  • 本記事は後者を試したものです

ドキュメント通り試す

  • ドキュメント通り記述します
  • ドキュメントではresources > Resources > StateMachineRole > Propertie以下が省略されていますが、ここでは具体的に記述しています
  • 単純化するため、中身は無いです(StateMachineが一つデプロイされます)
serverless.yml
service: sfn-roletest
plugins:
  - serverless-step-functions
provider:
  name: aws
  runtime: python3.8
package:
  exclude:
    - "**"
stepFunctions:
  stateMachines:
    hello:
      name: helloStateMachine
      role:
        Ref: StateMachineRole
      definition:
        StartAt: Hello
        States:
          Hello:
            Type: Pass
            End: true
resources:
  Resources:
    StateMachineRole:
      Type: AWS::IAM::Role
      Properties:
        Path: /
        AssumeRolePolicyDocument:
          Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Principal:
                Service:
                  - states.amazonaws.com
              Action: sts:AssumeRole
        Policies:
          - PolicyName: myPolicy
            PolicyDocument:
              Version: '2012-10-17'
              Statement:
                - Effect: Allow
                  Action:
                    - s3:GetObject
                  Resource: "*"

デプロイします

  • エラーになります
  • resourcesで設定したIAMロールのARNをうまく参照できないようです
$ sls deploy
(snip)
Serverless: Operation failed!
  Serverless Error ---------------------------------------
  An error occurred: HelloStateMachine - Invalid Role Arn: 'sfn-roletest-dev-StateMachineRole-1JIY0T8EYAG0V' (Service: AWSStepFunctions; Status Code: 400; Error Code: InvalidArn; Request ID: 9fc449df-94e0-436d-9e28-64c000bd5ecc).

記述を変えてみる

  • Ref: StateMachineRole 部分を Fn::GetAtt: [StateMachineRole, Arn] へ書き換えます
serverless.yml
(snip)
stepFunctions:
  stateMachines:
    hello:
      name: helloStateMachine
      role:
        #Ref: StateMachineRole
        Fn::GetAtt: [StateMachineRole, Arn]
(snip)
  • デプロイすると成功しました
$ sls deploy
(snip)
Serverless: Updating Stack...
Serverless: Checking Stack update progress...
..........
Serverless: Stack update finished...
Service Information
service: sfn-roletest
stage: dev
region: us-east-1
stack: sfn-roletest-dev
resources: 4
(snip)

確認

  • Management Consoleから確認します

Step Functions > ステートマシン

  • 作成されています
  • IAMロールのリンクをクリックします

IAMロール

  • ポリシーをJSON表示してみます
  • serverless.yml で指定した通り、s3:GetObject のアクセス許可設定が反映されています