Lambda权限排查:如何获取当前执行角色及关联策略?
Great question—this is a common scenario when debugging Lambda permission issues, and yes, you absolutely can retrieve your Lambda's execution role at runtime and inspect its attached policies to verify they match your initial setup. Let’s walk through how to do this:
Retrieving the Lambda Execution Role at Runtime
Lambda runs under its assigned execution role, and you can get this role’s details using the AWS Security Token Service (STS) API directly in your function code. Here’s a Python example using boto3:
import boto3 import re def lambda_handler(event, context): # Call STS to get the current caller identity (which is the Lambda's execution role) sts_client = boto3.client('sts') caller_identity = sts_client.get_caller_identity() # The ARN returned is for the assumed role (includes a session suffix) assumed_role_arn = caller_identity['Arn'] # Extract the base role name from the ARN (format: arn:aws:sts::123456789012:assumed-role/MyLambdaRole/session-id) role_name_match = re.search(r'assumed-role/([^/]+)/', assumed_role_arn) if role_name_match: role_name = role_name_match.group(1) # Build the full ARN of the underlying IAM role (without the session part) role_arn = f"arn:aws:iam::{caller_identity['Account']}:role/{role_name}" print(f"Lambda execution role name: {role_name}") print(f"Lambda execution role ARN: {role_arn}") return {"role_name": role_name, "role_arn": role_arn} else: raise ValueError("Could not extract execution role name from assumed role ARN")
Fetching Attached Policies for the Role
Once you have the role name, you can use the IAM API to pull both managed and inline policies attached to the role. First, make sure your Lambda’s execution role has permissions to call these IAM actions: iam:ListAttachedRolePolicies, iam:GetRolePolicy, iam:GetPolicy, and iam:GetPolicyVersion.
Here’s how to retrieve all policies:
import boto3 def get_role_attached_policies(role_name): iam_client = boto3.client('iam') all_policies = [] # Fetch attached managed policies managed_policies = iam_client.list_attached_role_policies(RoleName=role_name)['AttachedPolicies'] for policy in managed_policies: policy_arn = policy['PolicyArn'] # Get the default (latest) version of the managed policy policy_details = iam_client.get_policy(PolicyArn=policy_arn) default_version_id = policy_details['Policy']['DefaultVersionId'] policy_doc = iam_client.get_policy_version( PolicyArn=policy_arn, VersionId=default_version_id )['PolicyVersion']['Document'] all_policies.append({ "type": "managed", "name": policy['PolicyName'], "arn": policy_arn, "policy_document": policy_doc }) # Fetch inline policies inline_policy_names = iam_client.list_role_policies(RoleName=role_name)['PolicyNames'] for policy_name in inline_policy_names: inline_policy_doc = iam_client.get_role_policy( RoleName=role_name, PolicyName=policy_name )['PolicyDocument'] all_policies.append({ "type": "inline", "name": policy_name, "policy_document": inline_policy_doc }) return all_policies # Integrate this into your lambda handler def lambda_handler(event, context): # ... retrieve role_name as shown earlier ... role_name = "your-lambda-role-name" # Replace with actual retrieved name policies = get_role_attached_policies(role_name) print("Attached policies for Lambda role:") print(policies) return {"attached_policies": policies}
Verifying Policies Match the Initial Setup
To confirm the current policies match what you set up initially:
- Keep a snapshot of your original policies: Store the policy documents (JSON) in version control, a config file, or another secure location when you create the role.
- Normalize and compare: When retrieving the current policies, normalize both the original and current documents (e.g., sort JSON keys, remove whitespace) to avoid false differences from formatting. For Python, you can use libraries like
deepdiffto perform a deep comparison of the policy structures.
Important Notes
- Permission Prerequisite: If your Lambda function throws
AccessDeniederrors when calling IAM/STS APIs, you’ll need to update its execution role with a policy that allows the required actions (targeted to the specific role ARN to follow least privilege principles). - Assumed Role vs. Base Role: Remember that STS returns the assumed role ARN (with a session suffix), so you need to parse it to get the actual IAM role name for subsequent IAM API calls.
内容的提问来源于stack exchange,提问作者Nate Reed

