我正在尝试探索是否有更好的方法。我只是使用策略生成器定义IAM策略,然后使用以下内容——
const policyDocument = {
"Version": "2012-10-17",
"Statement": [
{
"Sid": "FirstStatement",
"Effect": "Allow",
"Action": ["iam:ChangePassword"],
"Resource": "*"
},
{
"Sid": "SecondStatement",
"Effect": "Allow",
"Action": [
"s3:List*",
"s3:Get*"
],
"Resource": [
"arn:aws:s3:::confidential-data",
"arn:aws:s3:::confidential-data/*"
],
"Condition": {"Bool": {"aws:MultiFactorAuthPresent": "true"}}
}
]
};
然后需要定义以下内容——
const customPolicyDocument = iam.PolicyDocument.fromJson(policyDocument);
const newManagedPolicy = new ManagedPolicy(stack, 'MyNewManagedPolicy', {
document: customPolicyDocument
});
const newPolicy = new Policy(stack, 'MyNewPolicy', {
document: customPolicyDocument
});
最后,我创建了一个角色并附加了策略-
const TestBucketRole = new iam.Role(this, 'TestBucketRole', {
assumedBy: new iam.ArnPrincipal('arn:aws:iam::123456789012:user/user1'),
roleName: "test-role-cdk"
})
TestBucketRole.attachInlinePolicy(newPolicy);
有更好的方法吗?
您可以使用CDK构造来实现iam。PolicyDocument和iam。实现相同目标的政策声明:
import * as iam from "@aws-cdk/aws-iam";
let policy = new iam.PolicyDocument({
statements: [
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["iam:ChangePassword"],
resources: ["*"],
}),
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["iam:ChangePassword"],
resources: ["*"],
}),
new iam.PolicyStatement({
effect: iam.Effect.ALLOW,
actions: ["s3:List*", "s3:Get*"],
resources: [
"arn:aws:s3:::confidential-data",
"arn:aws:s3:::confidential-data/*",
],
conditions: {
Bool: { "aws:MultiFactorAuthPresent": "true" },
},
}),
],
});
我喜欢使用CDK构造而不是JSON的地方是TypeScript属性/类型检查和自动完成。
但最终,它们是可以互换的!
CDK条件语句让我有点不知所措。。。我以为它是一个数组,但事实并非如此。