Bootstrap FreeKB - Amazon Web Services (AWS) Elastic Container Service (ECS) - Create IAM Role using Terraform
Amazon Web Services (AWS) Elastic Container Service (ECS) - Create IAM Role using Terraform


The IAM AmazonEC2ContainerServiceforEC2Role is needed to do certain things in an Elastic Container Service (ECS) Cluster such as creating EC2 Instances.

Let's say you have the following files on your Terraform server.

├── required_providers.tf
├── iam (directory)
│   ├── policies.tf
│   ├── profiles.tf
│   ├── provider.tf
│   ├── roles.tf

 

required_providers.tf will almost always have this.

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
    }
  }
}

 

Let's say provider.tf has the following. In this example, the "default" profile in /home/username/.aws/config and /home/username/.aws/credentials is being used. This assumes you have setup Terraform as described in Amazon Web Services (AWS) - Getting Started with Terraform.

provider "aws" {
  alias   = "default"
  profile = "default"
  region  = "default"
}

 

policies.tf could have something like this, to get the JSON for the AmazonEC2ContainerServiceforEC2Role policy.

data "aws_iam_policy" "AmazonEC2ContainerServiceforEC2Role_policy" {
  name = "AmazonEC2ContainerServiceforEC2Role"
}

data "aws_iam_policy_document" "assume_role" {
  statement {
    effect = "Allow"
    actions = [
      "sts:AssumeRole"
    ]
    principals {
      type = "Service"
      identifiers = [
        "ec2.amazonaws.com"
      ]
    }
  }
}

 

roles.tf could have something like this, to create a role named ecsInstanceRole.

resource "aws_iam_role" "ecsInstanceRole" {
  name                = "ecsInstanceRole"
  assume_role_policy  = data.aws_iam_policy_document.assume_role.json
  managed_policy_arns = [data.aws_iam_policy.AmazonEC2ContainerServiceforEC2Role_policy.arn]
}

 

And profiles.tf could have something like this, to create a profile named ecs-instance-profile.

resource "aws_iam_instance_profile" "ecs-instance-profile" {
  name = "ecs-instance-profile"
  role = aws_iam_role.ecsInstanceRole.role_name
}

 

You may need to issue the terraform init command.

terraform init

 

The terraform plan command can be used to see what Terraform will try to do.

terraform plan

 

The terraform apply command can be used to create or update the resource.

terraform apply -auto-approve

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter d5bf39 in the box below so that we can be sure you are a human.