

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

# PowerShell을 사용하여 AWS IAM Identity Center의 보안 인증 정보를 업데이트합니다.
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell"></a>

*Chad Miles, Andy Bowen, Amazon Web Services*

## 요약
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-summary"></a>

AWS Command Line Interface(AWS CLI), AWS SDK 또는 AWS Cloud Development Kit(AWS CDK)와 함께 AWS IAM Identity Center(AWS Single Sign-On의 후속) 보안 인증 정보를 사용하려면 일반적으로 IAM Identity Center 콘솔의 보안 인증 정보를 복사하여 명령줄 인터페이스에 붙여 넣어야 합니다. 이 프로세스는 상당한 시간이 소요될 수 있으며 액세스가 필요한 각 계정에 대해 반복해야 합니다.

일반적인 해결 방법 중 하나는 AWS CLI `aws sso configure` 명령을 사용하는 것입니다. 이 명령은 IAM Identity Center 지원 프로필을 AWS CLI 또는 AWS SDK에 추가합니다. 하지만 이 솔루션의 단점은 이러한 방식으로 구성한 각 AWS CLI 프로필 또는 계정에 대해 `aws sso login` 명령을 실행해야 한다는 것입니다.

대체 방안으로서 이 패턴은 AWS CLI [명명된 프로필](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles)과 AWS Tools for PowerShell을 사용하여 단일 IAM Identity Center 인스턴스에서 여러 계정의 보안 인증 정보를 동시에 저장하고 새로 고치는 방법을 설명합니다. 또한 이 스크립트는 IAM Identity Center에 다시 로그인하지 않고도 보안 인증 정보를 새로 고칠 수 있도록 IAM Identity Center 세션 데이터를 메모리에 저장합니다.

## 사전 조건 및 제한 사항
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-prereqs"></a>

**사전 조건 **
+ 설치 및 구성된 PowerShell입니다. 자세한 내용은 [PowerShell 설치](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.3)(Microsoft 설명서)를 참조하세요.
+ 설치 및 구성된 AWS Tools for PowerShell입니다. 성능상의 이유로 `AWS.Tools`로 부르는 AWS Tools for PowerShell의 모듈화된 버전을 설치하는 것이 좋습니다. 각 AWS 서비스는 개별적인 소형 모듈에서 지원됩니다. PowerShell 프롬프트에서 다음 명령을 입력하여 이 패턴에 필요한 `AWS.Tools.Installer`, `SSO`, `SSOIDC` 모듈을 설치합니다.

  ```
  Install-Module AWS.Tools.Installer
  Install-AWSToolsModule SSO, SSOOIDC
  ```

  자세한 내용은 [Windows에 AWS.Tools 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up-windows.html#ps-installing-awstools) 또는 [Linux 또는 macOS에 AWS.Tools 설치](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up-linux-mac.html#install-aws.tools-on-linux-macos)를 참조하세요.
+ 다음 중 하나를 수행하여 AWS CLI 또는 AWS SDK를 유효한 보안 인증 정보로 미리 구성해야 합니다.
  + AWS CLI `aws configure` 명령을 사용합니다. 자세한 내용을 알아보려면 [빠른 구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config)(AWS CLI 설명서)을 참조하세요.
  + IAM 역할을 통해 일시적으로 액세스할 수 있도록 AWS CLI 또는 AWS CDK를 구성합니다. 자세한 내용은 [CLI 액세스를 위한 IAM 역할 보안 인증 정보 가져오기](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html)(IAM Identity Center 설명서)를 참조하세요.

**제한 사항 **
+ 이 스크립트는 파이프라인 또는 완전 자동화된 솔루션에서 사용할 수 없습니다. 이 스크립트를 배포할 때는 IAM Identity Center에서 수동으로 액세스를 승인해야 합니다. 그러면 스크립트가 자동으로 계속됩니다.

**제품 버전**
+ 모든 운영 체제에서는 [PowerShell 버전 7.0](https://github.com/powershell/powershell) 이상을 사용하는 것이 좋습니다.

## 아키텍처
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-architecture"></a>

이 패턴의 스크립트를 사용하여 여러 IAM Identity Center 보안 인증 정보를 동시에 새로 고치고, AWS CLI, AWS SDK 또는 AWS CDK와 함께 사용할 보안 인증 정보 파일을 생성할 수 있습니다.

![\[PowerShell 스크립트를 사용하여 AWS CLI, AWS CDK 또는 AWS SKD에서 자격 증명 업데이트.\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/images/pattern-img/6d54a6bb-01ac-4736-9b78-40921fcc9056/images/01e0fcb6-3b48-422c-8868-07a7de83b3e3.png)


## 도구
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-tools"></a>

**서비스**
+ [AWS Command Line Interface (AWS CLI)](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)는 명령줄 쉘에서 명령을 사용하여 AWS 서비스와 상호 작용할 수 있는 오픈 소스 도구입니다.
+ [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html)를 사용하면 모든 AWS 계정과 클라우드 애플리케이션에 대한 AWS Single Sign-On(SSO) 액세스를 중앙에서 관리할 수 있습니다.
+ [AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-welcome.html)은 PowerShell 명령줄에서 AWS 리소스에 대한 작업을 스크립팅하는 데 도움이 되는 PowerShell 모듈 세트입니다.

**기타 도구**
+ [PowerShell](https://learn.microsoft.com/en-us/powershell/)은 Windows, Linux 및 macOS에서 실행되는 마이크로소프트 자동화 및 구성 관리 프로그램입니다.

## 모범 사례
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-best-practices"></a>

각 IAM Identity Center 인스턴스마다 이 스크립트 사본을 하나씩 보관합니다. 여러 인스턴스에 하나의 스크립트를 사용하는 것은 지원되지 않습니다.

## 에픽
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-epics"></a>

### SSO 스크립트 실행
<a name="run-the-sso-script"></a>


| 작업 | 설명 | 필요한 기술 | 
| --- | --- | --- | 
| SSO 스크립트를 사용자 지정합니다. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ko_kr/prescriptive-guidance/latest/patterns/update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell.html) | 클라우드 관리자 | 
| SSO 스크립트 실행. | PowerShell 쉘에서 다음 명령을 사용하여 사용자 지정 스크립트를 실행하는 것이 좋습니다.<pre>./Set-AwsCliSsoCredentials.ps1</pre>다음 명령을 입력하여 다른 쉘에서 스크립트를 실행할 수도 있습니다.<pre>pwsh Set-AwsCliSsoCredentials.ps1</pre> | 클라우드 관리자 | 

## 문제 해결
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-troubleshooting"></a>


| 문제 | Solution | 
| --- | --- | 
| `No Access` 오류 | 사용 중인 IAM 역할에는 `RoleName` 파라미터에 정의한 역할 또는 권한 세트에 액세스할 수 있는 권한이 없습니다. 사용 중인 역할의 권한을 업데이트하거나 스크립트에서 다른 역할 또는 권한 세트를 정의합니다. | 

## 관련 리소스
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-resources"></a>
+ [구성 설정이 저장되는 장소는 어딘가요?](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-where) (AWS CLI 설명서)
+ [AWS IAM Identity Center를 사용하도록 AWS CLI 구성](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html)(AWS CLI 설명서)
+ [명명된 프로필 사용](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles)(AWS CLI 설명서)

## 추가 정보
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-additional"></a>

**SSO 스크립트**

다음 스크립트에서 꺾쇠 괄호(<>) 안의 자리 표시자를 사용자 고유의 정보로 바꾸고 꺾쇠 괄호를 제거합니다.

```
Set-AwsCliSsoCredentials.ps1
Param(
    $DefaultRoleName = '<AWSAdministratorAccess>',
    $Region          = '<us-west-2>',
    $StartUrl        = "<https://d-12345abcde.awsapps.com/start/>",
    $EnvironmentName = "<CompanyName>"
) 
Try {$SsoAwsAccounts = (Get-Variable -name "$($EnvironmentName)SsoAwsAccounts" -Scope Global -ErrorAction 'SilentlyContinue').Value.Clone()} 
Catch {$SsoAwsAccounts = $False}
if (-not $SsoAwsAccounts) { $SsoAwsAccounts = @(    
# Add your account information in the list of hash tables below, expand as necessary, and do not forget the commas 
    @{Profile = "<Account1>"      ; AccountId = "<012345678901 >"; RoleName = $DefaultRoleName },
    @{Profile = "<Account2>"      ; AccountId = "<123456789012>"; RoleName = "<AWSReadOnlyAccess>" }
)}
$ErrorActionPreference = "Stop"
if (-not (Test-Path ~\.aws))      { New-Item ~\.aws -type Directory }
if (-not (Test-Path ~\.aws\credentials)) { New-Item ~\.aws\credentials -type File }
$CredentialFile = Resolve-Path ~\.aws\credentials 
$PsuedoCreds    = @{AccessKey = 'AKAEXAMPLE123ACCESS';SecretKey='PsuedoS3cret4cceSSKey123PsuedoS3cretKey'} # Pseudo Creds, do not edit.
Try {$SSOTokenExpire = (Get-Variable -Scope Global -Name "$($EnvironmentName)SSOTokenExpire" -ErrorAction 'SilentlyContinue').Value} Catch {$SSOTokenExpire = $False}
Try {$SSOToken       = (Get-Variable -Scope Global -Name "$($EnvironmentName)SSOToken" -ErrorAction 'SilentlyContinue').Value }      Catch {$SSOToken       = $False}
if ( $SSOTokenExpire -lt (Get-Date) ) {
    $SSOToken = $Null
    $Client   = Register-SSOOIDCClient -ClientName cli-sso-client -ClientType public -Region $Region @PsuedoCreds
    $Device   = $Client | Start-SSOOIDCDeviceAuthorization -StartUrl $StartUrl -Region $Region @PsuedoCreds
    Write-Host "A Browser window should open. Please login there and click ALLOW." -NoNewline
    Start-Process $Device.VerificationUriComplete
    While (-Not $SSOToken){
        Try {$SSOToken = $Client | New-SSOOIDCToken -DeviceCode $Device.DeviceCode -GrantType "urn:ietf:params:oauth:grant-type:device_code" -Region $Region @PsuedoCreds}
        Catch {If ($_.Exception.Message -notlike "*AuthorizationPendingException*"){Write-Error $_.Exception} ; Start-Sleep 1}
    }
    $SSOTokenExpire = (Get-Date).AddSeconds($SSOToken.ExpiresIn)
    Set-Variable -Name "$($EnvironmentName)SSOToken" -Value $SSOToken -Scope Global
    Set-Variable -Name "$($EnvironmentName)SSOTokenExpire" -Value $SSOTokenExpire -Scope Global
}
$CredsTime     = $SSOTokenExpire - (Get-Date)
$CredsTimeText = ('{0:D2}:{1:D2}:{2:D2} left on SSO Token' -f $CredsTime.Hours, $CredsTime.Minutes, $CredsTime.Seconds).TrimStart("0 :")
for ($i = 0; $i -lt $SsoAwsAccounts.Count; $i++) {
    if (([DateTimeOffset]::FromUnixTimeSeconds($SsoAwsAccounts[$i].CredsExpiration / 1000)).DateTime -lt (Get-Date).ToUniversalTime()) {
        Write-host "`r                                                                     `rRegistering Profile $($SsoAwsAccounts[$i].Profile)" -NoNewline
        $TempCreds = $SSOToken | Get-SSORoleCredential -AccountId $SsoAwsAccounts[$i].AccountId -RoleName $SsoAwsAccounts[$i].RoleName -Region $Region @PsuedoCreds
        [PSCustomObject]@{AccessKey = $TempCreds.AccessKeyId; SecretKey = $TempCreds.SecretAccessKey; SessionToken = $TempCreds.SessionToken
        } | Set-AWSCredential -StoreAs $SsoAwsAccounts[$i].Profile -ProfileLocation $CredentialFile 
        $SsoAwsAccounts[$i].CredsExpiration = $TempCreds.Expiration
    }
} 
Set-Variable -name "$($EnvironmentName)SsoAwsAccounts" -Value $SsoAwsAccounts.Clone() -Scope Global
Write-Host "`r$($SsoAwsAccounts.Profile) Profiles registered, $CredsTimeText"
```