Fetch IAM Username as the output - amazon-iam

`We are running an AWS Glue job and we believe the following code snippet should return the AWS UserId from which the job is being triggered.
For ex, the following code was run with the user mmohanty
import boto3 client = boto3.client('sts') response = client.get_caller_identity() print('User ID:', response['UserId'])
The output is being shown as **AROA6CNCYWLF5MGCB5DF4:GlueJobRunnerSession **instead of IAM username.
The entire output of client.get_caller_identity() doesn't have any reference to IAM username.
{'UserId': 'AROA6CNCYWLF5MGCB5DF4:GlueJobRunnerSession', 'Account': '1234567', 'Arn': 'arn:aws:sts::12345678:assumed-role/xxx-GlueRole/GlueJobRunnerSession', 'ResponseMetadata': {'RequestId': 'bb43bd2b-4426-46b5-8457-aaaaaaa92116d', 'HTTPStatusCode': 200, 'HTTPHeaders': {'x-amzn-requestid': 'bb43bd2b-4426-46b5-8457-aaaaaaa2116d', 'content-type': 'text/xml', 'content-length': '459', 'date': 'Fri, 20 Jan 2023 17:31:27 GMT'}, 'RetryAttempts': 0}}
Please let us know how to get IAM username instead of the cryptic userid.
We are getting cryptic Userid instead of actual IAM username.`

Related

IAM Permissions Errors When Using boto3 for AWS Comprehend

I'm playing around with the command line to run some sentiment analysis through aws and am running into some IAM issues. When running the "detect_dominant_language" function, I'm hitting NotAuthorizedExceptions despite having the policy in place to allow for all comprehend functions. The policy for the account is:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"comprehend:*",
"s3:ListAllMyBuckets",
"s3:ListBucket",
"s3:GetBucketLocation",
"iam:ListRoles",
"iam:GetRole"
],
"Effect": "Allow",
"Resource": "*"
}
]
}
Any ideas of where I might be going wrong with this? I've triple-checked my access key to make sure that I'm referring to the correct account. When I check the policy, it's there so I'm a little bit at a loss as to the disconnect. S3 seems to be working fine as well.
Steps already taken:
Resetting access key/secret access key.
Creating iam policy which explicitly refers to the needed functionality and attaching it to the "Admin" user.
Calling this method from the CLI (get the same error).
Below, I've included additional information that may be helpful...
Code to check iam policies:
iam = boto3.client('iam',
aws_access_key_id = '*********************',
aws_secret_access_key = '*************************************')
iam.list_attached_user_policies(UserName="Admin")
Output:
{'AttachedPolicies': [{'PolicyName': 'ComprehendFullAccess',
'PolicyArn': 'arn:aws:iam::aws:policy/ComprehendFullAccess'},
{'PolicyName': 'AdministratorAccess',
'PolicyArn': 'arn:aws:iam::aws:policy/AdministratorAccess'},
{'PolicyName': 'Comprehend-Limitied',
'PolicyArn': 'arn:aws:iam::401311205158:policy/Comprehend-Limitied'}],
'IsTruncated': False,
'ResponseMetadata': {'RequestId': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
'HTTPStatusCode': 200,
'HTTPHeaders': {'x-amzn-requestid': '9094d8ff-1730-44b8-af0f-9222a63b32e9',
'content-type': 'text/xml',
'content-length': '871',
'date': 'Thu, 20 Jan 2022 21:48:11 GMT'},
'RetryAttempts': 0}}
Code to trigger error:
comprehend = boto3.client('comprehend',
aws_access_key_id = '*********************',
aws_secret_access_key = '********************************')
test_language_string = "This is a test string. I'm hoping that AWS Comprehend can interprete this as english..."
comprehend.detect_dominant_language(Text=test_language_string)
Output:
ClientError: An error occurred (NotAuthorizedException) when calling the DetectDominantLanguage operation: Your account is not authorized to make this call.
I encountered the same error and I end up creating a new user group and a user for that particular API access. Here're the steps in a nutshell:
Create a user group (e.g. Research)
Give access to ComprehendFullAccess
Create a user (e.g.
ComprehendUser) under the newly created user group (i.e.
Research)
Bingo! It should work now.
Here is my code snippet:
# import packages
import boto3
# aws access credentials
AWS_ACCESS_KEY_ID = 'your-access-key'
AWS_SECRET_ACCESS_KEY = 'your-secret-key'
comprehend = boto3.client('comprehend',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
region_name='us-east-1')
test_language_string = "This is a test string. I'm hoping that AWS Comprehend can interprete this as english..."
comprehend.detect_dominant_language(Text=test_language_string)
Expected Output
{'Languages': [{'LanguageCode': 'en', 'Score': 0.9753355979919434}],
'ResponseMetadata': {'RequestId': 'd2ab429f-6ff7-4f9b-9ec2-dbf494ebf20a',
'HTTPStatusCode': 200,
'HTTPHeaders': {'x-amzn-requestid': 'd2ab429f-6ff7-4f9b-9ec2-dbf494ebf20a',
'content-type': 'application/x-amz-json-1.1',
'content-length': '64',
'date': 'Mon, 07 Feb 2022 16:31:36 GMT'},
'RetryAttempts': 0}}
UPDATE: Thanks for all the feedback y'all! It turns out us-west-1 doesn't support comprehend. Switching to a different availability zone did the trick, so I would recommend anyone with similar problems try different zones before digging too deep into permissions//access keys.

Can't receive text message using SNS python Lambda

I've read everything possible about SNS and I can't figure out why any text messages are sent from an aws lambda function.
My function can't be more simple:
def send_sms(message):
print ("sending message...")
print(message)
client = boto3.client("sns")
response = client.publish(
PhoneNumber="+336xxxxxxxxx",
Message=message
)
print (response)
I'm using an SNSFullAccess for this lambda function.
And my log for the print (response) are:
{'MessageId': '6e9aa592-4ff7-5cf1-be92-ffe34ca16120',
'ResponseMetadata': {'RequestId':
'5d73d693-b584-5ecb-926f-8ce2b6d2831a', 'HTTPStatusCode': 200,
'HTTPHeaders': {'x-amzn-requestid':
'5d73d693-b584-5ecb-926f-8ce2b6d2831a', 'content-type': 'text/xml',
'content-length': '294', 'date': 'Sun, 30 Jan 2022 21:20:22 GMT'},
'RetryAttempts': 0}}

AWS SES Email Verification RequestId status

Working on AWS SES Email Verification, after verifying an email i get back a RequestId from the response. Im trying to find a way to get an update form that RequestId i cant find a endpoint or method that can give me an update on this RequestId status.
{
ResponseMetadata: { RequestId: '1234567890' }
}
Here is the docs that im using for the Email Verification https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-email-addresses-procedure.html
You can't track the status of email verification using the RequestId received from SES email verification response. Pasting a sample response from SES email verification.
{'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'abcd-xyz-123', 'HTTPHeaders': {'date': 'Wed, 26 May 2021 04:44:03 GMT', 'x-amzn-requestid': '98768888-1111-qwaq-2222', 'content-length': '248', 'content-type': 'text/xml', 'connection': 'keep-alive'}}}
To get the status of the email verification, you can try list_verified_email_addresses operation. It list out all the verified email addresses. Check whether your required email address is listing in VerifiedEmailAddresses. If it is not there then it is not yet verified.
import boto3
from botocore.config import Config
my_config = Config(region_name = 'us-west-2')
ses = boto3.client('ses', config=my_config)
response = ses.list_verified_email_addresses()
print(response)
Response:
{'ResponseMetadata': {'RetryAttempts': 0, 'HTTPStatusCode': 200, 'RequestId': 'xxxxx', 'HTTPHeaders': {'date': 'Wed, 26 May 2021 05:25:00 GMT', 'x-amzn-requestid': 'xxxxxx', 'content-length': '412', 'content-type': 'text/xml', 'connection': 'keep-alive'}}, u'VerifiedEmailAddresses': ['example#gmail.com']}

aws boto3 paginator of list_images

can someone please help me understand and do paginator codehere in this list_images code:
When i run this to get list of images for ec2imagebuilder, in the responce i got the nexttoken so how to use this to list all images in next page/until end.
client = boto3.client('imagebuilder')
response = client.list_images(owner='Amazon')
print(response)
Response (Trucated result):
{'ResponseMetadata': {'RequestId': 'f4b9e178-b959-4e23-be57-0c234fbec69d', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'Sun, 10 May 2020 21:53:55 GMT', 'content-type': 'application/json', 'content-length': '8709', 'connection': 'keep-alive', 'x-amzn-requestid': 'f4b9e178-b959-4e23-be57-0c234fbec69d', 'x-amz-apigw-id': 'MVet5Hp0PHcFeaw=', 'x-amzn-trace-id': 'Root=1-5eb877f2-9bec8ecc200f1394f6b0d340;Sampled=1'}, 'RetryAttempts': 0}, 'requestId': 'f4b9e178-b959-4e23-be57-0c234fbec69d', 'imageVersionList': [{'arn': 'arn:aws:imagebuilder:us-west-2:aws:image/amazon-linux-2-x86/2019.11.21', 'name': 'Amazon Linux 2 x86', 'version': '2019.11.21', 'platform': 'Linux', 'owner': 'Amazon', 'dateCreated': '2019-11-30T07:37:51.495Z'}, {'arn': 'arn:aws:imagebuilder:us-west-2:aws:image/windows-server-2012-r2-rtm-english-core-x86/2019.11.19', 'name': 'Windows Server 2012 R2 RTM English Core x86', 'version': '2019.11.19', 'platform': 'Windows', 'owner': 'Amazon', 'dateCreated': '2019-11-30T07:38:07.177Z'}], 'nextToken': 'eyxxxMS4xOSIsICJBY2NvdW50SWQiOiAiNTgwMDg3NjIzMDA1In0sICJtYXhfcmVzdWx0cyI6IDI1LCAia2V5X2NvbmRpdGlvbnMiOiB7IkFjY291bnRJZCI6IHsiQXR0cmlidXRlVmFsdWVMaXN0IjogWyI1ODAwODc2MjMwdddiOiBmYWxzZSwgInNjYW5faW5kZXhfZm9yd2FyZCI6IHRydWUsICJleHBpcmF0aW9uX2RhdGUiOiAxNTg5MjM0MDM1fQ=='}
Based on the documentation, you can use the following code snippet to list all images owned by Amazon.
client = boto3.client('imagebuilder')
response = client.list_images(owner='Amazon')
print(response['imageVersionList'])
while 'nextToken' in response:
response = client.list_images(owner='Amazon', nextToken=response['nextToken'])
print(response['imageVersionList'])

How to get the current execution role in a lambda?

I'm having issues with a lambda that does not seem have the permissions to perform an action and want to get some troubleshooting information.
I can do this to get the current user:
print("Current user: " + boto3.resource('iam').CurrentUser().arn)
Is there a way to get the execution role at runtime? Better yet, is there a way to get the policies that are attached to this role dynamically?
They shouldn't change from when I created the lambda, but I want to verify to be sure.
Check this: list_attached_user_policies
Lists all managed policies that are attached to the specified IAM
user.
An IAM user can also have inline policies embedded with it.
If you want just the inline policies: get_user_policy
Retrieves the specified inline policy document that is embedded in the
specified IAM user.
Do not know, how much relevance this will bring to the OP.
But we can get lambda function configuration at runtime.
lambda_client = boto3.client('lambda')
role_response = (lambda_client.get_function_configuration(
FunctionName = os.environ['AWS_LAMBDA_FUNCTION_NAME'])
)
print(role_response)
role_arn = role_response['Role']
role_response will have role arn.
role_response =>
{'ResponseMetadata': {'RequestId': '', 'HTTPStatusCode': 200, 'HTTPHeaders': {'date': 'GMT', 'content-type': 'application/json', 'content-length': '877', 'connection': 'keep-alive', 'x-amzn-requestid': ''}, 'RetryAttempts': 0}, 'FunctionName': 'lambda_name', 'FunctionArn': 'arn:aws:lambda:<region>:<account_id>:function:lambda_arn', 'Runtime': 'python3.8', 'Role': 'arn:aws:iam::<account_id>:role/<role_name>', 'Handler': 'handlers.handle', 'CodeSize': 30772, 'Description': '', 'Timeout': 30, 'MemorySize': 128, 'LastModified': '', 'CodeSha256': '', 'Version': '$LATEST', 'VpcConfig': {'SubnetIds': [], 'SecurityGroupIds': [], 'VpcId': ''}, 'TracingConfig': {'Mode': 'PassThrough'}, 'RevisionId': '', 'State': 'Active', 'LastUpdateStatus': 'Successful'}