Skip to content

Instantly share code, notes, and snippets.

@moosejaw
Last active October 11, 2022 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moosejaw/051ca458c45796b8ddc38bb05df2ef53 to your computer and use it in GitHub Desktop.
Save moosejaw/051ca458c45796b8ddc38bb05df2ef53 to your computer and use it in GitHub Desktop.
Azure Powershell: How to get AKS kubeconfig from Azure Resource Manager API and use in kubectl commands.
param(
[Parameter(Position=0,mandatory=$true)]
[string]$SubscriptionId,
[Parameter(Position=1,mandatory=$true)]
[string]$ResourceGroupName,
[Parameter(Position=2,mandatory=$true)]
[string]$ResourceName
)
# Get the API access token using Azure Powershell
$Token = Get-AzAccessToken | Select-Object -ExpandProperty Token
# Construct the URL and send the request. The token is added to the Authorization header as a bearer token
$AccessProfileURL = "https://management.azure.com/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroupName/providers/Microsoft.ContainerService/managedClusters/$ResourceName/listClusterAdminCredential?api-version=2022-04-01"
$AccessProfile = Invoke-WebRequest -Method "POST" -Headers @{Authorization = "Bearer $Token"; "Content-Length" = 0; "Content-Type" = "application/json"} -Uri $AccessProfileURL
if ($AccessProfile.StatusCode -ne 200)
{
Throw "Got non-200 response code from Azure API."
}
# Extract the response and load into a Powershell object
$AccessProfile = $AccessProfile | Select-Object -ExpandProperty "Content" | ConvertFrom-Json
# Create a temporary kubeconfig file and write the kubeconfig data in the response to it.
# The data is base64 encoded in the response, so needs to be decoded
$TempKubeConfig = New-TemporaryFile
Write-Output $AccessProfile.kubeconfigs[0].value | base64 -d | Out-File $TempKubeConfig.FullName
# Temporarily save the path to the kubeconfig file in environment variables
$env:KUBECONFIG = $TempKubeConfig.FullName
# Once we're done, we can clean up by unsetting the environment variable and removing the temp file
$env:KUBECONFIG = ''
if (Test-Path -Path $TempKubeConfig.FullName -PathType Leaf)
{
Remove-Item $TempKubeConfig.FullName
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment