2019年12月4日 星期三

利用 AWS SAM 部署 Serverless 時,需要什麼權限??

利用 AWS SAM 部署 Serverless 時,需要什麼權限??

每次要部署 SAM Project 時,為了符合 AWS IAM Best Practices 都要調校一次 CI User 的 Policy,耗時耗力,所以整理一份 Sample Policy 以便之後直接取用。
會用到的 SAM command 有 validate, build, package, deploy
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:CreateFunction",
                "lambda:UpdateFunctionCode",
                "lambda:TagResource",
                "lambda:UntagResource",
                "lambda:ListTags",
                "lambda:GetFunctionConfiguration",
                "lambda:UpdateFunctionConfiguration",
                "iam:GetRole",
                "cloudformation:UpdateStack",
                "cloudformation:DescribeStackEvents",
                "cloudformation:CreateChangeSet",
                "cloudformation:DeleteChangeSet",
                "cloudformation:DescribeChangeSet",
                "cloudformation:ExecuteChangeSet"
                "s3:PutObject",
                "s3:GetObject",
            ],
            "Resource": [
                "arn:aws:lambda:{AWS::Region}:{AWS::AccountId}:function:{STACK_NAME}-{FUNCTION_NAME}*",
                "arn:aws:s3:::{BUCKET_NAME}/*",
                "arn:aws:iam::{AWS::AccountId}:role/{STACK_NAME}-{FUNCTION_NAME}Role*",
                "arn:aws:cloudformation:{AWS::Region}:aws:transform/Serverless-2016-10-31",
                "arn:aws:cloudformation:{AWS::Region}:{AWS::AccountId}:stack/{STACK_NAME}/*"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "cloudformation:ValidateTemplate",
                "cloudformation:GetTemplateSummary",
                "cloudformation:DescribeStacks"
            ],
            "Resource": "*"
        }
    ]
}
  • replace the following:
    • {BUCKET_NAME} with the bucket name you’re using for code upload
    • {STACK_NAME} with your stack name
    • {FUNCTION_NAME} with your function name
  • 如果在 deploy 加上 —debug 參數,則還會需要 cloudformation:DescribeStackEvents 權限
  • 如果用到 Events properties,則還會需要 lambda:AddPermission,以及 Event type 相對應的 Resource Permission
  • 如果有設定 Lambda Role Policies 則還會需要以下 Permission
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "iam:GetRole",
                "iam:PassRole",
                "iam:DeleteRolePolicy",
                "iam:CreateRole",
                "iam:DeleteRole",
                "iam:PutRolePolicy",
                "iam:GetRolePolicy"
            ],
            "Resource": "arn:aws:iam::{AWS::AccountId}:role/{STACK_NAME}-LambdaRole*"
        }
    ]
}

Reference