我在https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_instance_profile,我创建了iam.tf文件。我试图将策略附加到ec2实例。我得到一个错误:
aws_iam_role.role: Creating...
Error: failed creating IAM Role (jenkins_server_role): MalformedPolicyDocument: Has prohibited field Resource
status code: 400, request id: c2b8db57-357f-4657-a692-a3e6026a6b7b
with aws_iam_role.role,
on iam.tf line 6, in resource "aws_iam_role" "role":
6: resource "aws_iam_role" "role" Releasing state lock. This may take a few moments...
ERRO[0011] Terraform invocation failed in /home/pluo/works/infra/jenkins
ERRO[0011] 1 error occurred:
* exit status 1
这是iam.tf:
resource "aws_iam_instance_profile" "jenkins_server" {
name = "jenkins_server"
role = aws_iam_role.role.name
}
resource "aws_iam_role" "role" {
name = "jenkins_server_role"
path = "/"
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "ec2:*",
"Effect": "Allow",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "elasticloadbalancing:*",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "cloudwatch:*",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "autoscaling:*",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "iam:CreateServiceLinkedRole",
"Resource": "*",
"Condition": {
"StringEquals": {
"iam:AWSServiceName": [
"autoscaling.amazonaws.com",
"ec2scheduled.amazonaws.com",
"elasticloadbalancing.amazonaws.com",
"spot.amazonaws.com",
"spotfleet.amazonaws.com",
"transitgateway.amazonaws.com"
]
}
}
}
]
}
EOF
}
这里是创建ec2实例的模块。
module "ec2" {
source = "terraform-aws-modules/ec2-instance/aws"
version = "4.1.4"
name = var.ec2_name
ami = var.ami
instance_type = var.instance_type
availability_zone = var.availability_zone
subnet_id = data.terraform_remote_state.vpc.outputs.public_subnets[0]
vpc_security_group_ids = [aws_security_group.WebServerSG.id]
associate_public_ip_address = true
key_name = var.key_name
monitoring = true
iam_instance_profile = aws_iam_instance_profile.jenkins_server.name
enable_volume_tags = false
root_block_device = [
{
encrypted = true
volume_type = "gp3"
throughput = 200
volume_size = 100
tags = {
Name = "jenkins_server"
}
},
]
tags = {
Name = "WebServerSG"
}
}
您的assume_role_policy
不正确。对于ec2实例,它应该是:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": { "Service": "ec2.amazonaws.com"},
"Action": "sts:AssumeRole"
}
]
}
那么您当前的assume_role_policy
应该改为用aws_iam_role_policy编写。
只是为了在Marcin的好答案之上提供更多信息。在AWS IAM角色中,您可以指定两种策略(一开始可能会混淆(:
-
承担角色策略,即";谁"/什么可以承担这个角色,正如Marcin在这里提到的,你想指定EC2实例可以承担这个任务,即扮演这个角色
-
角色政策-即该角色可以做什么;在你的情况下,它将是所有这些弹性负载平衡,云手表,等等
因此,将其纳入Terraform视角:
- 前者应转到
aws_iam_role
的assume_role_policy
- 后者应该转到单独的
resource "iam_role_policy"