如何在不设置aws configure的情况下使用IAM角色获得临时IAM编程访问权限?
用python回答将很有帮助
请完整粘贴我的代码。
答案 0 :(得分:0)
(base) [root@ip-172-31-39-101 ec2-user]# cat role.py
import boto3
import botocore
account_no=7439222006066 # another account number
role_name='iamest' # another account role
sts_client = boto3.client('sts')
assume_role_response = sts_client.assume_role(
RoleArn = 'arn:aws:iam::{0}:role/{1}'.format(account_no,role_name),
RoleSessionName = 'CloudWatchMetricRoleSession',
DurationSeconds = 900,
#ExternalId = '9949183895'
)
#Below session is required to create request using temporary credentials generated.
session = boto3.Session(
aws_access_key_id = assume_role_response['Credentials']['AccessKeyId'],
aws_secret_access_key = assume_role_response['Credentials']['SecretAccessKey'],
aws_session_token = assume_role_response['Credentials']['SessionToken']
)
#print('your keys are here:', session)
#below we are specifying region for temporary credentials stored in 'session' same like we #configure region in 'aws configure'
cloudwatch_client = session.client('cloudwatch',
region_name = 'us-east-1'
)
all_metric_items = []
# using temporary credentials for a request.
cpu_util_metrices_response = cloudwatch_client.list_metrics(
Namespace = 'AWS/EC2',
MetricName = 'CPUUtilization',
Dimensions = [
{
'Name': 'i-00a2e99dc0855d2b7',
'Value': 'us-east-1'
}
]
)
print (cpu_util_metrices_response)
注意: 1)在另一个帐户中,必须为交叉帐户创建角色,并且在信任关系策略中,添加您要从中请求的AWS帐户的帐户ID。 2)从中运行aws请求的服务器应定义“ aws configure”,以便请求另一个aws帐户临时访问密钥。 3)同一帐户无法生成用于请求其资源的临时访问密钥