Find public IP address for Azure Kubernetes Service (AKS) using PowerShell

As part of my automation pipeline, I wanted to automatically create a few A records in Cloudflare that point to my AKS kubernetes cluster. I was creating the records using Terraform. Unfortuantely, at the time of writing, the azurerm provider for Terraform does not have a data source for load balancers.

Instead, I could use a PowerShell script to find the public IP address, and then pass the value in as a variable to my Terraform. Things are a bit more complicated if your load balancer has multiple IP addresses assigned (as is the case if you specify --outbound-type loadbalancer when creating your AKS cluster) as you must lookup the correct IP address. See Using SNAT for outbound connections for more information.

Here’s the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
$resource_group = "aks-resource-group-here"

$cluster_name = "aks-cluster-name-here"

$aks_cluster = az aks show -g $resource_group -n $cluster_name 2>&1

if ($aks_cluster -Match "ResourceNotFoundError*") {
Write-Host "Could not find AKS cluster"
}

# Find resource group that contains load balancer
$node_resource_group = ($aks_cluster | ConvertFrom-Json).nodeResourceGroup

$lb = az network lb show --n kubernetes -g $node_resource_group | ConvertFrom-Json

# Find load balancing rule that serves port 443. Could also use port 80
$rule = $lb.loadBalancingRules | Where-Object { $_.frontendPort -eq 443 }

# Find front-end IP config that uses this load balancing rule
$front_end_config = $lb.frontendIpConfigurations | Where-Object { ($_.loadBalancingRules | Where-Object { $_.id -eq $rule.id }) -ne $null }

$public_ip = az network public-ip show --ids $front_end_config.publicIpAddress.id | ConvertFrom-Json

$public_ip_address = $public_ip.ipAddress

Here’s an example of calling the terraform:

1
terraform apply -var "public_ip_address=$public_ip_address"

Another option to consider is using something like ExternalDNS, so DNS records will be created automatically based on the ingress resources in my kubernetes cluster.

It you know of a better way to do this - please do let me know!