예: Azure 라이브러리를 사용하여 리소스 그룹 만들기

이 예제에서는 Python 스크립트에서 Azure SDK 관리 라이브러리를 사용하여 리소스 그룹을 만드는 방법을 보여 줍니다. (다음 항목해당 Azure CLI 명령은 이 문서의 뒷부분에서 제공됩니다. Azure Portal을 사용하려면 리소스 그룹 만들기를 참조하세요.)

이 문서의 모든 명령은 언급되지 않는 한 Linux/macOS bash 및 Windows 명령 셸에서 동일하게 작동합니다.

1: 로컬 개발 환경 설정

아직 실행하지 않은 경우 이 코드를 실행할 수 있는 환경을 설정합니다. 다음은 몇 가지 옵션입니다.

2: Azure 라이브러리 패키지 설치

다음 내용이 포함된 requirements.txt 파일을 만듭니다.

azure-mgmt-resource
azure-identity

가상 환경이 활성화된 터미널 또는 명령 프롬프트에서 요구 사항을 설치합니다.

pip install -r requirements.txt

3: 리소스 그룹을 만드는 코드 작성

다음 코드를 사용하여 provision_rg.py라는 Python 파일을 만듭니다. 주석은 세부 정보를 설명합니다.

# Import the needed credential and management objects from the libraries.
import os

from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient

# Acquire a credential object using DevaultAzureCredential.
credential = DefaultAzureCredential()

# Retrieve subscription ID from environment variable.
subscription_id = os.environ["AZURE_SUBSCRIPTION_ID"]

# Obtain the management object for resources.
resource_client = ResourceManagementClient(credential, subscription_id)

# Provision the resource group.
rg_result = resource_client.resource_groups.create_or_update(
    "PythonAzureExample-rg", {"location": "centralus"}
)

# Within the ResourceManagementClient is an object named resource_groups,
# which is of class ResourceGroupsOperations, which contains methods like
# create_or_update.
#
# The second parameter to create_or_update here is technically a ResourceGroup
# object. You can create the object directly using ResourceGroup(location=
# LOCATION) or you can express the object as inline JSON as shown here. For
# details, see Inline JSON pattern for object arguments at
# https://learn.microsoft.com/azure/developer/python/sdk
# /azure-sdk-library-usage-patterns#inline-json-pattern-for-object-arguments

print(
    f"Provisioned resource group {rg_result.name} in the {rg_result.location} region"
)

# The return value is another ResourceGroup object with all the details of the
# new group. In this case the call is synchronous: the resource group has been
# provisioned by the time the call returns.

# To update the resource group, repeat the call with different properties, such
# as tags:
rg_result = resource_client.resource_groups.create_or_update(
    "PythonAzureExample-rg",
    {
        "location": "centralus",
        "tags": {"environment": "test", "department": "tech"},
    },
)

print(f"Updated resource group {rg_result.name} with tags")

# Optional lines to delete the resource group. begin_delete is asynchronous.
# poller = resource_client.resource_groups.begin_delete(rg_result.name)
# result = poller.result()

코드의 인증

이 문서의 뒷부분에서 Azure CLI를 사용하여 Azure에 로그인하여 샘플 코드를 실행합니다. 계정에 Azure 구독에서 리소스 그룹을 만들고 나열할 수 있는 권한이 있는 경우 코드가 성공적으로 실행됩니다.

프로덕션 스크립트에서 이러한 코드를 사용하려면 인증에 서비스 주체 기반 방법을 사용하도록 환경 변수를 설정할 수 있습니다. 자세한 내용은 Azure 서비스를 사용하여 Python 앱을 인증하는 방법을 참조 하세요. 서비스 주체가 Azure에서 적절한 역할(예: 구독의 기여자 역할)을 할당하여 구독에서 리소스 그룹을 만들고 나열할 수 있는 충분한 권한이 있는지 확인해야 합니다.

4: 스크립트 실행

  1. 아직 로그인하지 않은 경우 Azure CLI를 사용하여 Azure에 로그인합니다.

    az login
    
  2. 환경 변수를 AZURE_SUBSCRIPTION_ID 구독 ID로 설정합니다. (az account show 명령을 실행하고 출력의 속성에서 구독 ID를 id 가져올 수 있습니다.)

    set AZURE_SUBSCRIPTION_ID=00000000-0000-0000-0000-000000000000
    
  3. 스크립트를 실행합니다.

    python provision_rg.py
    

5: 리소스 그룹 확인

Azure Portal 또는 Azure CLI를 통해 그룹이 존재하는지 확인할 수 있습니다.

  • Azure Portal: Azure Portal열고, 리소스 그룹을 선택하고, 그룹이 나열된 검사. 포털을 이미 연 경우 새로 고침 명령을 사용하여 목록을 업데이트합니다.

  • Azure CLI: az group show 명령을 사용합니다.

    az group show -n PythonAzureExample-rg
    

6: 리소스 정리

이 예제에서 만든 리소스 그룹을 유지할 필요가 없는 경우 az group delete 명령을 실행합니다. 리소스 그룹은 구독에서 진행 중인 요금이 발생하지 않지만 리소스 그룹의 리소스에 요금이 계속 발생할 수 있습니다. 적극적으로 사용하지 않는 그룹을 클린 것이 좋습니다. 인수 --no-wait 를 사용하면 작업이 완료되는 것을 기다리는 대신 명령이 즉시 반환됩니다.

az group delete -n PythonAzureExample-rg  --no-wait

ResourceManagementClient.resource_groups.begin_delete 메서드를 사용하여 코드에서 리소스 그룹을 삭제할 수도 있습니다. 이 문서의 스크립트 맨 아래에 있는 주석 처리된 코드는 사용량을 보여 줍니다.

참조: 동등한 Azure CLI 명령

다음 Azure CLI az group create 명령은 Python 스크립트와 마찬가지로 태그가 있는 리소스 그룹을 만듭니다.

az group create -n PythonAzureExample-rg -l centralus --tags "department=tech" "environment=test"

참고 항목