如何在不设置aws configure的情况下使用IAM角色获得临时IAM编程访问?

问题描述 投票:-2回答:1

如何在不设置aws configure的情况下使用IAM角色获得临时IAM编程访问?

在python中回答会有所帮助

如果你有请,请粘贴我的完整代码。

python amazon-web-services boto3 amazon-iam
1个回答
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)同一帐户无法生成用于请求其资源的临时访问密钥

© www.soinside.com 2019 - 2024. All rights reserved.