AWS SDK for .NET를 사용하는 간단한 교차 플랫폼 애플리케이션 - AWS SDK for .NET

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

AWS SDK for .NET를 사용하는 간단한 교차 플랫폼 애플리케이션

이 자습서에서는 교차 플랫폼 개발을 위해 .NET Core와 AWS SDK for .NET를 사용합니다. 이 자습서는 SDK를 사용하여 소유한 Amazon S3 버킷을 나열하고 선택적으로 버킷을 생성하는 방법을 보여줍니다.

.NET 명령줄 인터페이스(CLI)와 같은 교차 플랫폼 도구를 사용하여 이 자습서를 수행합니다. 개발 환경을 구성하는 다른 방법은 도구 체인 설치 및 구성을 참조하십시오.

Windows, Linux 또는 macOS에서 교차 플랫폼 .NET 개발에 대한 필수 항목:

  • Microsoft .NET Core SDK, 버전 2.1, 3.1 이상. 여기에는 .NET 명령줄 인터페이스 (CLI)(dotnet) 및 .NET Core 런타임이 포함되어 있습니다.

참고

이 자습서를 사용하기 전에 먼저 도구 체인을 설치하고 SDK 인증을 구성해야 합니다.

단계

프로젝트 생성

  1. 명령 프롬프트 또는 터미널을 엽니다. .NET 프로젝트를 만들 수 있는 운영 체제 폴더를 찾거나 생성합니다.

  2. 해당 폴더에서 다음 명령을 실행하여 .NET 프로젝트를 만듭니다.

    dotnet new console --name S3CreateAndList
  3. 새로 만든 S3CreateAndList 폴더로 이동하여 다음 명령을 실행합니다.

    dotnet add package AWSSDK.S3 dotnet add package AWSSDK.SecurityToken dotnet add package AWSSDK.SSO dotnet add package AWSSDK.SSOOIDC

    위의 명령은 NuGet 패키지 관리자에서 NuGet 패키지를 설치합니다. 이 자습서에 필요한 NuGet 패키지를 정확하게 알고 있으므로 이제 이 단계를 수행할 수 있습니다. 또한 필요한 패키지가 개발 중에 알려지게 되는 것이 일반적입니다. 이 경우 비슷한 명령을 실행할 수 있습니다.

코드 생성

  1. S3CreateAndList 폴더에서 Program.cs를 찾아 코드 편집기에서 엽니다.

  2. 내용을 다음 코드로 바꾸고 파일을 저장합니다.

    using System; using System.Threading.Tasks; // NuGet packages: AWSSDK.S3, AWSSDK.SecurityToken, AWSSDK.SSO, AWSSDK.SSOOIDC using Amazon.Runtime; using Amazon.Runtime.CredentialManagement; using Amazon.S3; using Amazon.S3.Model; using Amazon.SecurityToken; using Amazon.SecurityToken.Model; namespace S3CreateAndList { class Program { // This code is part of the quick tour in the developer guide. // See https://docs.aws.amazon.com/sdk-for-net/v3/developer-guide/quick-start.html // for complete steps. // Requirements: // - An SSO profile in the SSO user's shared config file with sufficient privileges for // STS and S3 buckets. // - An active SSO Token. // If an active SSO token isn't available, the SSO user should do the following: // In a terminal, the SSO user must call "aws sso login". // Class members. static async Task Main(string[] args) { // Get SSO credentials from the information in the shared config file. // For this tutorial, the information is in the [default] profile. var ssoCreds = LoadSsoCredentials("default"); // Display the caller's identity. var ssoProfileClient = new AmazonSecurityTokenServiceClient(ssoCreds); Console.WriteLine($"\nSSO Profile:\n {await ssoProfileClient.GetCallerIdentityArn()}"); // Create the S3 client is by using the SSO credentials obtained earlier. var s3Client = new AmazonS3Client(ssoCreds); // Parse the command line arguments for the bucket name. if (GetBucketName(args, out String bucketName)) { // If a bucket name was supplied, create the bucket. // Call the API method directly try { Console.WriteLine($"\nCreating bucket {bucketName}..."); var createResponse = await s3Client.PutBucketAsync(bucketName); Console.WriteLine($"Result: {createResponse.HttpStatusCode.ToString()}"); } catch (Exception e) { Console.WriteLine("Caught exception when creating a bucket:"); Console.WriteLine(e.Message); } } // Display a list of the account's S3 buckets. Console.WriteLine("\nGetting a list of your buckets..."); var listResponse = await s3Client.ListBucketsAsync(); Console.WriteLine($"Number of buckets: {listResponse.Buckets.Count}"); foreach (S3Bucket b in listResponse.Buckets) { Console.WriteLine(b.BucketName); } Console.WriteLine(); } // // Method to parse the command line. private static Boolean GetBucketName(string[] args, out String bucketName) { Boolean retval = false; bucketName = String.Empty; if (args.Length == 0) { Console.WriteLine("\nNo arguments specified. Will simply list your Amazon S3 buckets." + "\nIf you wish to create a bucket, supply a valid, globally unique bucket name."); bucketName = String.Empty; retval = false; } else if (args.Length == 1) { bucketName = args[0]; retval = true; } else { Console.WriteLine("\nToo many arguments specified." + "\n\ndotnet_tutorials - A utility to list your Amazon S3 buckets and optionally create a new one." + "\n\nUsage: S3CreateAndList [bucket_name]" + "\n - bucket_name: A valid, globally unique bucket name." + "\n - If bucket_name isn't supplied, this utility simply lists your buckets."); Environment.Exit(1); } return retval; } // // Method to get SSO credentials from the information in the shared config file. static AWSCredentials LoadSsoCredentials(string profile) { var chain = new CredentialProfileStoreChain(); if (!chain.TryGetAWSCredentials(profile, out var credentials)) throw new Exception($"Failed to find the {profile} profile"); return credentials; } } // Class to read the caller's identity. public static class Extensions { public static async Task<string> GetCallerIdentityArn(this IAmazonSecurityTokenService stsClient) { var response = await stsClient.GetCallerIdentityAsync(new GetCallerIdentityRequest()); return response.Arn; } } }

애플리케이션을 실행합니다

  1. 다음 명령을 실행합니다.

    dotnet run
  2. 출력을 검사하여 소유한 Amazon S3 버킷 수(있는 경우)와 해당 이름을 확인합니다.

  3. 새 Amazon S3 버킷의 이름을 선택합니다. "dotnet-quicktour-s3-1-cross-"를 기본으로 사용하고 GUID 또는 사용자 이름과 같은 고유한 항목을 추가합니다. Amazon S3 사용 설명서버킷 이름 지정 규칙에 설명된 대로 버킷 이름 규칙을 준수해야 합니다.

  4. 다음 명령을 실행하여 BUCKET-NAME을 선택한 버킷의 이름으로 바꿉니다.

    dotnet run BUCKET-NAME
  5. 출력을 검사하여 생성된 새 버킷을 확인합니다.

정리

이 자습서를 수행하는 동안 현재 정리하도록 선택할 수 있는 몇 가지 리소스를 만들었습니다.

  • 이전 단계에서 애플리케이션이 생성한 버킷을 유지하지 않으려면 https://console.aws.amazon.com/s3/에서 Amazon S3 콘솔을 사용하여 삭제합니다.

  • .NET 프로젝트를 유지하지 않으려면 개발 환경에서 S3CreateAndList 폴더를 제거하십시오.

다음으로 진행할 단계

간략한 설명 메뉴로 이동하거나 이 간략한 설명의 끝으로 바로 이동합니다.