

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

# Perbarui kredensyal AWS CLI dari AWS IAM Identity Center dengan menggunakan PowerShell
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell"></a>

*Cad Miles dan Andy Bowen, Amazon Web Services*

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

Jika Anda ingin menggunakan kredensil AWS IAM Identity Center (penerus AWS Single Sign-On) dengan AWS Command Line Interface (AWS CLI), AWS, atau AWS Cloud Development Kit ( SDKsAWS CDK), Anda biasanya harus menyalin dan menempelkan kredensional dari konsol IAM Identity Center ke antarmuka baris perintah. Proses ini dapat memakan waktu yang cukup lama dan harus diulang untuk setiap akun yang memerlukan akses.

Salah satu solusi umum adalah dengan menggunakan perintah AWS CLI`aws sso configure`. Perintah ini menambahkan profil yang diaktifkan IAM Identity Center ke AWS CLI atau AWS SDK Anda. Namun, kelemahan dari solusi ini adalah Anda harus menjalankan perintah `aws sso login` untuk setiap profil AWS CLI atau akun yang telah Anda konfigurasikan dengan cara ini.

Sebagai solusi alternatif, pola ini menjelaskan cara menggunakan [profil bernama](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles) AWS CLI dan AWS Tools untuk menyimpan dan menyegarkan kredensil PowerShell untuk beberapa akun dari satu instans Pusat Identitas IAM secara bersamaan. Skrip ini juga menyimpan data sesi Pusat Identitas IAM di memori untuk menyegarkan kredensyal tanpa masuk ke Pusat Identitas IAM lagi.

## Prasyarat dan batasan
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-prereqs"></a>

**Prasyarat**
+ PowerShell, diinstal dan dikonfigurasi. Untuk informasi selengkapnya, lihat [Menginstal PowerShell](https://learn.microsoft.com/en-us/powershell/scripting/install/installing-powershell?view=powershell-7.3) (dokumentasi Microsoft).
+ AWS Tools untuk PowerShell, diinstal, dan dikonfigurasi. Untuk alasan kinerja, kami sangat menyarankan Anda menginstal AWS Tools versi termodulasi untuk PowerShell, yang disebut. `AWS.Tools` Setiap layanan AWS didukung oleh modul kecil individualnya sendiri. Dalam PowerShell prompt, masukkan perintah berikut untuk menginstal modul yang diperlukan untuk pola ini:`AWS.Tools.Installer`,`SSO`, dan`SSOIDC`.

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

  Untuk informasi selengkapnya, lihat [Menginstal AWS.Tools di Windows](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up-windows.html#ps-installing-awstools) atau [Menginstal AWS.Tools di Linux](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-getting-set-up-linux-mac.html#install-aws.tools-on-linux-macos) atau macOS.
+ AWS CLI atau AWS SDK harus dikonfigurasi sebelumnya dengan kredensyal kerja dengan melakukan salah satu hal berikut:
  + Gunakan perintah AWS CLI`aws configure`. Untuk informasi selengkapnya, lihat [Konfigurasi cepat](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html#cli-configure-quickstart-config) (dokumentasi AWS CLI).
  + Konfigurasikan AWS CLI atau AWS CDK untuk mendapatkan akses sementara melalui peran IAM. Untuk informasi selengkapnya, lihat [Mendapatkan kredensyal peran IAM untuk akses CLI](https://docs.aws.amazon.com/singlesignon/latest/userguide/howtogetcredentials.html) (dokumentasi Pusat Identitas IAM).

**Batasan**
+ Skrip ini tidak dapat digunakan dalam pipeline atau solusi yang sepenuhnya otomatis. Ketika Anda menyebarkan skrip ini, Anda harus secara manual mengotorisasi akses dari IAM Identity Center. Script kemudian berlanjut secara otomatis.

**Versi produk**
+ Untuk semua sistem operasi, disarankan agar Anda menggunakan [PowerShell versi 7.0](https://github.com/powershell/powershell) atau yang lebih baru.

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

Anda dapat menggunakan skrip dalam pola ini untuk menyegarkan beberapa kredensional Pusat Identitas IAM secara bersamaan, dan Anda dapat membuat file kredensi untuk digunakan dengan AWS CLI, AWS, atau SDKs AWS CDK.

![\[Menggunakan PowerShell skrip untuk memperbarui kredensyal di AWS CLI, AWS CDK, atau AWS. SKDs\]](http://docs.aws.amazon.com/id_id/prescriptive-guidance/latest/patterns/images/pattern-img/6d54a6bb-01ac-4736-9b78-40921fcc9056/images/01e0fcb6-3b48-422c-8868-07a7de83b3e3.png)


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

**Layanan AWS**
+ [AWS Command Line Interface (AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)) adalah alat sumber terbuka yang membantu Anda berinteraksi dengan layanan AWS melalui perintah di shell baris perintah Anda.
+ [AWS IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html) membantu Anda mengelola akses masuk tunggal (SSO) secara terpusat ke semua akun AWS dan aplikasi cloud Anda.
+ [AWS Tools for PowerShell](https://docs.aws.amazon.com/powershell/latest/userguide/pstools-welcome.html) adalah sekumpulan PowerShell modul yang membantu Anda menjalankan skrip pada sumber daya AWS Anda dari baris PowerShell perintah.

**Alat-alat lainnya**
+ [PowerShell](https://learn.microsoft.com/en-us/powershell/)adalah program manajemen otomatisasi dan konfigurasi Microsoft yang berjalan di Windows, Linux, dan macOS.

## Praktik terbaik
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-best-practices"></a>

Simpan satu salinan skrip ini untuk setiap instance IAM Identity Center. Menggunakan satu skrip untuk beberapa instance tidak didukung.

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

### Jalankan skrip SSO
<a name="run-the-sso-script"></a>


| Tugas | Deskripsi | Keterampilan yang dibutuhkan | 
| --- | --- | --- | 
| Sesuaikan skrip SSO. | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/id_id/prescriptive-guidance/latest/patterns/update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell.html) | Administrator awan | 
| Jalankan skrip SSO. | Disarankan agar Anda menjalankan skrip kustom Anda di PowerShell shell dengan perintah berikut.<pre>./Set-AwsCliSsoCredentials.ps1</pre>Atau, Anda dapat menjalankan skrip dari shell lain dengan memasukkan perintah berikut.<pre>pwsh Set-AwsCliSsoCredentials.ps1</pre> | Administrator awan | 

## Pemecahan masalah
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-troubleshooting"></a>


| Isu | Solusi | 
| --- | --- | 
| `No Access` kesalahan | Peran IAM yang Anda gunakan tidak memiliki izin untuk mengakses peran atau set izin yang Anda tetapkan dalam parameter. `RoleName` Perbarui izin untuk peran yang Anda gunakan, atau tentukan peran atau izin yang berbeda yang ditetapkan dalam skrip. | 

## Sumber daya terkait
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-resources"></a>
+ [Di mana pengaturan konfigurasi disimpan?](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-where) (Dokumentasi AWS CLI)
+ [Mengonfigurasi AWS CLI untuk menggunakan AWS IAM Identity Center](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sso.html) (dokumentasi AWS CLI)
+ [Menggunakan profil bernama](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html#cli-configure-files-using-profiles) (dokumentasi AWS CLI)

## Informasi tambahan
<a name="update-aws-cli-credentials-from-aws-iam-identity-center-by-using-powershell-additional"></a>

**Skrip SSO**

Dalam skrip berikut, ganti placeholder dalam kurung sudut (<>) dengan informasi Anda sendiri dan lepaskan tanda kurung sudut.

```
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"
```