AWS Bedrock IAM permissions setup
Quick answer
To use
AWS Bedrock, configure an IAM role or user with permissions for bedrock-runtime:InvokeModel. Attach a policy granting this action and ensure your AWS credentials are properly set for API calls.PREREQUISITES
Python 3.8+AWS CLI configured with appropriate credentialsboto3 installed (pip install boto3)
Setup IAM permissions
Create an IAM policy that allows bedrock-runtime:InvokeModel action. Attach this policy to an IAM role or user that your application will use. This enables secure access to AWS Bedrock models.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "bedrock-runtime:InvokeModel",
"Resource": "*"
}
]
} Step by step example
Use boto3 to call AWS Bedrock with the configured IAM permissions. The example below shows how to invoke a Bedrock model using boto3 bedrock-runtime client.
import boto3
import json
# Initialize Bedrock runtime client
client = boto3.client('bedrock-runtime', region_name='us-east-1')
# Define the model ID and input
model_id = 'anthropic.claude-3-5-sonnet-20241022-v2:0'
input_text = 'Hello, AWS Bedrock!'
# Prepare the message payload
messages = [{"role": "user", "content": [{"type": "text", "text": input_text}]}]
# Call the model
response = client.converse(
modelId=model_id,
messages=messages
)
# Extract and print the response text
output_text = response['output']['message']['content'][0]['text']
print('Model response:', output_text) output
Model response: Hello, AWS Bedrock! How can I assist you today?
Common variations
- Use
invoke_modelmethod for raw JSON payloads. - Set
region_nameto your AWS Bedrock supported region. - Use AWS IAM roles with EC2 or Lambda for automatic credential management.
import boto3
import json
client = boto3.client('bedrock-runtime', region_name='us-east-1')
body = json.dumps({
"anthropic_version": "bedrock-2023-05-31",
"max_tokens": 512,
"messages": [{"role": "user", "content": [{"type": "text", "text": "Explain AI."}]}]
})
response = client.invoke_model(
modelId='anthropic.claude-3-5-sonnet-20241022-v2:0',
body=body
)
output_text = json.loads(response['body'])['output']['message']['content'][0]['text']
print('Raw invoke_model response:', output_text) output
Raw invoke_model response: AI is the simulation of human intelligence processes by machines.
Troubleshooting common errors
- AccessDeniedException: Ensure your IAM policy includes
bedrock-runtime:InvokeModelpermission. - InvalidRegionError: Confirm you are using a supported AWS region for Bedrock.
- CredentialsNotFound: Verify AWS credentials are configured via environment variables, AWS CLI, or IAM roles.
Key Takeaways
- Grant
bedrock-runtime:InvokeModelpermission in IAM policies to access AWS Bedrock models. - Use
boto3bedrock-runtimeclient with proper AWS credentials for API calls. - Configure AWS region and credentials correctly to avoid common authorization and region errors.