簡體   English   中英

在不同 AWS 賬戶中啟動和停止 EC2 實例的 IAM 策略/角色設置

[英]IAM policy/role setup for Start and Stop EC2 instances in a different AWS account

我想從另一個 AWS 賬戶(賬戶:BBB)啟動和停止 AWS 賬戶(賬戶:AAA)中的 EC2 實例。 具體來說,我正在設置 API 以在賬戶 BBB 中的 ECS 上執行此操作。 當我測試 API 以啟動和停止同一帳戶中的帳戶時,它工作正常。 但是,我無法讓 IAM 角色正確地跨多個賬戶工作。

我的 API 使用 boto3 並使用 describe_instance_status 識別實例狀態,然后使用 start_instances 或 stop_instances 啟動/停止。 只要 EC2 實例與托管 API 的 ECS 位於同一賬戶中,所有這些都可以正常工作。

跨多個帳戶工作。 我做了以下,但我得到了錯誤:

"botocore.exceptions.ClientError: An error occurred (UnauthorizedOperation) when calling the DescribeInstanceStatus operation: You are not authorized to perform this operation.botocore.exceptions.ClientError: An error occurred (UnauthorizedOperation) when calling the DescribeInstanceStatus operation: You are not authorized to perform this operation."

我的設置如下:

  1. 在托管 EC2 實例的賬戶 AAA 中,我創建了一個如下所示的策略。 BBB 代表托管 ECS 任務的賬戶,該任務運行 API。
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:DescribeInstanceStatus",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "ec2:StartInstances",
                "ec2:StopInstances"
            ],
            "Resource": "arn:aws:ec2:*:AAA:instance/*",
            "Condition": {
                "StringEqualsIgnoreCase": {
                    "ec2:ResourceTag/ManagedBy": "API"
                }
            }
        }
    ]
  1. 創建了一個角色 (ec2-instance-mgmt-role),該角色使用上述策略並與 Account: BBB 建立信任關系。

  2. 在 Account BBB 中,我創建了一個策略 (ec2-assume-managerole),如下所示,其中 AAA 是托管 EC2 實例的帳戶的帳戶名稱。

{
    "Version": "2012-10-17",
    "Statement": {
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::AAA:role/ec2-instance-mgmt-role"
    }
} 
  1. 在 Account BBB 中,我創建了一個附加了 (3) 中的策略的角色。 此外,我為此角色創建了與 ecs-tasks 的信任關系。

我要開始的 boto3 代碼片段如下:

ec2 = boto3.client('ec2', region_name=region_name)

resp = ec2.describe_instance_status(
        InstanceIds=[str(instance_id)],
        IncludeAllInstances=True)

print("Response = ",resp)

instance_status = resp['InstanceStatuses'][0]['InstanceState']['Code']

print("Instance status =", instance_status)

if instance_status == 80:
    ec2.start_instances(InstanceIds=[instance_id])
    print("Started instance with Instance_id",instance_id)
    return {'message': 'instance started'}
else:
     print("Instance not in a state to start")
     return {'message': 'instance not in a state to be started'}
  1. 將步驟 (4) 中創建的角色分配為 ECS 任務的任務角色,該任務定義為啟動和停止 EC2 實例而構建的 API 的容器。 ECS 實例在賬戶 BBB 中運行。

當我嘗試調用此 API 時,我收到開頭描述的錯誤,該錯誤也粘貼在下面。

"botocore.exceptions.ClientError: An error occurred (UnauthorizedOperation) when calling the DescribeInstanceStatus operation: You are not authorized to perform this operation.botocore.exceptions.ClientError: An error occurred (UnauthorizedOperation) when calling the DescribeInstanceStatus operation: You are not authorized to perform this operation."

最后,我能夠解決這個問題。 我錯過的是我沒有承擔 boto3 代碼中的角色。 一旦添加它就可以了。 下面的代碼顯示了被調用來承擔角色的 function,下面的代碼顯示了在承擔角色后描述 ec2 實例狀態的用法。

def assume_role(role_arn):
    sts_client = boto3.client('sts')

    letters = string.ascii_letters
    session_name = f"AssumeRoleSession{random.choice(letters)}"
    assumed_role_object=sts_client.assume_role(
        RoleArn=role_arn,
        RoleSessionName=session_name
    )

    credentials=assumed_role_object['Credentials']

    print(f"Credentials: {credentials}")

    ec2_resource=boto3.resource(
                                    'ec2',
                                    aws_access_key_id=credentials['AccessKeyId'],
                                    aws_secret_access_key=credentials['SecretAccessKey'],
                                    aws_session_token=credentials['SessionToken'],
                                )


    return ec2_resource


 ec2_resource = assume_role(assume_role_arn)
  
 ec2 = ec2_resource.meta.client

 resp = ec2.describe_instance_status(
            InstanceIds=[str(instance_id)],
            IncludeAllInstances=True)


暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM