Azure CLI ile If Koşulları Nasıl Kullanılır?

Bu makalede, işlevlerini geliştirmek ve daha esnek hale getirmek için Azure CLI betiklerindeki if koşullarının nasıl kullanılacağını göstermeye çalışacağım. Uygun koşullu mantıkla, özel ihtiyaçlarınıza göre uyarlanmış daha dinamik ve verimli betikler oluşturabilirsiniz.

Koşullar, belirli kriterlere göre eylemler gerçekleştirmenize izin veriyorsa. Azure CLI betiklerinde, if koşulları için standart shell script syntax kullanırız. Bu öğretici için Bash shell syntax kullanacağız, ancak gerekirse diğer shell’lere uyarlayabilirsiniz.

Bash’teki temel if koşulu sözdizimi şöyledir:

#!/bin/bash

resource_group="myResourceGroup"

# Check if the resource group exists
exists=$(az group exists --name $resource_group)

if [ "$exists" == "true" ]; then
    echo "Resource group $resource_group exists."
else
    echo "Resource group $resource_group does not exist."
fi

Komut dosyasını daha da geliştirmek için, ifadenin sonucuna göre farklı komutları yürütmek için bir if-else koşulunu kullanabilirsiniz:

#!/bin/bash

resource_group="myResourceGroup"
location="East US"

exists=$(az group exists --name $resource_group)

if [ "$exists" == "true" ]; then
    echo "Resource group $resource_group exists."
else
    echo "Creating resource group $resource_group..."
    az group create --name $resource_group --location "$location"
fi

Birden çok koşulu kontrol etmek için elif (else if) ifadesini kullanabilirsiniz:

#!/bin/bash

resource_group="myResourceGroup"
vm_name="myVM"

# Get VM information
vm_info=$(az vm get-instance-view --name $vm_name --resource-group $resource_group --output json)

if [ -z "$vm_info" ]; then
    echo "Virtual machine $vm_name does not exist."
else
    vm_status=$(echo "$vm_info" | jq -r '.statuses[] | select(.code | startswith("PowerState")) | .code')
    
    if [ "$vm_status" == "PowerState/running" ]; then
        echo "Virtual machine $vm_name is running."
    else
        echo "Virtual machine $vm_name is not running. Current state: $vm_status"
    fi
fi

Bir cevap yazın

E-posta hesabınız yayımlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir

This site uses Akismet to reduce spam. Learn how your comment data is processed.