Georgi Koemdzhiev
Georgi Koemdzhiev

Reputation: 11931

AWS lambda to create ec2 instance using Launch template and boto3 only using the required permissions

I am having problems setting the correct permissions to my IAM role that is assumed by a lambda function. The purpose of the lambda is to launch ec2 instance using the provided Launch Template. However, I am constantly getting You are not authorized to perform this operation.errors due to not correct permissions of the IAM role.

The only policy I am attaching at the moment to the role is this one:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "logs:CreateLogGroup",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "arn:aws:logs:*:*:*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:RunInstances",
                "ec2:GetLaunchTemplateData"
            ],
            "Resource": "*"
        }
    ]
}

Lambda boto3/python code:

import boto3

ec2 = boto3.resource('ec2')

lt = {
    # 'LaunchTemplateId': 'lt-0b91c7e5c5437a1c1',
    'LaunchTemplateName': 'template_name',
    'Version': '$Latest'
}


def handler(event, context):

    instances = ec2.create_instances(
        LaunchTemplate=lt,
        MinCount=1,
        MaxCount=1
        # UserData=user_data
    )

Note: If I attach AmazonEC2FullAccess AWS Managed policy to the lambda role it works fine

What am I missing?

Also, is there an easy way of finding what are the "bare minimum" IAM policy permissions that are needed by a resource to function?

Upvotes: 2

Views: 2417

Answers (1)

Marcin
Marcin

Reputation: 238557

Based on the comments.

Often, RunInstances permission is not enough to launch an instance. What permissions are required depends on what does the instance do, e.g. uses KMS encrypted volumes, iam instance roles/profiles, set tags and more.

In the OPs case, the instance to be launched was using tags, thus ec2:CreateTags permission was needed to make it work.

Upvotes: 1

Related Questions