要使用AWS Identity and Access Management(IAM)角色和Security Token Service(STS),可以使用以下代码示例:
import boto3
iam_client = boto3.client('iam')
response = iam_client.create_role(
RoleName='MyRole',
AssumeRolePolicyDocument={
'Version': '2012-10-17',
'Statement': [
{
'Effect': 'Allow',
'Principal': {
'Service': 'ec2.amazonaws.com'
},
'Action': 'sts:AssumeRole'
}
]
}
)
print(response)
import boto3
iam_client = boto3.client('iam')
response = iam_client.attach_role_policy(
RoleName='MyRole',
PolicyArn='arn:aws:iam::aws:policy/AmazonS3ReadOnlyAccess'
)
print(response)
import boto3
sts_client = boto3.client('sts')
response = sts_client.assume_role(
RoleArn='arn:aws:iam::123456789012:role/MyRole',
RoleSessionName='MySession'
)
credentials = response['Credentials']
access_key = credentials['AccessKeyId']
secret_key = credentials['SecretAccessKey']
session_token = credentials['SessionToken']
print(f'Access Key: {access_key}')
print(f'Secret Key: {secret_key}')
print(f'Session Token: {session_token}')
这些示例代码中,我们使用boto3
库来调用AWS服务的API。首先,我们创建一个IAM角色,然后将策略附加到角色上。最后,我们使用assume_role
方法获取临时凭证。
上一篇:AWS IAM角色操作审核
下一篇:AWS IAM角色权限问题