I want to Add my Existing AWS IAM role for Ec2 instance

Hi Team
I’m New bee to terraform recently started to write a terraform files, i got struck while adding the existing (it’s been created before in AWS console )IAM role to EC2 instance.
I thought instead of create new using terraform i want to use existing one.

I tried below format to attach exiting role to my code but it’s not working, can you help me how to attach it.

#Attach existing IAM Role to EC2 instance

resource "aws_iam_instance_profile" "UC-profile" {
  name = "UC-profile"
  role = "AWS-SSM-Role-Connect"
  }

resource "aws_instance" "webserver-1" {
  ami                         = "ami-01410ca4af28f22b0"
  instance_type               = "r5.xlarge"
  vpc_security_group_ids      = ["${aws_security_group.sg-Uc2.id}"]
  subnet_id                   = "${element(aws_subnet.public.*.id,0)}"
  associate_public_ip_address = false
  iam_instance_profile = aws_iam_instance_profile.UC-profile.name
  
  tags = {
    Name = "web-1"
  }
}

To call the details of created resource, use “data” instead of “resource”. Here is the updated sample code. Hope this should work!!

data "aws_iam_instance_profile" "UC-profile" {
    name = "UC-profile"
}

resource "aws_instance" "webserver-1" {
  ami                         = "ami-05afd67c4a44cc983"
  instance_type               = "t2.micro"
  associate_public_ip_address = false
  iam_instance_profile = data.aws_iam_instance_profile.UC-profile.name

}

Hi
Thanks for the reply on my request, could you please elaborate more through sample code how we can attach the existing IAM role to this profile and attach to instance…