다음을 통해 공유


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

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

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

1: 로컬 개발 환경 설정

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

  • 선택한 도구를 사용하거나 venv, Python 가상 환경을 구성합니다. 가상 환경 사용을 시작하려면 가상 환경을 활성화해야 합니다. Python을 설치하려면 Python 설치를 참조하세요.

    #!/bin/bash
    # Create a virtual environment
    python -m venv .venv
    # Activate the virtual environment
    source .venv/Scripts/activate # only required for Windows (Git Bash)
    
  • conda 환경을 사용합니다. Conda를 설치하려면 Miniconda 설치를 참조하세요.

  • Visual Studio Code 또는 GitHub Codespaces에서 개발 컨테이너를 사용합니다.

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

  1. 콘솔에서 이 예제에 사용된 관리 라이브러리를 나열하는 requirements.txt 파일을 만듭니다.

    azure-mgmt-resource
    azure-identity
    
  2. 가상 환경이 활성화된 콘솔에서 요구 사항을 설치합니다.

    pip install -r requirements.txt
    

3. 환경 변수 설정

이 단계에서는 이 문서의 코드에서 사용할 환경 변수를 설정합니다. 이 코드는 메서드를 os.environ 사용하여 값을 검색합니다.

#!/bin/bash
export AZURE_RESOURCE_GROUP_NAME=<ResourceGroupName> # Change to your preferred resource group name
export LOCATION=<Location> # Change to your preferred region
export AZURE_SUBSCRIPTION_ID=$(az account show --query id --output tsv)

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

이 단계에서는 다음 코드를 사용하여 provision_blob.py 이라는 Python 파일을 만듭니다. 이 Python 스크립트는 Python용 Azure SDK 관리 라이브러리를 사용하여 Azure 구독에 리소스 그룹을 만듭니다.

다음 코드를 사용하여 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"]

# Retrieve resource group name and location from environment variables
RESOURCE_GROUP_NAME = os.environ["AZURE_RESOURCE_GROUP_NAME"]
LOCATION = os.environ["LOCATION"]

# 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(RESOURCE_GROUP_NAME,
    { "location": LOCATION })

print(f"Provisioned resource group {rg_result.name}")

# 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(
    RESOURCE_GROUP_NAME,
    {
        "location": LOCATION,
        "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의 RBAC(역할 기반 액세스 제어)를 참조하세요.

5: 스크립트 실행

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

    az login
    
  2. 스크립트를 실행합니다.

    python provision_rg.py
    

6: 리소스 그룹 확인

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

  • Azure Portal: Azure Portal을 열고 , 리소스 그룹을 선택하고, 그룹이 나열되어 있는지 확인합니다. 필요한 경우 새로 고침 명령을 사용하여 목록을 업데이트합니다.

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

    #!/bin/bash
    az group show -n $AZURE_RESOURCE_GROUP_NAME
    

7: 리소스 정리

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

#!/bin/bash
az group delete -n $AZURE_RESOURCE_GROUP_NAME --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"

참고하십시오