Last active
October 11, 2022 19:36
-
-
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.
This file contains 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( | |
[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