Created
January 8, 2021 11:15
-
-
Save stknohg/237b7099fd12d9187d9913f14ecfdb4c to your computer and use it in GitHub Desktop.
Set-AWSCredentialと同時にプロファイルに設定されているリージョンをデフォルト設定する関数
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function Set-AWSCredentialWithRegion { | |
[CmdletBinding()] | |
param ( | |
[string]$ProfileName | |
) | |
# Invoke Set-AWSCredential first | |
Write-Verbose "Invoke Set-AWSCredential -ProfileName $ProfileName " | |
Set-AWSCredential -ProfileName $ProfileName -Scope Global | |
if (-not $StoredAWSCredentials) { | |
return | |
} | |
# (just in case) check if the credential source is profile | |
$typeCredential = $StoredAWSCredentials.GetType() | |
$propSource = $typeCredential.GetProperty("Source", [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Instance) | |
$propSourceValue = $propSource.GetValue($StoredAWSCredentials) | |
if ($propSourceValue -ne "Profile") { | |
Write-Verbose "Current credential source is not the 'Profile'... ($propSourceValue)" | |
return | |
} | |
# find region name from shared credential file, and set the default region. | |
$profileObject = $null | |
if (-not [Amazon.PowerShell.Common.SettingsStore]::TryGetProfile($StoredAWSCredentials.ToString(), "$HOME/.aws/credentials", [ref]$profileObject)) { | |
return | |
} | |
$autoRegistRegionName = $profileObject.Region.SystemName | |
if ($autoRegistRegionName) { | |
Write-Verbose "Success! Set default region to $autoRegistRegionName..." | |
Write-Verbose "Invoke Set-DefaultAWSRegion -Region $autoRegistRegionName " | |
Set-DefaultAWSRegion -Region $autoRegistRegionName -Scope Global | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment