I am creating a Terraform script which creates a IAM role to be assumbed by EC2 instance via Launch Template. I have a simple lambda function (boto3/python) that creates/launches the EC2 instance using the Launch Template. However, I am getting this error when I run the lambda function:
"errorMessage": "An error occurred (InvalidParameterValue) when calling the RunInstances operation:
Value (arn:aws:iam::xxx:instance-profile/RigstopgapInstanceProfile) for parameter iamInstanceProfile.name is invalid. Invalid IAM Instance Profile name",
"errorType": "ClientError",
My terraform code is this one:
resource "aws_launch_template" "rig_stopgap" {
name = "rig_stopgap"
image_id = var.ami_image
instance_type = var.instance_type
iam_instance_profile {
name = aws_iam_instance_profile.rig_stopgap.arn
}
...
}
resource "aws_iam_instance_profile" "rig_stopgap" {
name = "RigstopgapInstanceProfile"
role = aws_iam_role.rigs_stopgap_ec2.name
}
# EC2 "Trust relationships" policy (necessary to allow the instance to assume a role)
data "aws_iam_policy_document" "trust_relationships_ec2_policy" {
statement {
actions = ["sts:AssumeRole"]
principals {
type = "Service"
identifiers = ["ec2.amazonaws.com"]
}
}
}
# EC2 main policy
resource "aws_iam_policy" "rigs_stopgap_ec2_policy" {
name = "RigsStopgapPolicy"
description = "Rigs Stopgap Policy allowing access to all of the necessary resources"
policy = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"dynamodb:UpdateItem"
],
"Effect": "Allow",
"Resource": "${aws_dynamodb_table.rigs_stopgap.arn}"
}
]
}
EOF
}
# Attach the ec2 policy
resource "aws_iam_role_policy_attachment" "attach_ec2_instance_policy" {
role = aws_iam_role.rigs_stopgap_ec2.name
policy_arn = aws_iam_policy.rigs_stopgap_ec2_policy.arn
}
resource "aws_iam_role" "rigs_stopgap_ec2" {
name = "RigsStopgapRole"
assume_role_policy = data.aws_iam_policy_document.trust_relationships_ec2_policy.json
tags = var.common_tags
}
My Lambda code:
import boto3
ec2 = boto3.resource('ec2')
lt = {
'LaunchTemplateName': 'rig_stopgap',
'Version': '$Latest'
}
def handler(event, context):
instances = ec2.create_instances(
LaunchTemplate=lt,
MinCount=1,
MaxCount=1
)
What am I missing?
Update: When I open the Launch Template in the AWS Console and navigate to the Instance Profile section it apparantly cannot find it: