다음을 통해 공유


EDW(이벤트 기반 워크플로) 워크로드에 대한 애플리케이션 코드 업데이트

이 문서에서는 Azure SDK를 사용하여 Azure 서비스에서 작동하도록 Azure에서 EDW 워크로드를 복제하기 위한 주요 애플리케이션 코드 업데이트를 간략하게 설명합니다.

데이터 액세스 코드

AWS 구현

AWS 워크로드는 AWS 서비스와 관련 데이터 액세스 AWS SDK를 활용합니다. AWS 서비스를 이미 동등한 Azure 서비스에 매핑했으므로 이제 Azure SDK를 사용하여 Python에서 프로듀셔 큐 및 소비자 결과 데이터베이스 테이블에 대한 데이터에 액세스하는 코드를 만들 수 있습니다.

Azure 구현

데이터 평면의 경우 프로듀셔 메시지 본문(페이로드)은 JSON이며 Azure에 대한 스키마 변경은 필요하지 않습니다. 원래 소비자 앱은 처리된 메시지를 DynamoDB 테이블에 저장합니다. 소비자 앱 코드를 약간 수정하면 처리된 메시지를 Azure Storage 테이블에 저장할 수 있습니다.

인증 코드

AWS 구현

AWS 워크로드는 Amazon SQS(Simple Queue Service) 리소스에 대한 모든 권한을 정의하는 IAM 역할 정책을 사용합니다.

{
  "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "sqs:*",
            "Resource": "*"
        }
    ]
}

AWS 워크로드는 Amazon DynamoDB 리소스에 대한 모든 권한을 정의하는 IAM 역할 정책을 사용합니다.

{
  "Version": "2012-10-17",
  "Statement": [
    {
        "Effect": "Allow",
        "Action": "dynamodb:*",
        "Resource": "*"
    }
  ]
}

AWS 워크로드에서 AWS CLI를 사용하여 다음 정책을 할당합니다.

aws iam create-policy --policy-name sqs-sample-policy --policy-document <filepath/filename>.json
aws iam create-policy --policy-name dynamodb-sample-policy --policy-document <filepath/filename>.json
aws iam create-role --role-name keda-sample-iam-role  --assume-role-policy-document <filepath/filename>.json

aws iam attach-role-policy --role-name keda-sample-iam-role --policy-arn=arn:aws:iam::${<AWSAccountID>}:policy/sqs-sample-policy
aws iam attach-role-policy --role-name keda-sample-iam-role --policy-arn=arn:aws:iam::${<AWSAccountID>}:policy/dynamodb-sample-policy

# Set up trust relationship Kubernetes federated identity credential and map IAM role via kubectl annotate serviceaccount

Azure 구현

AKS를 사용하여 Azure 환경 내에서 유사한 AWS 서비스 통신 논리를 수행하는 방법을 살펴보겠습니다.

두 개의 Azure RBAC 역할 정의를 적용하여 Azure Storage 큐 및 Azure Storage 테이블에 대한 데이터 평면 액세스를 제어합니다. 이러한 역할은 AWS가 SQS 및 DynamoDB에 대한 액세스를 제어하는 ​​데 사용하는 IAM 역할 정책과 유사합니다. Azure RBAC 역할은 리소스와 함께 번들로 제공되지 않습니다. 대신 지정된 리소스와 연결된 서비스 주체에 역할을 할당합니다.

EDW 워크로드의 Azure 구현에서 AKS Pod의 워크로드 ID에 연결된 사용자 할당 관리 ID에 역할을 할당합니다. Azure Storage 큐 및 Azure Storage 테이블에 대한 Azure Python SDK는 보안 주체의 컨텍스트를 자동으로 사용하여 두 리소스의 데이터에 액세스합니다.

스토리지 큐 데이터 기여자 역할을 사용하여 역할 담당자가 Azure Storage 큐에 대해 읽고, 쓰거나, 삭제할 수 있도록 하고, 스토리지 테이블 데이터 기여자 역할을 사용하여 담당자가 Azure Storage 테이블에 대해 데이터를 읽거나, 쓰거나, 삭제할 수 있도록 합니다.

다음 단계에서는 Azure CLI를 사용하여 관리 ID를 만들고 스토리지 큐 데이터 기여자스토리지 테이블 데이터 기여자 역할을 할당하는 방법을 보여 줍니다.

  1. az identity create 명령을 사용하여 관리 ID를 만듭니다.

    managedIdentity=$(az identity create \
        --resource-group $resourceGroup \
        --name $managedIdentityName
    
  2. az role assignment create 명령을 사용하여 관리 ID에 스토리지 큐 데이터 기여자 역할을 할당합니다.

    principalId=$(echo $managedIdentity | jq -r `.principalId`)
    
    az role assignment create \
        --assignee-object-id $principalId \
        --assignee-principal-type ServicePrincipal
        --role "Storage Queue Data Contributor" \
        --scope $resourceId
    
  3. az role assignment create 명령을 사용하여 관리 ID에 스토리지 테이블 데이터 기여자 역할을 할당합니다.

    az role assignment create \
        --assignee-object-id $principalId \
        --assignee-principal-type ServicePrincipal
        --role "Storage Table Data Contributor" \
        --scope $resourceId
    

작업 예제를 보려면 GitHub 리포지토리deploy.sh 스크립트를 참조하세요.

프로듀셔 코드

AWS 구현

AWS 워크로드는 Amazon boto3 Python 라이브러리를 사용하여 AWS SQS 큐와 상호 작용하여 스토리지 큐 액세스를 구성합니다. AWS IAM AssumeRole 기능은 애플리케이션을 호스트하는 EKS Pod와 연결된 IAM ID를 사용하여 SQS 엔드포인트에 인증합니다.

import boto3
# other imports removed for brevity
sqs_queue_url = "https://<region>.amazonaws.com/<queueid>/source-queue.fifo"
sqs_queue_client = boto3.client("sqs", region_name="<region>")    
response = sqs_client.send_message(
    QueueUrl = sqs_queue_url,
    MessageBody = 'messageBody1',
    MessageGroupId='messageGroup1')

Azure 구현

Azure 구현은 Azure SDK for Python 및 암호 없는 OAuth 인증을 사용하여 Azure Storage 큐 서비스와 상호 작용합니다. DefaultAzureCredential Python 클래스는 워크로드 ID를 인식하고 워크로드 ID와 연결된 관리 ID를 사용하여 스토리지 큐에 인증합니다.

다음 예제에서는 DefaultAzureCredential 클래스를 사용하여 Azure Storage 큐에 인증하는 방법을 보여 줍니다.

from azure.identity import DefaultAzureCredential
from azure.storage.queue import QueueClient
# other imports removed for brevity

# authenticate to the storage queue.
account_url = "https://<storageaccountname>.queue.core.windows.net"
default_credential = DefaultAzureCredential()
aqs_queue_client = QueueClient(account_url, queue_name=queue_name ,credential=default_credential)

aqs_queue_client.create_queue()
aqs_queue_client.send_message('messageBody1')

GitHub 리포지토리에서 큐 프로듀셔(aqs-producer.py)에 대한 코드를 검토할 수 있습니다.

소비자 코드

AWS 구현

DynamoDB 액세스를 위한 원래 AWS 코드는 AWS boto3 Python 라이브러리를 사용하여 Amazon SQS 큐와 상호 작용합니다. 워크로드의 소비자 부분은 Amazon SQS 큐에 연결하여 메시지를 읽기 위해 생산자와 동일한 코드를 사용합니다. 또한 소비자는 애플리케이션을 호스트하는 EKS Pod와 연결된 IAM ID를 통해 DynamoDB 엔드포인트에 인증하는 AWS IAM AssumeRole 기능을 사용하여 DynamoDB에 연결하는 Python 코드를 포함합니다.

# presumes policy deployment ahead of time such as: aws iam create-policy --policy-name <policy_name> --policy-document <policy_document.json>
dynamodb = boto3.resource('dynamodb', region_name='<region>')
table = dynamodb.Table('<dynamodb_table_name>')
table.put_item(
    Item = {
      'id':'<guid>',
      'data':jsonMessage["<message_data>"],
      'srcStamp':jsonMessage["<source_timestamp_from_message>"],
      'destStamp':'<current_timestamp_now>',
      'messageProcessingTime':'<duration>'
    }
)

Azure 구현

Azure 구현은 Python용 Azure SDK를 사용하여 Azure Storage 테이블과 상호 작용합니다.

이제 Azure Storage 테이블에 인증하는 프로듀셔 코드가 필요합니다. 앞에서 설명한 것처럼 이전 섹션에서 DynamoDB와 함께 사용된 스키마는 Azure Storage 테이블과 호환되지 않습니다. Azure Cosmos DB와 호환되는 테이블 스키마를 사용하여 DynamoDB에 AWS 워크로드와 동일한 데이터를 저장합니다.

다음 예제에서는 Azure에 필요한 코드를 보여 줍니다.

from azure.storage.queue import QueueClient
from azure.data.tables import (TableServiceClient)

    creds = DefaultAzureCredential()
    table = TableServiceClient(
        endpoint=f"https://{storage_account_name}.table.core.windows.net/",  
        credential=creds).get_table_client(table_name=azure_table)

entity={
    'PartitionKey': _id,
    'RowKey': str(messageProcessingTime.total_seconds()),
    'data': jsonMessage['msg'],
    'srcStamp': jsonMessage['srcStamp'],
    'dateStamp': current_dateTime
}
        
response = table.insert_entity(
    table_name=azure_table,
    entity=entity,
    timeout=60
)

DynamoDB와 달리 Azure Storage 테이블 코드는 PartitionKeyRowKey를 모두 지정합니다. PartitionKey는 DynamoDB의 ID uniqueidentifer와 비슷합니다. PartitionKey는 Azure Storage 테이블의 논리 컨테이너에 있는 파티션에 대한 uniqueidentifier입니다. RowKey는 지정된 파티션의 모든 행에 대한 uniqueidentifier입니다.

GitHub 리포지토리의 전체 프로듀셔 및 소비자 코드를 검토할 수 있습니다.

컨테이너 이미지를 만들고 Azure Container Registry로 푸시

이제 컨테이너 이미지를 빌드하고 ACR(Azure Container Registry)로 푸시할 수 있습니다.

복제된 리포지토리의 app 디렉터리에서 docker-command.sh라는 셸 스크립트는 컨테이너 이미지를 빌드하고 ACR로 푸시합니다. .sh 파일을 열고 코드를 검토합니다. 스크립트는 프로듀셔 및 소비자 컨테이너 이미지를 빌드하고 ACR로 푸시합니다. 자세한 내용은 Azure의 컨테이너 레지스트리 소개ACR에서 이미지 푸시 및 끌어오기를 참조하세요.

컨테이너 이미지를 빌드하고 ACR로 푸시하려면 AZURE_CONTAINER_REGISTRY 환경 변수가 이미지를 푸시할 레지스트리의 이름으로 설정되어 있는지 확인한 후 다음 명령을 실행합니다.

./app/docker-command.sh

다음 단계

참가자

Microsoft는 이 문서를 유지 관리합니다. 다음 기여자는 원래 그것을 썼다:

  • Ken Kilty | 수석 TPM
  • Russell de Pina | 수석 TPM
  • Jenny Hayes | 선임 콘텐츠 개발자
  • Carol Smith | 선임 콘텐츠 개발자
  • Erin Schaffer | 콘텐츠 개발자 2