Amazon Simple Storage Service
开发人员指南 (API 版本 2006-03-01)
AWS 文档中描述的 AWS 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 Amazon AWS 入门

使用 IAM 用户临时凭证进行请求 - 适用于 Ruby 的 AWS 开发工具包

IAM 用户或 AWS 账户可以使用 适用于 Ruby 的 AWS 开发工具包 请求临时安全凭证,然后使用这些凭证访问 Amazon S3。在会话持续时间结束后,这些凭证将过期。默认情况下,会话的持续时间为一个小时。如果使用了 IAM 用户凭证,则可在请求临时安全凭证时指定持续时间 (1 到 36 小时)。有关请求临时安全凭证的信息,请参阅创建请求

注意

如果您使用 AWS 账户安全凭证获取临时安全凭证,则临时安全凭证的有效期仅为一个小时。只有当您使用 IAM 用户凭证请求会话时,才可以指定会话持续时间。

以下 Ruby 示例将创建一个临时用户来列出指定存储桶中的项目 1 小时。要使用此示例,则必须具有 AWS 凭证,此类凭证具有创建新的 AWS Security Token Service (AWS STS) 客户端和列出 Amazon S3 存储桶所需的权限。

require 'aws-sdk-core' require 'aws-sdk-s3' require 'aws-sdk-iam' USAGE = <<DOC Usage: assumerole_create_bucket_policy.rb -b BUCKET -u USER [-r REGION] [-d] [-h] Assumes a role for USER to list items in BUCKET for one hour. BUCKET is required and must already exist. USER is required and if not found, is created. If REGION is not supplied, defaults to us-west-2. -d gives you extra (debugging) information. -h displays this message and quits. DOC $debug = false def print_debug(s) if $debug puts s end end def get_user(region, user_name, create) user = nil iam = Aws::IAM::Client.new(region: 'us-west-2') begin user = iam.create_user(user_name: user_name) iam.wait_until(:user_exists, user_name: user_name) print_debug("Created new user #{user_name}") rescue Aws::IAM::Errors::EntityAlreadyExists print_debug("Found user #{user_name} in region #{region}") end end # main region = 'us-west-2' user_name = '' bucket_name = '' i = 0 while i < ARGV.length case ARGV[i] when '-b' i += 1 bucket_name = ARGV[i] when '-u' i += 1 user_name = ARGV[i] when '-r' i += 1 region = ARGV[i] when '-d' puts 'Debugging enabled' $debug = true when '-h' puts USAGE exit 0 else puts 'Unrecognized option: ' + ARGV[i] puts USAGE exit 1 end i += 1 end if bucket_name == '' puts 'You must supply a bucket name' puts USAGE exit 1 end if user_name == '' puts 'You must supply a user name' puts USAGE exit 1 end #Identify the IAM user that is allowed to list Amazon S3 bucket items for an hour. user = get_user(region, user_name, true) # Create a new Amazon STS client and get temporary credentials. This uses a role that was already created. creds = Aws::AssumeRoleCredentials.new( client: Aws::STS::Client.new(region: region), role_arn: "arn:aws:iam::111122223333:role/assumedrolelist", role_session_name: "assumerole-s3-list" ) # Create an Amazon S3 resource with temporary credentials. s3 = Aws::S3::Resource.new(region: region, credentials: creds) puts "Contents of '%s':" % bucket_name puts ' Name => GUID' s3.bucket(bucket_name).objects.limit(50).each do |obj| puts " #{obj.key} => #{obj.etag}" end