연합된 사용자의 임시 자격 증명을 사용하여 요청하기 - Amazon Simple Storage Service

연합된 사용자의 임시 자격 증명을 사용하여 요청하기

임시 보안 자격 증명을 요청하고 이를 AWS 리소스에 액세스해야 하는 페더레이션 사용자 또는 애플리케이션에 제공할 수 있습니다. 이 섹션에서는 AWS SDK를 사용하여 페더레이션 사용자 또는 애플리케이션에 대한 임시 보안 자격 증명을 가져오고 이러한 자격 증명을 사용하여 인증된 요청을 Amazon S3로 보내는 방법에 대한 예제를 제공합니다. 사용 가능한 AWS SDK 목록은 샘플 코드 및 라이브러리를 참조하세요.

참고

AWS 계정 및 IAM 사용자 모두 페더레이션 사용자에 대해 임시 보안 자격 증명을 요청할 수 있습니다. 그러나 보안 강화를 위해 필요한 권한이 있는 IAM 사용자만 이러한 임시 자격 증명을 요청하여 연합된 사용자가 요청하는 IAM 사용자의 권한을 최대한 얻을 수 있도록 해야 됩니다. 일부 애플리케이션에서는 연합된 사용자 및 애플리케이션에 임시 보안 자격 증명을 부여하기 위한 목적으로만 특정 권한이 있는 IAM 사용자를 만드는 것이 적합할 수도 있습니다.

Java

AWS 리소스에 액세스하기 위해 인증된 요청을 보낼 수 있도록 페더레이션 사용자 및 애플리케이션에 대해 임시 보안 자격 증명을 제공할 수 있습니다. 이러한 임시 자격 증명을 요청할 때는 사용자 이름과 부여할 리소스 권한을 설명하는 IAM 정책을 제공해야 합니다. 세션은 기본적으로 1시간 동안 지속됩니다. 연합된 사용자 및 애플리케이션에 대한 임시 보안 자격 증명을 요청할 때는 다른 기간 값을 명시적으로 설정할 수 있습니다.

참고

연합된 사용자 및 애플리케이션에 대한 임시 보안 자격 증명을 요청할 때 보안 강화를 위해 필요한 액세스 권한만 가진 전용 IAM 사용자를 사용하는 것이 좋습니다. 생성하는 임시 사용자는 임시 보안 자격 증명을 요청한 IAM 사용자보다 더 많은 권한을 가질 수 없습니다. 자세한 내용은 AWS Identity and Access Management FAQ를 참조하세요.

리소스에 액세스하기 위해 보안 자격 증명을 제공하고 인증된 요청을 보내려면 다음을 수행합니다.

  • AWSSecurityTokenServiceClient 클래스의 인스턴스를 만듭니다. 자격 증명 제공에 대한 자세한 내용은 AWS SDK for Java 사용 단원을 참조하십시오.

  • 보안 토큰 서비스(STS) 클라이언트의 getFederationToken() 메서드를 호출하여 세션을 시작합니다. 임시 자격 증명에 연결하려는 IAM 정책 및 사용자 이름을 비롯한 세션 정보를 제공합니다. 선택적 세션 기간을 제공할 수 있습니다. 이 메서드는 임시 보안 자격 증명을 반환합니다.

  • BasicSessionCredentials 객체의 인스턴스에 임시 보안 자격 증명을 패키지로 포함합니다. 이 객체를 사용하여 Amazon S3 클라이언트에 임시 보안 자격 증명을 제공합니다.

  • 임시 보안 자격 증명을 사용하여 AmazonS3Client 클래스의 인스턴스를 만듭니다. 이 클라이언트를 사용하여 Amazon S3에 요청을 보냅니다. 만료된 자격 증명을 사용하여 요청을 보낼 경우 Amazon S3에서 오류를 반환합니다.

다음 예제는 지정된 S3 버킷의 키를 나열합니다. 이 예제에서는 연합된 사용자를 위해 2시간의 세션에 대한 임시 보안 자격 증명을 가져오고 이 자격 증명을 사용하여 인증된 요청을 Amazon S3으로 보냅니다. 이 예제를 실행하려면 사용자가 임시 보안 자격 증명을 요청하고 AWS 리소스를 나열하도록 허용하는 연결된 정책을 사용해 IAM 사용자를 생성해야 합니다. 다음 정책을 통해 이러한 작업을 수행할 수 있습니다.

{ "Statement":[{ "Action":["s3:ListBucket", "sts:GetFederationToken*" ], "Effect":"Allow", "Resource":"*" } ] }

IAM 사용자를 만드는 방법에 대한 자세한 내용은 IAM 사용 설명서의 첫 번째 IAM 사용자 및 관리자 그룹 생성을 참조하세요.

IAM 사용자를 생성한 후 이전 정책을 연결하면 다음 예제를 실행할 수 있습니다. 실제 예제를 작성 및 테스트하는 방법에 대한 자세한 내용은 Amazon S3 Java 코드 예제 테스트 섹션을 참조하세요.

import com.amazonaws.AmazonServiceException; import com.amazonaws.SdkClientException; import com.amazonaws.auth.AWSStaticCredentialsProvider; import com.amazonaws.auth.BasicSessionCredentials; import com.amazonaws.auth.policy.Policy; import com.amazonaws.auth.policy.Resource; import com.amazonaws.auth.policy.Statement; import com.amazonaws.auth.policy.Statement.Effect; import com.amazonaws.auth.policy.actions.S3Actions; import com.amazonaws.auth.profile.ProfileCredentialsProvider; import com.amazonaws.regions.Regions; import com.amazonaws.services.s3.AmazonS3; import com.amazonaws.services.s3.AmazonS3ClientBuilder; import com.amazonaws.services.s3.model.ObjectListing; import com.amazonaws.services.securitytoken.AWSSecurityTokenService; import com.amazonaws.services.securitytoken.AWSSecurityTokenServiceClientBuilder; import com.amazonaws.services.securitytoken.model.Credentials; import com.amazonaws.services.securitytoken.model.GetFederationTokenRequest; import com.amazonaws.services.securitytoken.model.GetFederationTokenResult; import java.io.IOException; public class MakingRequestsWithFederatedTempCredentials { public static void main(String[] args) throws IOException { Regions clientRegion = Regions.DEFAULT_REGION; String bucketName = "*** Specify bucket name ***"; String federatedUser = "*** Federated user name ***"; String resourceARN = "arn:aws:s3:::" + bucketName; try { AWSSecurityTokenService stsClient = AWSSecurityTokenServiceClientBuilder .standard() .withCredentials(new ProfileCredentialsProvider()) .withRegion(clientRegion) .build(); GetFederationTokenRequest getFederationTokenRequest = new GetFederationTokenRequest(); getFederationTokenRequest.setDurationSeconds(7200); getFederationTokenRequest.setName(federatedUser); // Define the policy and add it to the request. Policy policy = new Policy(); policy.withStatements(new Statement(Effect.Allow) .withActions(S3Actions.ListObjects) .withResources(new Resource(resourceARN))); getFederationTokenRequest.setPolicy(policy.toJson()); // Get the temporary security credentials. GetFederationTokenResult federationTokenResult = stsClient.getFederationToken(getFederationTokenRequest); Credentials sessionCredentials = federationTokenResult.getCredentials(); // Package the session credentials as a BasicSessionCredentials // object for an Amazon S3 client object to use. BasicSessionCredentials basicSessionCredentials = new BasicSessionCredentials( sessionCredentials.getAccessKeyId(), sessionCredentials.getSecretAccessKey(), sessionCredentials.getSessionToken()); AmazonS3 s3Client = AmazonS3ClientBuilder.standard() .withCredentials(new AWSStaticCredentialsProvider(basicSessionCredentials)) .withRegion(clientRegion) .build(); // To verify that the client works, send a listObjects request using // the temporary security credentials. ObjectListing objects = s3Client.listObjects(bucketName); System.out.println("No. of Objects = " + objects.getObjectSummaries().size()); } catch (AmazonServiceException e) { // The call was transmitted successfully, but Amazon S3 couldn't process // it, so it returned an error response. e.printStackTrace(); } catch (SdkClientException e) { // Amazon S3 couldn't be contacted for a response, or the client // couldn't parse the response from Amazon S3. e.printStackTrace(); } } }
.NET

AWS 리소스에 액세스하기 위해 인증된 요청을 보낼 수 있도록 페더레이션 사용자 및 애플리케이션에 대해 임시 보안 자격 증명을 제공할 수 있습니다. 이러한 임시 자격 증명을 요청할 때는 사용자 이름과 부여할 리소스 권한을 설명하는 IAM 정책을 제공해야 합니다. 세션은 기본적으로 1시간 동안 지속됩니다. 연합된 사용자 및 애플리케이션에 대한 임시 보안 자격 증명을 요청할 때는 다른 기간 값을 명시적으로 설정할 수 있습니다. 인증된 요청 전송에 대한 자세한 내용은 요청 만들기 단원을 참조하십시오.

참고

연합된 사용자 및 애플리케이션에 대한 임시 보안 자격 증명을 요청할 때 보안 강화를 위해 필요한 액세스 권한만 가진 전용 IAM 사용자를 사용하는 것이 좋습니다. 생성하는 임시 사용자는 임시 보안 자격 증명을 요청한 IAM 사용자보다 더 많은 권한을 가질 수 없습니다. 자세한 내용은 AWS Identity and Access Management FAQ를 참조하세요.

다음을 수행합니다.

  • AWS Security Token Service 클라이언트의 인스턴스인 AmazonSecurityTokenServiceClient 클래스를 만듭니다. 자격 증명 제공에 대한 자세한 내용은 AWS SDK for .NET 사용 단원을 참조하십시오.

  • STS 클라이언트의 GetFederationToken 메서드를 호출하여 세션을 시작합니다. 임시 자격 증명에 연결하려는 IAM 정책 및 사용자 이름을 비롯한 세션 정보를 제공해야 합니다. 경우에 따라 세션 기간을 제공할 수 있습니다. 이 메서드는 임시 보안 자격 증명을 반환합니다.

  • SessionAWSCredentials 객체의 인스턴스에 임시 보안 자격 증명을 패키지로 포함합니다. 이 객체를 사용하여 Amazon S3 클라이언트에 임시 보안 자격 증명을 제공합니다.

  • 임시 보안 자격 증명을 전달하여 AmazonS3Client 클래스의 인스턴스를 만듭니다. 이 클라이언트를 사용하여 Amazon S3에 요청을 보냅니다. 만료된 자격 증명을 사용하여 요청을 보낼 경우 Amazon S3에서 오류를 반환합니다.

다음 C# 예제는 지정된 버킷의 키를 나열합니다. 이 예제에서는 먼저 연합된 사용자(User1)를 위해 2시간의 세션에 대한 임시 보안 자격 증명을 가져오고 이 자격 증명을 사용하여 인증된 요청을 Amazon S3으로 보냅니다.

  • 이 연습에서는 최소한의 권한을 가진 IAM 사용자를 생성합니다. 이 IAM 사용자의 자격 증명을 사용하여 다른 사용자에 대한 임시 자격 증명을 요청합니다. 이 예제는 특정 버킷의 객체만 나열합니다. 다음과 같은 정책을 연결하여 IAM 사용자를 생성합니다.

    { "Statement":[{ "Action":["s3:ListBucket", "sts:GetFederationToken*" ], "Effect":"Allow", "Resource":"*" } ] }

    이 정책은 IAM 사용자에게 임시 보안 자격 증명을 요청하고, AWS 리소스를 나열할 수 있는 액세스 권한만 허용합니다. IAM 사용자를 만드는 방법에 대한 자세한 내용은 IAM 사용 설명서의 IAM 사용자 및 관리자 그룹 생성을 참조하세요.

  • IAM 사용자 보안 자격 증명을 사용하여 다음 예제를 테스트합니다. 이 예제에서는 임시 보안 자격 증명을 사용하여 인증된 요청을 Amazon S3으로 보냅니다. 이 예제에서는 연합된 사용자(User1)에 대한 임시 보안 자격 증명을 요청할 때 특정 버킷(YourBucketName)의 객체를 나열하는 데 필요한 액세스 권한을 제한하는 다음 정책을 지정합니다. 정책을 업데이트하고 자신의 기존 버킷 이름을 제공해야 합니다.

    { "Statement":[ { "Sid":"1", "Action":["s3:ListBucket"], "Effect":"Allow", "Resource":"arn:aws:s3:::YourBucketName" } ] }
  • 다음 샘플을 업데이트하고 이전 연동 사용자 액세스 정책에 지정한 버킷 이름을 제공합니다. 실제 예제를 작성하여 테스트하는 방법에 대한 자세한 내용은 Amazon S3 .NET 코드 예제 실행를 참조하십시오.

    using Amazon; using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Model; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; using System; using System.Collections.Generic; using System.Threading.Tasks; namespace Amazon.DocSamples.S3 { class TempFederatedCredentialsTest { private const string bucketName = "*** bucket name ***"; // Specify your bucket region (an example region is shown). private static readonly RegionEndpoint bucketRegion = RegionEndpoint.USWest2; private static IAmazonS3 client; public static void Main() { ListObjectsAsync().Wait(); } private static async Task ListObjectsAsync() { try { Console.WriteLine("Listing objects stored in a bucket"); // Credentials use the default AWS SDK for .NET credential search chain. // On local development machines, this is your default profile. SessionAWSCredentials tempCredentials = await GetTemporaryFederatedCredentialsAsync(); // Create a client by providing temporary security credentials. using (client = new AmazonS3Client(bucketRegion)) { ListObjectsRequest listObjectRequest = new ListObjectsRequest(); listObjectRequest.BucketName = bucketName; ListObjectsResponse response = await client.ListObjectsAsync(listObjectRequest); List<S3Object> objects = response.S3Objects; Console.WriteLine("Object count = {0}", objects.Count); Console.WriteLine("Press any key to continue..."); Console.ReadKey(); } } catch (AmazonS3Exception e) { Console.WriteLine("Error encountered ***. Message:'{0}' when writing an object", e.Message); } catch (Exception e) { Console.WriteLine("Unknown encountered on server. Message:'{0}' when writing an object", e.Message); } } private static async Task<SessionAWSCredentials> GetTemporaryFederatedCredentialsAsync() { AmazonSecurityTokenServiceConfig config = new AmazonSecurityTokenServiceConfig(); AmazonSecurityTokenServiceClient stsClient = new AmazonSecurityTokenServiceClient( config); GetFederationTokenRequest federationTokenRequest = new GetFederationTokenRequest(); federationTokenRequest.DurationSeconds = 7200; federationTokenRequest.Name = "User1"; federationTokenRequest.Policy = @"{ ""Statement"": [ { ""Sid"":""Stmt1311212314284"", ""Action"":[""s3:ListBucket""], ""Effect"":""Allow"", ""Resource"":""arn:aws:s3:::" + bucketName + @""" } ] } "; GetFederationTokenResponse federationTokenResponse = await stsClient.GetFederationTokenAsync(federationTokenRequest); Credentials credentials = federationTokenResponse.Credentials; SessionAWSCredentials sessionCredentials = new SessionAWSCredentials(credentials.AccessKeyId, credentials.SecretAccessKey, credentials.SessionToken); return sessionCredentials; } } }
PHP

이 주제에서는 AWS SDK for PHP 버전 3의 클래스를 사용하여 연합된 사용자 및 애플리케이션에 대한 임시 보안 자격 증명을 요청하고 이를 사용하여 Amazon S3에 저장된 리소스에 액세스하는 방법을 설명합니다. 이미 AWS SDK for PHP 사용 및 PHP 예제 실행의 지침에 따라 AWS SDK for PHP가 올바르게 설치되어 있다고 가정합니다.

AWS 리소스에 액세스하기 위해 인증된 요청을 보낼 수 있도록 페더레이션 사용자 및 애플리케이션에 임시 보안 자격 증명을 제공할 수 있습니다. 이러한 임시 자격 증명을 요청할 때는 사용자 이름과 부여할 리소스 권한을 설명하는 IAM 정책을 제공해야 합니다. 세션의 유효 기간이 만료되면 이 자격 증명도 만료됩니다. 세션은 기본적으로 1시간 동안 지속됩니다. 연동 사용자 및 애플리케이션에 대한 임시 보안 자격 증명을 요청할 때는 다른 기간 값을 명시적으로 설정할 수 있습니다. 임시 보안 자격 증명에 대한 자세한 내용은 IAM 사용 설명서임시 보안 자격 증명을 참조하세요. 연동 사용자와 애플리케이션에 임시 보안 자격 증명 제공에 대한 자세한 내용은 요청 만들기 단원을 참조하십시오.

연합된 사용자 및 애플리케이션에 대한 임시 보안 자격 증명을 요청할 때 보안 강화를 위해 필요한 액세스 권한만 가진 전용 IAM 사용자를 사용하는 것이 좋습니다. 생성하는 임시 사용자는 임시 보안 자격 증명을 요청한 IAM 사용자보다 더 많은 권한을 가질 수 없습니다. 자격 증명 연동에 대한 자세한 내용은 AWS Identity and Access Management FAQ를 참조하세요.

이 가이드의 PHP 예제 실행에 대한 자세한 내용은 PHP 예제 실행 섹션을 참조하세요.

다음 PHP 예제는 지정된 버킷의 키를 나열합니다. 이 예제에서는 먼저 연동 사용자(User1)를 위해 1시간짜리 세션에 대한 임시 보안 자격 증명을 가져오고 가져온 임시 보안 자격 증명을 사용하여 인증된 요청을 Amazon S3으로 보냅니다.

다른 사용자에 대한 임시 보안 자격 증명을 요청할 경우, 보안 강화를 위해 임시 자격 증명을 요청할 수 있는 IAM 사용자의 보안 자격 증명을 사용할 수 있습니다. IAM 사용자가 연합된 사용자에게 최소한의 애플리케이션별 권한만 부여하도록 이 IAM 사용자의 액세스 권한을 제한할 수도 있습니다. 이 예제는 특정 버킷의 객체만 나열합니다. 다음과 같은 정책을 연결하여 IAM 사용자를 생성합니다.

{ "Statement":[{ "Action":["s3:ListBucket", "sts:GetFederationToken*" ], "Effect":"Allow", "Resource":"*" } ] }

이 정책은 IAM 사용자에게 임시 보안 자격 증명을 요청하고, AWS 리소스를 나열할 수 있는 액세스 권한만 허용합니다. IAM 사용자를 만드는 방법에 대한 자세한 내용은 IAM 사용 설명서의 첫 번째 IAM 사용자 및 관리자 그룹 생성을 참조하세요.

이제 IAM 사용자 보안 자격 증명을 사용하여 다음 예제를 테스트할 수 있습니다. 이 예제에서는 임시 보안 자격 증명을 사용하여 인증된 요청을 Amazon S3으로 보냅니다. 이 예제에서는 연동 사용자(User1)에 대한 임시 보안 자격 증명을 요청할 때 특정 버킷의 객체를 나열하는 데 필요한 액세스 권한을 제한하는 다음 정책을 지정합니다. 정책을 자신의 버킷 이름으로 업데이트합니다.

{ "Statement":[ { "Sid":"1", "Action":["s3:ListBucket"], "Effect":"Allow", "Resource":"arn:aws:s3:::YourBucketName" } ] }

다음 예제에서는 정책 리소스를 지정할 때 YourBucketName을 자신의 기존 버킷 이름으로 대체합니다.

require 'vendor/autoload.php'; use Aws\S3\Exception\S3Exception; use Aws\S3\S3Client; use Aws\Sts\StsClient; $bucket = '*** Your Bucket Name ***'; // In real applications, the following code is part of your trusted code. It has // the security credentials that you use to obtain temporary security credentials. $sts = new StsClient([ 'version' => 'latest', 'region' => 'us-east-1' ]); // Fetch the federated credentials. $sessionToken = $sts->getFederationToken([ 'Name' => 'User1', 'DurationSeconds' => '3600', 'Policy' => json_encode([ 'Statement' => [ 'Sid' => 'randomstatementid' . time(), 'Action' => ['s3:ListBucket'], 'Effect' => 'Allow', 'Resource' => 'arn:aws:s3:::' . $bucket ] ]) ]); // The following will be part of your less trusted code. You provide temporary // security credentials so the code can send authenticated requests to Amazon S3. $s3 = new S3Client([ 'region' => 'us-east-1', 'version' => 'latest', 'credentials' => [ 'key' => $sessionToken['Credentials']['AccessKeyId'], 'secret' => $sessionToken['Credentials']['SecretAccessKey'], 'token' => $sessionToken['Credentials']['SessionToken'] ] ]); try { $result = $s3->listObjects([ 'Bucket' => $bucket ]); } catch (S3Exception $e) { echo $e->getMessage() . PHP_EOL; }
Ruby

AWS 리소스에 액세스하기 위해 인증된 요청을 보낼 수 있도록 페더레이션 사용자 및 애플리케이션에 대해 임시 보안 자격 증명을 제공할 수 있습니다. IAM 서비스로부터 이러한 임시 자격 증명을 요청할 경우 사용자 이름과 부여할 리소스 권한을 설명하는 IAM 정책을 제공해야 합니다. 세션은 기본적으로 1시간 동안 지속됩니다. 하지만 IAM 사용자 자격 증명을 사용하여 임시 자격 증명을 요청하면, 연합된 사용자 및 애플리케이션에 대해 임시 보안 자격 증명을 요청할 기간에 대해 다른 값을 명시적으로 설정할 수 있습니다. 연동 사용자와 애플리케이션의 임시 보안 자격 증명에 대한 자세한 내용은 요청 만들기 단원을 참조하십시오.

참고

연합된 사용자 및 애플리케이션에 대한 임시 보안 자격 증명을 요청할 때 보안 강화를 위해 필요한 액세스 권한만 가진 전용 IAM 사용자를 사용하는 것이 좋습니다. 생성하는 임시 사용자는 임시 보안 자격 증명을 요청한 IAM 사용자보다 더 많은 권한을 가질 수 없습니다. 자세한 내용은 AWS Identity and Access Management FAQ를 참조하세요.

다음 Ruby 코드 예제에서는 제한된 권한을 가진 연동 사용자가 지정된 버킷의 키를 나열하도록 합니다.

# Prerequisites: # - An existing Amazon S3 bucket. require "aws-sdk-s3" require "aws-sdk-iam" require "json" # Checks to see whether a user exists in IAM; otherwise, # creates the user. # # @param iam [Aws::IAM::Client] An initialized IAM client. # @param user_name [String] The user's name. # @return [Aws::IAM::Types::User] The existing or new user. # @example # iam = Aws::IAM::Client.new(region: 'us-west-2') # user = get_user(iam, 'my-user') # exit 1 unless user.user_name # puts "User's name: #{user.user_name}" def get_user(iam, user_name) puts "Checking for a user with the name '#{user_name}'..." response = iam.get_user(user_name: user_name) puts "A user with the name '#{user_name}' already exists." return response.user # If the user doesn't exist, create them. rescue Aws::IAM::Errors::NoSuchEntity puts "A user with the name '#{user_name}' doesn't exist. Creating this user..." response = iam.create_user(user_name: user_name) iam.wait_until(:user_exists, user_name: user_name) puts "Created user with the name '#{user_name}'." return response.user rescue StandardError => e puts "Error while accessing or creating the user named '#{user_name}': #{e.message}" end # Gets temporary AWS credentials for an IAM user with the specified permissions. # # @param sts [Aws::STS::Client] An initialized AWS STS client. # @param duration_seconds [Integer] The number of seconds for valid credentials. # @param user_name [String] The user's name. # @param policy [Hash] The access policy. # @return [Aws::STS::Types::Credentials] AWS credentials for API authentication. # @example # sts = Aws::STS::Client.new(region: 'us-west-2') # credentials = get_temporary_credentials(sts, duration_seconds, user_name, # { # 'Version' => '2012-10-17', # 'Statement' => [ # 'Sid' => 'Stmt1', # 'Effect' => 'Allow', # 'Action' => 's3:ListBucket', # 'Resource' => 'arn:aws:s3:::doc-example-bucket' # ] # } # ) # exit 1 unless credentials.access_key_id # puts "Access key ID: #{credentials.access_key_id}" def get_temporary_credentials(sts, duration_seconds, user_name, policy) response = sts.get_federation_token( duration_seconds: duration_seconds, name: user_name, policy: policy.to_json ) return response.credentials rescue StandardError => e puts "Error while getting federation token: #{e.message}" end # Lists the keys and ETags for the objects in an Amazon S3 bucket. # # @param s3_client [Aws::S3::Client] An initialized Amazon S3 client. # @param bucket_name [String] The bucket's name. # @return [Boolean] true if the objects were listed; otherwise, false. # @example # s3_client = Aws::S3::Client.new(region: 'us-west-2') # exit 1 unless list_objects_in_bucket?(s3_client, 'doc-example-bucket') def list_objects_in_bucket?(s3_client, bucket_name) puts "Accessing the contents of the bucket named '#{bucket_name}'..." response = s3_client.list_objects_v2( bucket: bucket_name, max_keys: 50 ) if response.count.positive? puts "Contents of the bucket named '#{bucket_name}' (first 50 objects):" puts "Name => ETag" response.contents.each do |obj| puts "#{obj.key} => #{obj.etag}" end else puts "No objects in the bucket named '#{bucket_name}'." end return true rescue StandardError => e puts "Error while accessing the bucket named '#{bucket_name}': #{e.message}" end # Example usage: def run_me region = "us-west-2" user_name = "my-user" bucket_name = "doc-example-bucket" iam = Aws::IAM::Client.new(region: region) user = get_user(iam, user_name) exit 1 unless user.user_name puts "User's name: #{user.user_name}" sts = Aws::STS::Client.new(region: region) credentials = get_temporary_credentials(sts, 3600, user_name, { "Version" => "2012-10-17", "Statement" => [ "Sid" => "Stmt1", "Effect" => "Allow", "Action" => "s3:ListBucket", "Resource" => "arn:aws:s3:::#{bucket_name}" ] } ) exit 1 unless credentials.access_key_id puts "Access key ID: #{credentials.access_key_id}" s3_client = Aws::S3::Client.new(region: region, credentials: credentials) exit 1 unless list_objects_in_bucket?(s3_client, bucket_name) end run_me if $PROGRAM_NAME == __FILE__

관련 리소스