【问题标题】:Using Boto3 to get AWS configuration option使用 Boto3 获取 AWS 配置选项
【发布时间】:2021-10-16 02:42:10
【问题描述】:

我正在寻找一种在 python 中使用 boto3 来执行与 AWS CLI 的方法 aws configure get varname [--profile profile-name] 等效的方法。有谁知道这是否可能没有:

  1. 自己解析 AWS 配置文件
  2. 通过我的 python 脚本以某种方式与 AWS CLI 本身进行交互

关于更多上下文,我正在编写一个 python cli 工具,它将使用 boto3 与 AWS API 进行交互。 python 工具使用存储在 ~/.aws/credentials 文件的配置文件中的 AWS 会话令牌。我正在使用 saml2aws cli 从我公司的身份提供商获取 AWS 凭证,该身份提供商将 aws_access_key_idaws_secret_access_keyaws_session_tokenaws_security_tokenx_principal_arnx_security_token_expires 参数写入 ~/.aws/credentials像这样的文件:

[saml]
aws_access_key_id        = #REMOVED#
aws_secret_access_key    = #REMOVED#
aws_session_token        = #REMOVED#
aws_security_token       = #REMOVED#
x_principal_arn          = arn:aws:sts::000000000123:assumed-role/MyAssumedRole
x_security_token_expires = 2019-08-19T15:00:56-06:00

由于我的 python cli 工具的性质,有时该工具会在 AWS 会话令牌的到期时间之后执行,我的公司强制执行该时间非常短。我希望 python cli 工具在开始其关键任务之前检查过期时间,以验证它是否有足够的时间来完成其任务,如果没有,则提醒用户刷新他们的会话令牌。

使用 AWS CLI,我可以使用如下方式从 ~/.aws/credentials 文件中获取 AWS 会话令牌的到期时间:

$ aws configure get x_security_token_expires --profile saml
2019-08-19T15:00:56-06:00

我很好奇 boto3 是否有我找不到的机制来做类似的事情。


作为替代解决方案,给定已生成的 AWS 会话令牌,是否可以获取它的到期时间?但是,鉴于Ways to find out how soon the AWS session expires? 等问题缺乏答案,我猜不会。

【问题讨论】:

    标签: python amazon-web-services boto3


    【解决方案1】:

    由于官方 AWS CLI 由 boto3 提供支持,因此我能够深入研究源代码以了解 aws configure get 是如何实现的。可以通过 botocore Session 对象读取配置文件配置。以下是获取示例中使用的配置文件和值的一些代码:

    import botocore.session
    
    # Create an empty botocore session directly
    session = botocore.session.Session()
    
    # Get config of desired profile. full_config is a standard python dictionary.
    profiles_config = session.full_config.get("profiles", {})
    saml_config = profiles_config.get("saml", {})
    
    # Get config value. This will be None if the setting doesn't exist.
    saml_security_token_expires = saml_config.get("x_security_token_expires")
    

    我正在使用与上述类似的代码作为透明会话缓存的一部分。它会检查配置文件的 role_arn,因此我可以识别要加载的缓存会话(如果存在且尚未过期)。

    至于知道给定会话在到期之前还有多长时间的替代问题,您是正确的,因为目前没有 API 调用可以告诉您这一点。会话过期仅在创建会话时给出,通过 STS get_session_tokenassume_role API 调用。之后您必须自己保留到期信息。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-05-26
      • 2016-01-27
      • 1970-01-01
      • 2016-11-04
      • 2023-03-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多