2
votes

My lambda code:

instances = [aws_instance]

ec2 = boto3.client('ec2',region_name="us-west-2")
if task == 'start':
    ec2.start_instances(InstanceIds=instances)

My IAM user policy:

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeInstances",
                "ec2:DescribeVolumes",
                "ec2:StartInstances",
                "ec2:StopInstances",
                "ec2:CreateSnapshot",
                "ec2:DeleteSnapshot",
                "ec2:DescribeSnapshots",
         }
```       "ec2:RunInstances",
                "ec2:CopySnapshot",
                "ec2:CreateTags",
                "rds:DescribeDBInstances",
                "rds:CreateDBSnapshot",
                "rds:DeleteDBSnapshot",
                "rds:DescribeDBSnapshots",
                "rds:ListTagsForResource",
                "lambda:AddPermission",
                "lambda:CreateFunction",
                "lambda:InvokeFunction",
                "apigateway:PUT",
                "apigateway:POST",
                "apigateway:GET",
                "ssm:SendCommand"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}

This is throwing error "An error occurred (UnauthorizedOperation) when calling the StartInstances operation: You are not authorized to perform this operation."

C:\Program Files\Microsoft Visual Studio 11.0>aws --region us-west-2 ec2 start-instances --instance-id i-cd2cb9d5

works fine.

I am unable to understand, why lambda function says, I am not allowed to execute "start_instances"

2

2 Answers

1
votes

Your Lambda does not use a IAM user, but an IAM execution role. You can check the role that is associated to the Lambda in "Configuration" tab >> "Existing role". Then you can find the role in IAM and add the policy to it.

The console probably created the current role for you and it is only allowed to write in CloudWatch. It is possible to "manually" create this role. Use the following Trust Relationship to be able to associate it to a Lambda:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}

More about creating an execution role for Lambda

-1
votes

Getting error while testing lambda function.

"errorMessage": "An error occurred (UnauthorizedOperation) when calling the StopInstances operation: You are not authorized to perform this operation...

Solution:

  1. open IAM(Identity and Access Management) page.
  2. Select Lambda Function from list.
  3. Open Basic setting page.
  4. Find the selected role in Roles list in IAM page.
  5. In permissions section, attach AdministratorAccess policy and change permission boundary to AdministratorAccess.