다음을 통해 공유


Bash 스크립팅 언어로 Azure CLI를 사용하는 방법

Azure CLI 참조 명령은 여러 스크립팅 언어로 실행할 수 있습니다. Bash 및 Azure CLI를 접하는 경우 이 문서를 통해 학습 과정을 시작할 수 있습니다. 이 문서를 통해 Bash 스크립팅 언어로 Azure CLI를 사용하는 방법을 쉽게 알아볼 수 있습니다.

이 문서에서는 다음 방법을 설명합니다.

  • JSON 사전 또는 배열로 결과 쿼리
  • JSON, 테이블 또는 TSV로 출력 형식 지정
  • 단일 값 및 여러 값 쿼리, 필터링 및 형식 지정
  • if/exists/then 및 case 구문 사용
  • 반복에 사용
  • grep, sed, paste 및 bc 명령 사용
  • 셸 및 환경 변수 채우기 및 사용

Azure를 구독하고 있지 않다면 시작하기 전에 Azure 체험 계정을 만듭니다.

Bash 시작

Azure Cloud Shell 또는 Azure CLI의 로컬 설치를 사용하여 Bash를 시작합니다. 이 문서에서는 Azure Cloud Shell을 사용하거나 Docker 컨테이너에서 로컬로 Azure CLI를 실행하는 Bash를 실행한다고 가정합니다.

사전 쿼리 결과

항상 단일 개체만 반환하는 명령은 JSON 사전을 반환합니다. 사전은 키로 액세스되며 순서가 지정되지 않은 개체입니다. 이 문서에서는 먼저 Account Show 명령을 사용하여 Account 개체를 쿼리합니다.

az account show
az account show --output json # JSON is the default format

다음 JSON 사전 출력에는 간결성을 위해 생략된 일부 필드가 있으며 식별 정보가 제거됩니다.

bash-5.1# az account show
{
  "environmentName": "AzureCloud",
  "isDefault": true,
  "managedByTenants": [],
  "name": "My test subscription",
  "state": "Enabled",
  "user": {
    "name": "user@contoso.com",
    "type": "user"
  }
}

YAML로 출력 형식 지정

--output yaml 인수(또는-o yaml)를 사용하여 일반 텍스트 데이터 serialization 형식인 yaml 형식으로 출력의 형식을 지정합니다. YAML은 JSON보다 읽기 쉬우며 해당 형식에 쉽게 매핑됩니다. 일부 애플리케이션 및 CLI 명령은 JSON 대신 YAML을 구성 입력으로 사용합니다.

az account show --output yaml

yaml로 출력 형식을 지정하는 방법에 대한 자세한 내용은 YAML 출력 형식을 참조하세요.

테이블로 출력 형식 지정

--output table 인수(또는-o table)를 사용하여 ASCII 테이블로 출력의 형식을 지정합니다. 중첩된 개체는 테이블 출력에 포함되지 않지만 쿼리의 일부로 필터링될 수 있습니다.

az account show --output table

테이블로 출력 형식을 지정하는 방법에 대한 자세한 내용은 테이블 출력 형식을 참조하세요.

단일 값 및 중첩 값 쿼리 및 형식 지정

다음 쿼리는 JSON 사전 출력에 중첩된 값을 포함하여 단일 값을 쿼리하는 방법을 보여 줍니다. 이 집합의 마지막 쿼리는 -o tsv 인수를 사용하여 출력의 형식을 지정하는 방법을 보여 줍니다. 이 인수는 결과를 탭 및 줄 바꿈 문자로 구분된 값으로 반환합니다. 이 작업은 반환된 값에서 따옴표를 제거하는 데 유용합니다. 이 작업은 텍스트를 어떤 형태로 처리해야 하는 다른 명령 및 도구로 출력을 사용하는 데 유용합니다(이 문서의 뒷부분에서 설명).

az account show --query name # Querying a single value
az account show --query name -o tsv # Removes quotation marks from the output

az account show --query user.name # Querying a nested value
az account show --query user.name -o tsv # Removes quotation marks from the output

배열에서 속성 쿼리 및 서식 지정

다음 쿼리는 JSON 배열에서 속성을 가져오는 방법을 보여 줍니다. 구독 테이블로 표시되는 구독 속성을 가져옵니다.

az account list --query "[].{subscription_id:id, name:name, isDefault:isDefault}" -o table

이 쿼리는 다음과 유사한 결과를 반환합니다.

Subscription_id                       Name                                               IsDefault
------------------------------------  -------------------------------------------------  -----------
11111111-3ddc-45ce-8334-c7b28a9e1c3a  C & L Azure developer experience content projects  False
22222222-8f1c-409b-af1e-8e2e65d9b90a  DevCenter - Infrastructure - Dogfood               False
33333333-c080-42a7-8973-1aa853ab4df3  Babel                                              False

중첩된 값을 포함한 여러 값 쿼리 및 형식 지정

둘 이상의 속성을 가져오려면 대괄호 [ ](다중 선택 목록)에 쉼표로 구분된 목록으로 언어 식을 입력합니다. 다음 쿼리에서는 여러 출력 형식을 사용하여 JSON 사전 출력에서 여러 값을 쿼리하는 방법을 보여 줍니다.

az account show --query [name,id,user.name] # return multiple values
az account show --query [name,id,user.name] -o table # return multiple values as a table

여러 값을 반환하는 방법에 대한 자세한 내용은 여러 값 가져오기를 참조하세요.

쿼리에서 속성 이름 바꾸기

다음 쿼리에서는 여러 값을 쿼리할 때 { }(다중 선택 해시) 연산자를 사용하여 배열 대신 사전을 가져오는 방법을 보여 줍니다. 또한 쿼리 결과의 속성 이름을 바꾸는 방법을 보여 줍니다.

az account show --query "{SubscriptionName: name, SubscriptionId: id, UserName: user.name}" # Rename the values returned
az account show --query "{SubscriptionName: name, SubscriptionId: id, UserName: user.name}" -o table # Rename the values returned in a table

쿼리에서 속성 이름을 바꾸는 방법에 대한 자세한 내용은 쿼리에서 속성 이름 바꾸기를 참조하세요.

부울 값 쿼리

부울 값은 true로 간주되므로 az account list 명령에 대한 "[?isDefault]" 쿼리 구문은 현재 기본 구독을 반환합니다. false 값을 얻으려면 이스케이프 문자(예: \)를 사용해야 합니다.

다음 쿼리는 구독의 모든 계정을 쿼리하고, 지정된 계정에 대해 여러 구독이 있는 경우 잠재적으로 JSON 배열을 반환한 다음, 기본 구독인 계정을 쿼리하는 방법을 보여 줍니다. 또한 기본 구독이 아닌 계정에 대한 쿼리를 보여 줍니다. 이러한 쿼리는 이전에 배운 내용을 기반으로 결과를 필터링하고 형식을 지정합니다. 마지막으로 최종 쿼리는 쿼리 결과를 변수에 저장하는 방법을 보여 줍니다.

az account list
az account list --query "[?isDefault]" # Returns the default subscription
az account list --query "[?isDefault]" -o table # Returns the default subscription as a table
az account list --query "[?isDefault].[name,id]" # Returns the name and id of the default subscription
az account list --query "[?isDefault].[name,id]" -o table # Returns the name and id of the default subscription as a table
az account list --query "[?isDefault].{SubscriptionName: name, SubscriptionId: id}" -o table # Returns the name and id of the default subscription as a table with friendly names

az account list --query "[?isDefault == \`false\`]" # Returns all non-default subscriptions, if any
az account list --query "[?isDefault == \`false\`].name" -o table # Returns all non-default subscriptions, if any, as a table

az account list --query "[?isDefault].id" -o tsv # Returns the subscription id without quotation marks
subscriptionId="$(az account list --query "[?isDefault].id" -o tsv)" # Captures the subscription id as a variable.
echo $subscriptionId # Returns the contents of the variable.
az account list --query "[? contains(name, 'Test')].id" -o tsv # Returns the subscription id of a non-default subscription containing the substring 'Test'
subscriptionId="$(az account list --query "[? contains(name, 'Test')].id" -o tsv) # Captures the subscription id as a variable. 
az account set -s $subscriptionId # Sets the current active subscription

변수 및 임의화를 사용하여 개체 만들기

후속 명령에서 사용할 임의 값 설정

변수에 사용할 임의 값을 설정하고 사용하면 명명 충돌 없이 스크립트를 여러 번 실행할 수 있습니다. 서비스 전체에서 값이 고유해야 하거나 삭제한 개체가 삭제 프로세스가 완료될 때까지 Azure 내에 존재하기 때문에 명명 충돌이 발생합니다.

$RANDOM 는 임의의 부호 있는 16비트 정수(0에서 32767까지)를 반환하는 bash 함수(상수가 아님)입니다. let 명령은 산술 식을 평가하는 기본 제공 Bash 명령입니다. 다음 명령을 사용하면 대부분의 용도에 충분히 고유한 값이 만들어집니다.

let "randomIdentifier=$RANDOM*$RANDOM"

공백 및 따옴표 사용

공백은 명령, 옵션 및 인수를 구분하는 데 사용됩니다. 공백이 특수 문자인 특수 문자를 모두 무시하도록 Bash 셸에 지시하려면 따옴표를 사용합니다. Bash 셸이 첫 번째 따옴표를 보면 닫는 따옴표까지 특수 문자를 무시합니다. 그러나 Bash 셸에서 달러 기호, 역따옴표, 역슬래시와 같은 특정 특수 문자를 구문 분석하려는 경우가 있습니다. 이 시나리오에서는 큰따옴표를 사용합니다.

다음 명령은 az group create 명령을 사용하여 작은따옴표와 큰따옴표의 사용을 보여 줍니다. 이러한 명령은 변수로 작업하고 개체를 만들 때 공백을 처리하고 특수 문자를 평가하는 데 사용됩니다.

resourceGroup='msdocs-learn-bash-$randomIdentifier'
echo $resourceGroup # The $ is ignored in the creation of the $resourceGroup variable
resourceGroup="msdocs-learn-bash-$randomIdentifier"
echo $resourceGroup # The $randomIdentifier is evaluated when defining the $resourceGroup variable
location="East US" # The space is ignored when defining the $location variable
echo The value of the location variable is $location # The value of the $location variable is evaluated
echo "The value of the location variable is $location" # The value of the $location variable is evaluated
echo "The value of the location variable is \$location" # The value of the $location variable is not evaluated
echo 'The value of the location variable is $location' # The value of the $location variable is not evaluated
az group create --name $resourceGroup --location $location # Notice that the space in the $location variable is not ignored and the command fails as it treats the value after the space as a new command 
az group create --name $resourceGroup --location "$location" # Notice that the space in the $location variable is ignored and the location argument accepts the entire string as the value 

JSON 사전 출력에서 생성된 리소스 그룹의 속성을 검토합니다.

If Then Else를 사용하여 변수가 null인지 확인

문자열을 평가하려면 !=을 사용하고 숫자를 평가하려면 -ne를 사용합니다. 다음 If Then Else 문은 $resourceGroup 변수가 설정되었는지 여부를 평가합니다. 그렇다면 변수의 값을 반환합니다. 그렇지 않은 경우에는 변수를 설정합니다.

if [ $resourceGroup != '' ]; then
   echo $resourceGroup
else
   resourceGroup="msdocs-learn-bash-$randomIdentifier"
fi

If Then을 사용하여 리소스 그룹 만들기 또는 삭제

다음 스크립트는 지정된 이름의 리소스 그룹이 아직 없는 경우에만 새 리소스 그룹을 만듭니다.

if [ $(az group exists --name $resourceGroup) = false ]; then 
   az group create --name $resourceGroup --location "$location" 
else
   echo $resourceGroup
fi

다음 스크립트는 지정된 이름의 리소스 그룹이 이미 있는 경우 기존의 새 리소스 그룹을 삭제합니다. 명령이 완료되기를 기다리지 않고 --no-wait 인수를 사용하여 컨트롤을 반환할 수 있습니다. 그러나 이 문서에서는 계속하기 전에 리소스 그룹이 삭제될 때까지 기다립니다. 비동기 작업에 대한 자세한 내용은 Azure CLI를 성공적으로 사용하기 위한 팁( 비동기 작업)을 참조 하세요. 이 문서의 끝에 인수를 --no-wait 사용하는 방법을 보여 줍니다.

if [ $(az group exists --name $resourceGroup) = true ]; then 
   az group delete --name $resourceGroup -y # --no-wait
else
   echo The $resourceGroup resource group does not exist
fi

Grep를 사용하여 리소스 그룹이 있는지 확인하고, 리소스 그룹이 없는 경우 리소스 그룹을 만듭니다.

다음 명령은 출력은 az group list 명령의 출력을 grep 명령에 파이프합니다. 지정된 리소스 그룹이 없으면 명령은 이전에 정의된 변수를 사용하여 리소스 그룹을 만듭니다.

az group list --output tsv | grep $resourceGroup -q || az group create --name $resourceGroup --location "$location"

CASE 문을 사용하여 리소스 그룹이 있는지 확인하고, 그렇지 않은 경우 리소스 그룹을 만듭니다.

다음 CASE 문은 지정된 이름의 리소스 그룹이 아직 없는 경우에만 새 리소스 그룹을 만듭니다. 지정된 이름을 가진 리소스 그룹이 있으면 CASE 문에서 리소스 그룹이 있음을 에코합니다.

var=$(az group list --query "[? contains(name, '$resourceGroup')].name" --output tsv)
case $resourceGroup in
$var)
echo The $resourceGroup resource group already exists.;;
*)
az group create --name $resourceGroup --location "$location";;
esac

반복에 사용하고 배열 쿼리

이 문서의 이 섹션에서는 스토리지 계정을 만든 다음 루프에 사용하여 Blob 및 컨테이너를 만듭니다. 또한 JSON 배열을 쿼리하고 환경 변수를 사용하는 방법을 보여 줍니다.

스토리지 계정 만들기

다음 명령은 az storage account create 명령을 사용하여 스토리지 컨테이너를 만들 때 사용하는 스토리지 계정을 만듭니 다.

storageAccount="learnbash$randomIdentifier"
az storage account create --name $storageAccount --location "$location" --resource-group $resourceGroup --sku Standard_LRS --encryption-services blob

스토리지 계정 키 가져오기

다음 명령은 az storage account keys list 명령을 사용하여 스토리지 계정 키 값을 반환합니다. 그런 다음, 스토리지 컨테이너를 만들 때 사용할 키 값을 변수에 저장합니다.

az storage account keys list --resource-group $resourceGroup --account-name $storageAccount --query "[].value" -o tsv # returns both storage account key values

az storage account keys list --resource-group $resourceGroup --account-name $storageAccount --query "[0].value" -o tsv # returns a single storage account key value

accountKey=$(az storage account keys list --resource-group $resourceGroup --account-name $storageAccount --query "[0].value" -o tsv)

echo $accountKey

스토리지 컨테이너 만들기

먼저 az storage container create를 사용하여 단일 스토리지 컨테이너를 만든 다음, az storage container list를 사용하여 만든 컨테이너의 이름을 쿼리합니다.

container="learningbash"
az storage container create --account-name $storageAccount --account-key $accountKey --name $container

az storage container list --account-name $storageAccount --account-key $accountKey --query [].name

컨테이너로 데이터 업로드

다음 스크립트는 for 반복을 사용하여 3개 샘플 파일을 만듭니다.

for i in `seq 1 3`; do
    echo $randomIdentifier > container_size_sample_file_$i.txt
done

다음 스크립트는 az storage blob upload-batch 명령을 사용하여 Blob을 스토리지 컨테이너에 업로드합니다.

az storage blob upload-batch \
    --pattern "container_size_sample_file_*.txt" \
    --source . \
    --destination $container \
    --account-key $accountKey \
    --account-name $storageAccount

다음 스크립트는 az storage blob list 명령을 사용하여 컨테이너의 Blob을 나열합니다.

az storage blob list \
    --container-name $container \
    --account-key $accountKey \
    --account-name $storageAccount \
    --query "[].name"

다음 스크립트는 스토리지 컨테이너의 총 바이트를 표시합니다.

bytes=`az storage blob list \
    --container-name $container \
    --account-key $accountKey \
    --account-name $storageAccount \
    --query "[*].[properties.contentLength]" \
    --output tsv | paste -s -d+ | bc`

echo "Total bytes in container: $bytes"
echo $bytes

반복을 사용하여 많은 컨테이너 만들기

다음으로 루프를 작성하는 몇 가지 방법을 보여주는 루프를 사용하여 여러 컨테이너를 만듭니다.

for i in `seq 1 4`; do 
az storage container create --account-name $storageAccount --account-key $accountKey --name learnbash-$i
done

for value in {5..8}
for (( i=5; i<10; i++));
do
az storage container create --account-name $storageAccount --account-key $accountKey --name learnbash-$i
done

az storage container list --account-name $storageAccount --account-key $accountKey --query [].name

EXPORT를 사용하여 환경 변수 정의

이전 스토리지 컨테이너 스크립트에서는 모든 명령에 계정 이름 및 계정 키를 지정했습니다. 대신 AZURE_STORAGE_ACCOUNTAZURE_STORAGE_KEY 환경 변수를 사용하여 인증 자격 증명을 저장할 수 있습니다. 이 작업을 수행하려면 EXPORT를 사용합니다.

export AZURE_STORAGE_ACCOUNT=$storageAccount
export AZURE_STORAGE_KEY=$accountKey
az storage container list # Uses the environment variables to display the list of containers.

다음 스크립트는 메타데이터 문자열을 만든 다음, az storage container metadata update 명령을 사용하여 해당 문자열로 컨테이너를 업데이트합니다(역시 환경 변수 사용).

metadata="key=value pie=delicious" # Define metadata
az storage container metadata update \
    --name $container \
    --metadata $metadata # Update the metadata
az storage container metadata show \
    --name $containerName # Show the metadata

다음 명령은 az storage container delete 명령을 사용하여 명명된 단일 컨테이너를 삭제한 다음, 반복에서 여러 컨테이너를 삭제합니다.

az storage container delete \
    --name $container

특정 접두사가 포함된 컨테이너 목록을 가져와서 결과를 변수에 저장합니다.

containerPrefix="learnbash"
containerList=$(az storage container list \
    --query "[].name" \
    --prefix $containerPrefix \
    --output tsv)

--prefix 인수를 사용하여 반복에서 컨테이너 목록을 삭제합니다.

for row in $containerList
do
    tmpName=$(echo $row | sed -e 's/\r//g')
    az storage container delete \
    --name $tmpName 
done

오류 처리

명령이 0이 아닌 상태를 반환하는 경우 스크립트를 즉시 종료하려면 다음 명령을 실행합니다.

set -e

셸 옵션 및 기타 도움말을 설정하는 방법에 대한 자세한 내용은 다음 명령을 실행합니다.

help set
help help

리소스 정리

이 문서를 완료한 후 리소스 그룹 및 리소스 내의 모든 리소스를 삭제합니다. --no-wait 인수를 사용합니다.

if [ $(az group exists --name $resourceGroup) = true ]; then 
   az group delete --name $resourceGroup -y  --no-wait
else
   echo The $resourceGroup resource group does not exist
fi

참고 항목