예: Azure 라이브러리를 사용하여 리소스 그룹 및 리소스 나열

이 예제에서는 Python 스크립트에서 Azure SDK 관리 라이브러리를 사용하여 두 가지 작업을 수행하는 방법을 보여 줍니다.

  • Azure 구독의 모든 리소스 그룹을 나열합니다.
  • 특정 리소스 그룹 내의 리소스를 나열합니다.

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

해당하는 Azure CLI 명령은 이 문서의 뒷부분에 나와 있습니다.

1: 로컬 개발 환경 설정

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

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

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

azure-mgmt-resource
azure-identity

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

pip install -r requirements.txt

3: 리소스 그룹 작업을 위한 코드 작성

3a. 구독의 리소스 그룹 나열

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

# Import the needed credential and management objects from the libraries.
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
import os

# Acquire a credential object.
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)

# Retrieve the list of resource groups
group_list = resource_client.resource_groups.list()

# Show the groups in formatted output
column_width = 40

print("Resource Group".ljust(column_width) + "Location")
print("-" * (column_width * 2))

for group in list(group_list):
    print(f"{group.name:<{column_width}}{group.location}")

3b. 특정 리소스 그룹 내의 리소스 나열

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

기본적으로 코드는 "myResourceGroup"의 리소스를 나열합니다. 다른 리소스 그룹을 사용하려면 환경 변수를 RESOURCE_GROUP_NAME 원하는 그룹 이름으로 설정합니다.

# Import the needed credential and management objects from the libraries.
from azure.identity import DefaultAzureCredential
from azure.mgmt.resource import ResourceManagementClient
import os

# Acquire a credential object.
credential = DefaultAzureCredential()

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

# Retrieve the resource group to use, defaulting to "myResourceGroup".
resource_group = os.getenv("RESOURCE_GROUP_NAME", "myResourceGroup")

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

# Retrieve the list of resources in "myResourceGroup" (change to any name desired).
# The expand argument includes additional properties in the output.
resource_list = resource_client.resources.list_by_resource_group(
    resource_group, expand = "createdTime,changedTime")

# Show the groups in formatted output
column_width = 36

print("Resource".ljust(column_width) + "Type".ljust(column_width)
    + "Create date".ljust(column_width) + "Change date".ljust(column_width))
print("-" * (column_width * 4))

for resource in list(resource_list):
    print(f"{resource.name:<{column_width}}{resource.type:<{column_width}}"
       f"{str(resource.created_time):<{column_width}}{str(resource.changed_time):<{column_width}}")

코드의 인증

이 문서의 뒷부분에서 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 list_groups.py
    
  4. 리소스 그룹의 모든 리소스를 나열합니다.

    python list_resources.py
    

    기본적으로 코드는 "myResourceGroup"의 리소스를 나열합니다. 다른 리소스 그룹을 사용하려면 환경 변수를 RESOURCE_GROUP_NAME 원하는 그룹 이름으로 설정합니다.

참조용: 해당 Azure CLI 명령

다음 Azure CLI 명령은 구독의 리소스 그룹을 나열합니다.

az group list

다음 명령은 중앙 지역의 "myResourceGroup" 내의 리소스를 나열합니다( location 인수는 특정 데이터 센터를 식별하는 데 필요합니다.)

az resource list --resource-group myResourceGroup --location centralus

참고 항목