【问题标题】:How to I access Security token for Python SDK boto3如何访问 Python SDK boto3 的安全令牌
【发布时间】:2019-01-22 15:12:06
【问题描述】:

我想从 python 脚本访问 AWS comprehend api。没有得到任何关于如何消除此错误的线索。我知道我必须获得会话安全令牌的一件事。

try:
  client = boto3.client(service_name='comprehend', region_name='us-east-1', aws_access_key_id='KEY ID', aws_secret_access_key= 'ACCESS KEY')
  text = "It is raining today in Seattle"
  print('Calling DetectEntities')
  print(json.dumps(client.detect_entities(Text=text, LanguageCode='en'), sort_keys=True, indent=4))
  print('End of DetectEntities\n')

except ClientError as e:
  print (e)

错误:调用 DetectEntities 操作时发生错误(UnrecognizedClientException):请求中包含的安全令牌无效。

【问题讨论】:

  • 所提供的凭证是否来自具有理解权限的有效 IAM 用户?还是它们是临时凭证(在这种情况下您需要提供 aws_session_token)?
  • 您是在 Amazon EC2 实例上还是在您自己的计算机上运行此代码?

标签: python amazon-web-services aws-sdk boto3


【解决方案1】:

此错误提示您提供的凭据无效。

你应该永远在你的源代码中放入凭据也是没有价值的。如果其他人获得源代码的访问权限,这可能会导致潜在的安全问题。

有多种方法可以向使用 AWS 开发工具包的应用程序(例如 boto3)提供有效凭证。

如果应用程序在 Amazon EC2 实例上运行,请为实例分配 IAM 角色。这将自动提供 boto3 可以检索的凭据。

如果您在自己的计算机上运行该应用程序,请将凭据存储在 .aws/credentials 文件中。创建此文件的最简单方法是使用aws configure 命令。

见:Credentials — Boto 3 documentation

【讨论】:

    【解决方案2】:

    我每天使用的一个有用工具是:https://github.com/atward/aws-profile/blob/master/aws-profile

    这使得担任角色变得更加容易!

    在 .aws/credentials 和 .aws/config 中设置访问密钥后

    你可以这样做:

    AWS_PROFILE=**you-profile** aws-profile [python x.py]

    [] 中的部分可以替换为您想要使用 AWS 凭证的任何内容。例如,地形计划

    本质上,此实用程序只是将您的 AWS 凭证放入操作系统环境变量中。然后在您的 boto 脚本中,您无需担心设置 aws_access_key_id 等。

    【讨论】:

      【解决方案3】:

      使用aws configure 或更新~/.aws/config 创建配置文件。如果您只有一个配置文件可以使用 = default,您可以在 Session() 调用中省略 profile_name 参数(参见下面的示例)。然后使用会话对象创建 AWS 服务特定客户端。示例;

      import boto3
      session = boto3.session.Session(profile_name="test")
      ec2_client = session.client('ec2')
      ec2_client.describe_instances()
      ec2_resource = session.resource(‘ec2’)
      

      【讨论】:

        猜你喜欢
        • 2014-10-30
        • 1970-01-01
        • 2021-02-04
        • 2018-10-16
        • 2012-09-11
        • 1970-01-01
        • 2011-11-15
        • 1970-01-01
        • 2015-11-16
        相关资源
        最近更新 更多