AWS: Boto3: AssumeRole example which includes role usage

前端 未结 7 1420
梦毁少年i
梦毁少年i 2020-12-14 18:28

I\'m trying to use the AssumeRole in such a way that i\'m traversing multiple accounts and retrieving assets for those accounts. I\'ve made it to this point:



        
7条回答
  •  没有蜡笔的小新
    2020-12-14 19:13

    If you want a functional implementation, this is what I settled on:

    def filter_none_values(kwargs: dict) -> dict:
        """Returns a new dictionary excluding items where value was None"""
        return {k: v for k, v in kwargs.items() if v is not None}
    
    
    def assume_session(
        role_session_name: str,
        role_arn: str,
        duration_seconds: Optional[int] = None,
        region_name: Optional[str] = None,
    ) -> boto3.Session:
        """
        Returns a session with the given name and role.
        If not specified, duration will be set by AWS, probably at 1 hour.
        If not specified, region will be left unset.
        Region can be overridden by each client or resource spawned from this session.
        """
        assume_role_kwargs = filter_none_values(
            {
                "RoleSessionName": role_session_name,
                "RoleArn": role_arn,
                "DurationSeconds": duration_seconds,
            }
        )
        credentials = boto3.client("sts").assume_role(**assume_role_kwargs)["Credentials"]
        create_session_kwargs = filter_none_values(
            {
                "aws_access_key_id": credentials["AccessKeyId"],
                "aws_secret_access_key": credentials["SecretAccessKey"],
                "aws_session_token": credentials["SessionToken"],
                "region_name": region_name,
            }
        )
        return boto3.Session(**create_session_kwargs)
    
    
    def main() -> None:
        session = assume_session(
            "MyCustomSessionName",
            "arn:aws:iam::XXXXXXXXXXXX:role/TheRoleIWantToAssume",
            region_name="us-east-1",
        )
        client = session.client(service_name="ec2")
        print(client.describe_key_pairs())
    
    

提交回复
热议问题