I'm using Terraform to create IAM and EC2 as below.
I want to attach a role named ec2_role
to the EC2 instance profile. But it seems it only can attach one that created by aws_iam_instance_profile
.
resource "aws_instance" "this" {
# ..
iam_instance_profile = aws_iam_instance_profile.this.name
}
resource "aws_iam_instance_profile" "this" {
name = "ec2-profile"
role = aws_iam_role.ec2_role.name
}
About the ec2_role
, it uses an ec2_role_policy
. But if I set source_json = data.aws_iam_policy.amazon_ssm_managed_instance_core.policy
to data "aws_iam_policy_document" "ec2_role_policy" {
, it throws an error.
resource "aws_iam_role" "ec2_role" {
name = "ec2-role"
assume_role_policy = data.aws_iam_policy_document.ec2_role_policy.json
}
resource "aws_iam_policy" "ec2_policy" {
name = "ec2-policy"
policy = data.aws_iam_policy_document.ec2_use_role_policy.json
}
resource "aws_iam_role_policy_attachment" "attach" {
role = aws_iam_role.ec2_role.name
policy_arn = aws_iam_policy.ec2_policy.arn
}
data "aws_iam_policy" "amazon_ssm_managed_instance_core" {
arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore"
}
data "aws_iam_policy_document" "ec2_role_policy" {
source_json = data.aws_iam_policy.amazon_ssm_managed_instance_core.policy
statement { # Doc A
effect = "Allow"
principals {
identifiers = ["ec2.amazonaws.com"]
type = "Service"
}
actions = ["sts:AssumeRole"]
}
}
data "aws_iam_policy_document" "ec2_use_role_policy" {
statement {
effect = "Allow"
actions = ["sts:AssumeRole"]
resources = ["arn:aws:iam::12313113231:role/s3-role"]
}
}
The error message is:
Error: Error creating IAM Role ec2-role: MalformedPolicyDocument: Has prohibited field Resource
status code: 400, request id: 1111111-3333-2222-4444-2131331312
with aws_iam_role.ec2_role,
on main.tf line 10, in resource "aws_iam_role" "ec2_role":
10: resource "aws_iam_role" "ec2_role" {
If I remove the source_json = data.aws_iam_policy.amazon_ssm_managed_instance_core.policy
from the ec2_role_policy
, it works. But how to set it with Doc A
together?