0
votes

I am trying to attach an IAM role to EC2 instance using terraform. But after looking out on some web pages.. I found that the attaching can be done at the time of creating ec2 instance.

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"
  iam_instance_profile = "${aws_iam_instance_profile.ec2_profile.name}"
  tags = {
    Name = "HelloWorld"
  }
}

As in the above part , it can be clearly seen that, AMI is being passed which will create a new instance. Is it somehow possible that instead of using AMI id, we can provide instance it, so that it can attach role to that instance?

I found out one link from terraform community pointing out that this feature is not yet released. https://github.com/hashicorp/terraform/issues/11852

Please provide inputs on how to accomplish this task. Thanks in advance

1
Are you saying that your only issue is that the AMI returned by the data source is different to your existing instance that you've imported and thus it want's to destroy and recreate the instance? Have you considered either hard-coding the AMI or using ignore_changes = [ami] if you don't want the instance to be replaced? It would be useful to see the output of your plan edited into the question. - ydaetskcoR
If I pass the AMI id, it will always create a new instance and attach the new role to that. But if we somehow pass the instance id, then we can directly attach IAM role to that. - Tapesh Gupta
I'm not sure I follow what you are saying. Can you edit the question to include the output of your plan please? - ydaetskcoR

1 Answers

1
votes

As you pointed out this is not supported. But if you really want to use terraform for that you could consider two options: