创建策略资源时未使用
for_each
元参数,因此您需要使用以下内容:
resource "aws_iam_policy" "s3_policy" {
name = "s3-policy"
description = "S3 IAM policy"
policy = <<-JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "*"
}
]
}
JSON
}
resource "aws_iam_policy" "ec2_policy" {
name = "ec2-policy"
description = "EC2 IAM policy"
policy = <<-JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ec2:*",
"Resource": "*"
}
]
}
JSON
}
resource "aws_iam_user_policy_attachment" "ec2_policy" {
user = module.iam_user_module.aws_iam_user.this[0].name
policy_arn = aws_iam_policy.ec2_policy.arn
}
resource "aws_iam_user_policy_attachment" "s3_policy" {
user = module.iam_user_module.aws_iam_user.this[0].name
policy_arn = aws_iam_policy.s3_policy.arn
}
请注意,使用时
implicit references
,语法为:
<resource type>.<logical name>.<attribute>
或者在你的情况下
| aws_iam_policy | ec2_policy | arn
| resource type | logical name | attribute
由于策略被分配给同一用户,因此可以执行以下操作:
resource "aws_iam_policy" "iam_policies" {
name = "ec2-s3-policy"
description = "EC2 and S3 IAM policy"
policy = <<-JSON
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:GetObject",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "ec2:*",
"Resource": "*"
}
]
}
JSON
}
resource "aws_iam_user_policy_attachment" "user_policy" {
user = module.iam_user_module.aws_iam_user.this[0].name
policy_arn = aws_iam_policy.iam_policy.arn
}