Eric M.Johnson给出的答案是正确的,只是为了完整性,
resource "aws_launch_configuration" "ecs_launch_configuration" {
name = "${var.application_name}-${var.stack}"
image_id = var.image_id
instance_type = var.instance_type
iam_instance_profile = aws_iam_instance_profile.esc_launch_configuration_iam_instance_profile.arn
security_groups = split(",",aws_security_group.ecs_launch_configuration_security_group.id)
associate_public_ip_address = "true"
// key_name = "${var.ecs-key-pair-name}"
user_data = data.template_file.user_data.rendered
}
data "template_file" "user_data" {
template = file("${path.module}/ec2/user-data.sh")
vars = {
ecs_cluster_name = "${var.application_name}-${var.stack}"
}
}
resource "aws_iam_instance_profile" "esc_launch_configuration_iam_instance_profile" {
name = "${var.application_name}-${var.stack}"
role = aws_iam_role.iam_role.name
}
resource "aws_iam_role" "iam_role" {
name = "${var.application_name}-${var.stack}"
force_detach_policies = true
assume_role_policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRole",
"Principal": {
"Service": [
"ec2.amazonaws.com",
"ecs.amazonaws.com"
]
},
"Effect": "Allow",
"Sid": ""
}
]
}
EOF
}
resource "aws_iam_role_policy_attachment" "iam_role_policy_attachment" {
role = aws_iam_role.iam_role.name
policy_arn = aws_iam_policy.ecs_iam_policy.arn
}
resource "aws_iam_policy" "ecs_iam_policy" {
name = "${var.application_name}-${var.stack}"
description = "EC2 instance can pull from ECR"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:DescribeTags",
"ecs:CreateCluster",
"ecs:DeregisterContainerInstance",
"ecs:DiscoverPollEndpoint",
"ecs:Poll",
"ecs:RegisterContainerInstance",
"ecs:StartTelemetrySession",
"ecs:UpdateContainerInstancesState",
"ecs:Submit*",
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
"logs:CreateLogStream",
"logs:PutLogEvents"
],
"Resource": "*"
}
]
}
EOF
}