예: Azure 라이브러리를 사용하여 리소스 그룹 만들기
이 예제에서는 Python 스크립트에서 Azure SDK 관리 라이브러리를 사용하여 리소스 그룹을 만드는 방법을 보여 줍니다. (해당 Azure CLI 명령은 이 문서의 뒷부분에 제공됩니다. Azure Portal 사용하려면 리소스 그룹 만들기를 참조하세요.)
이 문서의 모든 명령은 언급되지 않는 한 Linux/macOS bash 및 Windows 명령 셸에서 동일하게 작동합니다.
1: 로컬 개발 환경 설정
아직 실행하지 않은 경우 이 코드를 실행할 수 있는 환경을 설정합니다. 다음은 몇 가지 옵션입니다.
Python 가상 환경을 구성합니다. 로컬 또는 Azure Cloud Shell 가상 환경을 만들고 해당 환경에서 코드를 실행할 수 있습니다. 가상 환경을 활성화하여 사용을 시작해야 합니다.
conda 환경을 사용합니다.
Visual Studio Code 또는 GitHub Codespaces에서 개발 컨테이너를 사용합니다.
2: Azure 라이브러리 패키지 설치
다음과 같은 콘텐츠가 포함된 requirements.txt라는 파일을 만듭니다.
azure-mgmt-resource>=18.0.0
azure-identity>=1.5.0
이러한 라이브러리 버전을 사용해야 합니다. 이전 버전을 사용하면 "'AzureCliCredential' 개체에 'signed_session' 특성이 없습니다."와 같은 오류가 발생합니다.
가상 환경이 활성화된 터미널 또는 명령 프롬프트에서 다음 요구 사항을 설치합니다.
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 AzureCliCredential
from azure.mgmt.resource import ResourceManagementClient
# Acquire a credential object using CLI-based authentication.
credential = AzureCliCredential()
# 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에서 직접 수행할 수 있는 작업을 보여주므로 CLI 기반 인증(AzureCliCredential
사용)을 사용합니다. 두 경우 모두 인증에 동일한 ID를 사용합니다. 사용자 환경에 따라 먼저 를 실행 az login
하여 인증해야 할 수 있습니다.
프로덕션 스크립트(예: VM 관리 자동화)에서 이러한 코드를 사용하려면 Azure 서비스를 사용하여 Python 앱을 인증하는 방법에 설명된 대로 (권장) 또는 서비스 주체 기반 메서드를 사용합니다 DefaultAzureCredential
.
코드에 사용된 클래스에 대한 참조 링크
4: 스크립트 실행
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 -n PythonAzureExample-rg --no-wait
이 예제에서 만든 리소스 그룹을 유지할 필요가 없는 경우 az group delete 명령을 실행합니다. 리소스 그룹에는 구독에서 진행 중인 요금이 발생하지 않지만, 적극적으로 사용하지 않는 그룹을 정리하는 것이 좋습니다. --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"