Add/attach AWS IAM Role to EC2 instance via terraform

2.4k views Asked by At

i have a quick question here.. I am using terraform to deploy ec2 instances on AWS, and i need a way to attach AWS IAM Role to the instance.

I have created manuall on AWS console an IAM Policy + role, and attached to EC2 instance and tested, it works. Now i need to use same role (i created earlier manually) to automatically attach to new ec2 instances via terraform

I am tring to do this:

resource "aws_instance" "test-ec2" {
  ami                         = "ami-xxxxxxxxxx"
  instance_type               = "t3.large"
  iam_instance_profile        = "arn:aws:iam::1234567890:role/my-role-name" ## I know i am missing something here... (:facepalm:)
  key_name                    = "my-key"
  subnet_id                   = "subnet-some-subnet-d"
  vpc_security_group_ids      = ["sg-some-group-id"]
  associate_public_ip_address = true
  root_block_device {
    delete_on_termination = true
    volume_type           = "gp3"
    volume_size           = 40
}

The reason i am doing it that way (create manualy role once and not via terraform) is becouse i dont want to give terraform ability to create roles and permissions, only ec2 instances and attach only existing role, less permissions on jenkins/terraform = better security (at least this is what i think is proper..)

This is the error I get:

Error: creating EC2 Instance: InvalidParameterValue: Value (arn:aws:iam::1234567890:role/my-role-name) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name    status code: 400, request id: xxxxxx-xxxxx-xxxx-xxxx-xxxxxxxxxx  with aws_instance.test-ec2, on main.tf line 11, in resource "aws_instance" "test-ec2": 11: resource "aws_instance" "test-ec2" {
1

There are 1 answers

0
Grey Vugrin On

You can get an error like this when specifying a role name directly on the instance's iam_instance_profile. Sometimes they have the same name as the role, which can make it hard to diagnose the issue.

When terraforming existing resources this can be easy to miss - you need a aws_iam_instance_profile resource in addition to the aws_iam_role.

Ex:

resource "aws_iam_instance_profile" "test_profile" {
  name = "test_profile"
  role = aws_iam_role.role.name
}

resource "aws_instance" "instance" {
  iam_instance_profile = aws_iam_instance_profile.test_profile.name
}

Related Resources

Terraform aws_iam_instance_profile resource

AWS IAM Roles

AWS Instance Profiles