Below is a Bash script snippet that you can use in your GitLab pipeline to achieve the described functionality. Please make sure that you have the Azure CLI (az) installed and configured correctly in your runner environment for this script to work. Also, ensure that the LOCATION_LONG and CLUSTER variables are set in your pipeline environment.
#!/bin/bash
# Ensure that LOCATION_LONG and CLUSTER variables are set
if [ -z "$LOCATION_LONG" ] || [ -z "$CLUSTER" ]; then
echo "Both LOCATION_LONG and CLUSTER variables must be set."
exit 1
fi
# Obtain the list of supported AKS versions in the provided region
supported_versions=$(az aks get-versions --location "$LOCATION_LONG" --output tsv --query 'orchestrators[].orchestratorVersion')
# Check if the command failed
if [ $? -ne 0 ]; then
echo "Failed to get supported AKS versions for region $LOCATION_LONG"
exit 1
fi
# Check if the AKS cluster exists
cluster_info=$(az aks show --name "$CLUSTER" --query 'kubernetesVersion' --output tsv 2>/dev/null)
# If the cluster does not exist, cluster_info will be empty
if [ -z "$cluster_info" ]; then
echo "Cluster $CLUSTER does not exist."
exit 1
fi
# Extract the version of the existing cluster
cluster_version=$cluster_info
# Check if the cluster version is in the list of supported versions
if [[ ! " ${supported_versions[@]} " =~ " ${cluster_version} " ]]; then
echo "Cluster version $cluster_version is not supported in region $LOCATION_LONG"
exit 1
fi
echo "Cluster $CLUSTER with version $cluster_version is supported."
# Continue with the pipeline...
Copy and paste the above script into your GitLab pipeline configuration file (gitlab-ci.yml) under the relevant job. Ensure that this job has the necessary permissions to execute Azure CLI commands.
Please note that this script assumes that you have the necessary privileges to run these commands and that your Azure CLI is already logged in to the appropriate account. If you need to automate the login process within the script, you'll need to handle Azure Service Principal creation and manage secrets securely within your CI/CD pipeline.
Also, error handling in this script is basic. Depending on the complexity of your pipeline and the need for debugging, you may want to enhance error handling, logging, and output formatting.