文档中解释了为轮换 AWS Secrets Manager 密钥的 lambda 函数设置权限的过程。[1]
简而言之,您需要两个步骤:
- 向 lambda 函数添加信任策略。这可以使用 serverless.yml 文件中的 CloudFormation 资源AWS::Lambda::Permission来实现。但是,设置它有点棘手,因为您需要依赖于正在创建的函数。这就是为什么DependsOn是必要的,并且它的值必须按如下结构构成:
<function-name-with-first-letter-uppercase>LambdaFunction
.
- 为 lambda 函数添加语句以调用 AWS Secrets Manager API 来更新密钥。在以下示例中,我将这些语句(对于单用户轮换案例 - 请参阅文档 [1])添加到名为rotateKeysPolicy的客户管理策略中。
注意:函数名称在DependsOn属性中引用。它还在条件StringEquals和属性FunctionName中被引用为:arn:aws:lambda:${self:custom.region}:${self:custom.accountId}:function:${self:service}-${self:provider.stage}-rotateKeys
。如果您更改函数名称,请记住更改它们。
下面是 serverless.yml 文件的外观:
service:
name: <your-service-name>
provider:
name: aws
region: '<your-region>'
custom:
region: ${self:provider.region}
accountId: <your-account-id>
resources:
Resources:
FunctionRole:
Type: AWS::IAM::Role
Properties:
RoleName: basic-function-role
ManagedPolicyArns:
- arn:aws:iam::aws:policy/service-role/AWSLambdaBasicExecutionRole
Policies:
- PolicyName: rotateKeysPolicy
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- secretsmanager:DescribeSecret
- secretsmanager:GetSecretValue
- secretsmanager:PutSecretValue
- secretsmanager:UpdateSecretVersionStage
Resource: '*'
Condition:
StringEquals:
'secretsmanager:resource/AllowRotationLambdaArn': "arn:aws:lambda:${self:custom.region}:${self:custom.accountId}:function:${self:service}-${self:provider.stage}-rotateKeys"
- Effect: Allow
Action:
- secretsmanager:GetRandomPassword
Resource: '*'
- Effect: Allow
Action:
- ec2:CreateNetworkInterface
- ec2:DeleteNetworkInterface
- ec2:DescribeNetworkInterfaces
Resource: '*'
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action: sts:AssumeRole
LambdaInvokePermission:
Type: AWS::Lambda::Permission
DependsOn: RotateKeysLambdaFunction
Properties:
FunctionName: "arn:aws:lambda:${self:custom.region}:${self:custom.accountId}:function:${self:service}-${self:provider.stage}-rotateKeys"
Action: lambda:InvokeFunction
Principal: 'secretsmanager.amazonaws.com'
functions:
rotateKeys:
handler: lambdas.rotate_keys.handler
role: FunctionRole
您必须替换<your-service-name>
,并使用属性上传您<your-region>
的<your-account-id>
轮换代码。package -> include
注意:有用于更新秘密的 lambda 函数的模板。[2][3]
另请记住,正确配置您的 VPC 以使 lambda 函数能够通过网络访问 AWS Secrets Manager 服务。[4]
参考
[1] https://docs.aws.amazon.com/secretsmanager/latest/userguide/rotating-secrets-required-permissions.html
[2] https://docs.aws.amazon.com/secretsmanager/latest/userguide /rotating-secrets-create-generic-template.html
[3] https://github.com/aws-samples/aws-secrets-manager-rotation-lambdas
[4] https://docs.aws.amazon.com /secretsmanager/latest/userguide/rotation-network-rqmts.html