# define a policy document for role below data "aws_iam_policy_document" "ecs-agent" { statement { actions = [ "sts:AssumeRole"] principals { type = "Service" identifiers = [ "ec2.amazonaws.com", "ecs-tasks.amazonaws.com"] } } } # define the role for ECS agent so that ECS container agent can make API calls resource "aws_iam_role" "ecs-agent" { name = var.ecs_iam_role assume_role_policy = data.aws_iam_policy_document.ecs-agent.json } # grant role permission for ECS agent operations resource "aws_iam_role_policy_attachment" "ecs-agent" { role = aws_iam_role.ecs-agent.name policy_arn = "arn:aws:iam::aws:policy/service-role/AmazonEC2ContainerServiceforEC2Role" } # grant access for systems manager to access the EC2 instance resource "aws_iam_role_policy_attachment" "ssm-policy" { role = aws_iam_role.ecs-agent.name policy_arn = "arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore" } # allow instance profile to assume this role resource "aws_iam_instance_profile" "ecs-instance-profile" { name = var.iam_instance_profile role = aws_iam_role.ecs-agent.name }