-
Notifications
You must be signed in to change notification settings - Fork 12
/
ec2-iam-role.tf
80 lines (73 loc) · 2.38 KB
/
ec2-iam-role.tf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# Create an IAM role for the ECS EC2 instances.
data "aws_iam_policy_document" "ecs_role_definition" {
statement {
effect = "Allow"
actions = [
"sts:AssumeRole",
]
principals {
identifiers = [
"ec2.amazonaws.com",
"ecs-tasks.amazonaws.com"
]
type = "Service"
}
}
}
resource "aws_iam_role" "ecs_role" {
name_prefix = "${var.cluster_name}-ec2-role"
assume_role_policy = data.aws_iam_policy_document.ecs_role_definition.json
# Allows the role to be deleted and reacreated (when needed)
force_detach_policies = true
tags = {
Name = var.cluster_name
}
}
# Create an IAM policy which allows the ECS agent to function inside EC2 instances
data "aws_iam_policy_document" "ecs_instance_role_policy_doc" {
statement {
actions = [
# Requirements for ECS agent
"ecs:CreateCluster",
"ecs:DeregisterContainerInstance",
"ecs:DiscoverPollEndpoint",
"ecs:Poll",
"ecs:RegisterContainerInstance",
"ecs:StartTelemetrySession",
"ecs:Submit*",
"ecs:StartTask",
# Requirements for EC2 instances within the cluster to be able to pull ECR Docker images
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:BatchGetImage",
# Allow EC2 instances to write to CloudWatch logs
"logs:CreateLogStream",
"logs:PutLogEvents"
]
resources = [
"*",
]
}
}
resource "aws_iam_policy" "ecs_role_permissions" {
name_prefix = "${var.cluster_name}-ecs-policy"
description = "These policies allow the ECS instances to do certain actions like pull images from ECR"
path = "/"
policy = data.aws_iam_policy_document.ecs_instance_role_policy_doc.json
}
# Attach the ECS agent IAM policy to the service Role that is assinged to each EC2 instance
resource "aws_iam_policy_attachment" "ecs_instance_role_policy_attachment" {
name = "${var.cluster_name}-iam-policy-attachment"
roles = [
aws_iam_role.ecs_role.name
]
policy_arn = aws_iam_policy.ecs_role_permissions.arn
}
# Allow EC2 instances to be launched using this role,
# allowing them to automatically gain the permissions that were present in this role
# (attached through policies to the Role)
resource "aws_iam_instance_profile" "ec2_iam_instance_profile" {
name_prefix = var.cluster_name
role = aws_iam_role.ecs_role.name
}