IAM
IAM is AWS access management tool. It can hold users, groups, roles and policies for services.
In these exercise you will learn how to import dynamically data from AWS using Terraform and creating IAM resources.
Import information
- Get data from
aws_iam_policyusingdatablock type with the nameexecution_policy aws_iam_policyrequires ARN:arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy
Help
terraform/iam.tf
data "aws_iam_policy" "execution_policy" {
arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
- We need to create also a
aws_iam_policy_documentusingdatablock type with namessm_assumeand content:version = "2012-10-17" statement { effect = "Allow" principals { identifiers = ["ecs-tasks.amazonaws.com"] type = "Service" } actions = ["sts:AssumeRole"] }versionusually is just a random datestatementis a JSON formatted (in HCL) to give or deny permissions. In this we will allow ECS to assume Execution Role.
Help
terraform/iam.tf
data "aws_iam_policy_document" "ssm_assume" {
version = "2012-10-17"
statement {
effect = "Allow"
principals {
identifiers = ["ecs-tasks.amazonaws.com"]
type = "Service"
}
actions = ["sts:AssumeRole"]
}
}
Create aws_iam_role resource
After we have created and imported information from AWS, we can create a role and bind the policy to it.
- Create
resourceblock with typeaws_iam_rolenamedthis aws_iam_rolerequires these parameters:name="${var.service_name}-role"managed_policy_arns=[data.aws_iam_policy.execution_policy.arn]assume_role_policy=data.aws_iam_policy_document.ssm_assume.json
Check your configuration
To check your Terraform configuration run
terraform plan
It will show you the resources that Terraform will create,delete or change. It will not apply anything.
Answer
terraform/iam.tf
data "aws_iam_policy" "execution_policy" {
arn = "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy"
}
data "aws_iam_policy_document" "ssm_assume" {
version = "2012-10-17"
statement {
effect = "Allow"
principals {
identifiers = ["ecs-tasks.amazonaws.com"]
type = "Service"
}
actions = ["sts:AssumeRole"]
}
}
resource "aws_iam_role" "this" {
name = "${var.service_name}-role"
managed_policy_arns = [data.aws_iam_policy.execution_policy.arn]
assume_role_policy = data.aws_iam_policy_document.ssm_assume.json
}