Getting authentication error while running python code.

0

Hello Experts,

This is regarding my boto3 python code which I am running to get basically all my ec2 instances, created by me. Problem is it's giving Authentication error in Lambda aws.

Tried efforts: I have put my user's access id and access security key on program it's not working. Then I created 1 policy added all permissions to ec2 there and attach to user but then also same error.

Error message: In lambda code execution.

{
  "errorMessage": "An error occurred (UnauthorizedOperation) when calling the DescribeInstances operation: You are not authorized to perform this operation.",
  "errorType": "ClientError",
  "requestId": "",
  "stackTrace": [
    "  File \"/var/lang/lib/python3.10/importlib/__init__.py\", line 126, in import_module\n    return _bootstrap._gcd_import(name[level:], package, level)\n",
    "  File \"<frozen importlib._bootstrap>\", line 1050, in _gcd_import\n",
    "  File \"<frozen importlib._bootstrap>\", line 1027, in _find_and_load\n",
    "  File \"<frozen importlib._bootstrap>\", line 1006, in _find_and_load_unlocked\n",
    "  File \"<frozen importlib._bootstrap>\", line 688, in _load_unlocked\n",
    "  File \"<frozen importlib._bootstrap_external>\", line 883, in exec_module\n",
    "  File \"<frozen importlib._bootstrap>\", line 241, in _call_with_frames_removed\n",
    "  File \"/var/task/lambda_function.py\", line 29, in <module>\n    instances= ec2.meta.client.describe_instances()\n",
    "  File \"/var/runtime/botocore/client.py\", line 530, in _api_call\n    return self._make_api_call(operation_name, kwargs)\n",
    "  File \"/var/runtime/botocore/client.py\", line 960, in _make_api_call\n    raise error_class(parsed_response, operation_name)\n"
  ]
}

Boto3 lambda code:

import boto3 
import os
regions= [
    #'ap-east-1',
    'ap-northeast-1',
    'ap-northeast-2',
    'ap-south-1',
    'ap-southeast-1',
    'ap-southeast-2',
    'ca-central-1',
    'eu-central-1',
    'eu-north-1',
    'eu-west-1',
    'eu-west-2',
    'eu-west-3',
    #'me-south-1',
    'sa-east-1',
    'us-east-1',
    'us-east-2',
    'us-west-1',
    'us-west-2'
    ]
# os.environ['AWS_ACCESS_KEY_ID'] = 'key id here'
# os.environ['AWS_SECRET_ACCESS_KEY'] = 'access key here'

for region_name in regions:
    # print(f'region_name: {region_name}')
    ec2= boto3.resource('ec2', region_name=region_name)
    instances= ec2.meta.client.describe_instances()
    for instance in instances['Reservations']:
        id = instance['Instances'][0]['InstanceId']
        if(id):
           instance_state = instance['Instances'][0]['State']['Name']
           print("Instance id of region " + str(region_name) + " is:" + str(id) + ", its state is: " + str(instance_state))

Policy Name: Enter image description here

How Policy looks: Enter image description here

Your guidance is really appreciated 🙏

2 Answers
1
Accepted Answer

For Lamba, you want to use a role and not a user. Lambda always has an "execution role", which is assumed when the function is executed.

Given that you have a Lambda function already, an execution role is most probably already present. What you need to do now is:

  • Find the execution role, in the settings of your Lambda function
  • Attach the policy you have created

As Nitin has stated already, there's no need to hard-code credentials within your function, since Lambda will request temporary credentials via STS automatically (the key here is "trust policies", the execution role contains a trust policy which allows Lambda to assume this role).

If this still doesn't work, please consult the CloudWatch logs for your Lambda function. They might contain useful information about the root cause of any potential additional issue.

profile pictureAWS
Michael
answered 10 months ago
  • Thank you Michael for letting know. I will do the changes and get back to you, cheers

1

Hi - It would be great to share the policy and also error messages.

Couple of things

  1. You don't have to hard code your credentials and use roles . See Lambda execution role (https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html)
  2. The roles should have required policy for the actions
  3. I would say , see lambda functions logs in cloudwatch for more detailed error message. Reference https://docs.aws.amazon.com/lambda/latest/dg/monitoring-cloudwatchlogs.html
profile pictureAWS
EXPERT
answered 10 months ago
  • Hello @AWS-User-Nitin, I have updated question with Error and code. But I am not sure how to attach the policy screen shot in question.

  • I have successfully updated policy screen shots also in my question, kindly do let me know in case of any thing needed, cheers.

  • Please check if your trust relationship for the lambda policy under "Entities attached" has EC2 as the service.

    Also check if your ec2 instance profile also allows access to the lambda- for this check trust relationship of ec2 instance profile policy has the lambda as the service provided.

    Once you have set this up, you can access ec2. You don't need to configure your user creds for the API calls.

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions