Created
July 13, 2023 17:02
-
-
Save jimbo8098/43a30543198807e0584a59556c4aaf9f to your computer and use it in GitHub Desktop.
Replicate Docker credential locally from a Kubernetes secret
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
param ( | |
[switch] | |
$Overwrite = $false, | |
# If DockerServer is null, script performs the operation on all servers in the registry credential | |
[string] | |
$DockerServer = $null, | |
[string] | |
$SecretName = "regcred", | |
[string] | |
$Namespace = "default", | |
# Provide the output of, for example, "kubectl get secret/regcred -o yaml | ConvertFrom-Yaml" | |
[Parameter(ValueFromPipeline = $true)] | |
[PSObject] | |
$SecretContent = $null | |
) | |
function ConvertFrom-Base64 { | |
[Parameter(ValueFromPipeline = $true)] | |
param ($In) | |
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($In)) | |
} | |
if([string]::IsNullOrEmpty($SecretContent)) { | |
$secret = kubectl -n $Namespace get secret/$SecretName -o yaml | ConvertFrom-Yaml | |
} else { | |
$secret = $SecretContent | |
} | |
$regcred = ConvertFrom-Base64 $secret.data.'.dockerconfigjson' | ConvertFrom-Json | |
$servers = $regcred.auths | Get-Member -MemberType NoteProperty | Select -ExpandProperty Name | |
$matched = $false | |
foreach ($server in $servers) { | |
if([string]::IsNullOrEmpty($DockerServer) -or $server -eq $DockerServer) { | |
$matched = $true | |
if($Overwrite) { | |
Write-Host "Log out of ${server}" | |
docker logout $server | |
} | |
Write-Host "Log into ${server}" | |
$regcred.auths.$server.password | docker login $server --username $regcred.auths.$server.username --password-stdin | |
} | |
} | |
if(!$matched) { | |
if([string]::IsNullOrEmpty($DockerServer)) { | |
Write-Error "No servers are defined in the list of credentials" | |
} else { | |
Write-Error "Didn't find $DockerServer in the list of servers" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment