AWS Python IAM API - 如何以编程方式获取 AWS IAM 权限?

问题描述 投票:0回答:2

有没有办法知道 AWS IAM 账户是否具有创建 VPC、EC2、SQS、SNS 和 CloudTrail 的正确权限?

鉴于 IAM 的访问密钥和安全访问密钥,如果 IAM 没有正确的权限,我想以编程方式阻止它进一步创建 VPC、SQS、SNS。

是否有 AWS Python API 可以进行此类检查?
VPC 和 EC2 有 DryRun 选项。 但 SQS、SNS、S3 和 CloudTrail API 没有这样的选项。

有人可以帮忙吗? 预先感谢。

python amazon-web-services amazon-s3 aws-sdk amazon-iam
2个回答
0
投票

AWS 为此提供了一个 CLI 命令:

aws iam simulate-principal-policy \
--policy-source-arn arn:aws:iam::123456789:user/SomeUser \
--action-names sqs:CreateQueue

https://docs.aws.amazon.com/cli/latest/reference/iam/simulate-principal-policy.html

您也可以将它与 Python boto3 包一起使用: http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.simulate_principal_policy

作为解决方法,您还可以检查特定策略是否附加到特定用户/角色。如果您的 IAM 具有秩序和良好的结构,那么对于 AWS 和客户托管策略,它可能会非常简单:

aws iam list-attached-user-policies --user-name your SomeUser
aws iam list-attached-role-policies --role-name SomeRole
aws iam list-attached-group-policies --group-name SomeGroup

0
投票

我想将我的生产密钥移至 AWS 密钥管理器而不是环境变量中。

import boto3
import os
import json
from botocore.exceptions import NoCredentialsError, PartialCredentialsError
from datetime import datetime

# Initialize the ECS client using credentials from environment variables
def initialize_client():
    try:
        ecs_client = boto3.client(
            'ecs',
            region_name=os.getenv('AWS_REGION', 'us-east-1')  # Default to 'us-east-1' if not set
        )
        return ecs_client
    except (NoCredentialsError, PartialCredentialsError):
        print("Error: AWS credentials are not properly set in environment variables.")
        exit(1)

# Function to list all ECS task definitions
def list_task_definitions(ecs_client):
    task_definitions = []
    paginator = ecs_client.get_paginator('list_task_definitions')
    page_iterator = paginator.paginate()

    for page in page_iterator:
        task_definitions.extend(page['taskDefinitionArns'])

    return task_definitions

# Function to describe a single task definition
def describe_task_definition(ecs_client, task_definition_arn):
    try:
        response = ecs_client.describe_task_definition(taskDefinition=task_definition_arn)
        return response['taskDefinition']
    except Exception as e:
        print(f"Error describing task definition {task_definition_arn}: {e}")
        return None

# Helper function to serialize datetime objects
def json_serializer(obj):
    if isinstance(obj, datetime):
        return obj.isoformat()
    raise TypeError(f"Type {type(obj)} not serializable")

if __name__ == "__main__":
    # Initialize ECS client
    ecs_client = initialize_client()

    # Fetch ECS task definitions
    task_defs = list_task_definitions(ecs_client)
    if task_defs:
        print("ECS Task Definitions (JSON):")
        for task_def_arn in task_defs:
            task_definition = describe_task_definition(ecs_client, task_def_arn)
            if task_definition:
                try:
                    # Pretty print the task definition JSON, handling datetime serialization
                    print(json.dumps(task_definition, indent=4, default=json_serializer))
                except Exception as e:
                    print(f"Error serializing JSON for task definition {task_def_arn}: {e}")
    else:
        print("No ECS task definitions found.")


## AKIA4VDBMA2N2WZPKOEL, QoFPDxtcij7sk4ylde5ZVq0U/c3pqXp68ynYTXJj
© www.soinside.com 2019 - 2024. All rights reserved.