Skip to content

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

  1. Get data from aws_iam_policy using data block type with the name execution_policy
  2. aws_iam_policy requires 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"
}

  1. We need to create also a aws_iam_policy_document using data block type with name ssm_assume and content:
      version = "2012-10-17"
      statement {
        effect = "Allow"
        principals {
          identifiers = ["ecs-tasks.amazonaws.com"]
          type = "Service"
        }
        actions = ["sts:AssumeRole"]
      }
    
    version usually is just a random date statement is 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.

  1. Create resource block with type aws_iam_role named this
  2. aws_iam_role requires these parameters:
    1. name = "${var.service_name}-role"
    2. managed_policy_arns = [data.aws_iam_policy.execution_policy.arn]
    3. 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
}