

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Apache Airflow PythonVirtualenvOperator용 사용자 지정 플러그인 생성
<a name="samples-virtualenv"></a>

다음 샘플은 Amazon Managed Workflows for Apache Airflow에서 사용자 지정 플러그인을 사용하여 Apache Airflow `PythonVirtualenvOperator`를 패치하는 방법을 설명합니다.

**Topics**
+ [버전](#samples-virtualenv-version)
+ [사전 조건](#samples-virtualenv-prereqs)
+ [권한](#samples-virtualenv-permissions)
+ [요구 사항](#samples-virtualenv-dependencies)
+ [사용자 지정 플러그인 샘플 코드](#samples-virtualenv-plugins-code)
+ [Plugins.zip](#samples-virtualenv-pluginszip)
+ [코드 샘플](#samples-virtualenv-code)
+ [Airflow 구성 옵션](#samples-virtualenv-airflow-config)
+ [다음 단계](#samples-virtualenv-next-up)

## 버전
<a name="samples-virtualenv-version"></a>

이 페이지의 코드 예제는 [Python 3.10](https://peps.python.org/pep-0619/)의 **Apache Airflow v2** 및 [Python 3.11](https://peps.python.org/pep-0664/)의 **Apache Airflow v3**에서 사용할 수 있습니다.

## 사전 조건
<a name="samples-virtualenv-prereqs"></a>

이 페이지의 이 샘플 코드를 사용하려면 다음 항목이 필요합니다.
+ [Amazon MWAA 환경](get-started.md).

## 권한
<a name="samples-virtualenv-permissions"></a>

이 페이지의 코드 예제를 사용하는 데 추가 권한이 필요하지 않습니다.

## 요구 사항
<a name="samples-virtualenv-dependencies"></a>

이 페이지의 샘플 코드를 사용하려면 다음 종속성을 사용자 `requirements.txt`에 추가합니다. 자세한 내용은 [Python 종속성 설치](working-dags-dependencies.md) 섹션을 참조하세요.

```
virtualenv
```

## 사용자 지정 플러그인 샘플 코드
<a name="samples-virtualenv-plugins-code"></a>

Apache Airflow는 스타트업 시 플러그인 폴더에 있는 Python 파일의 콘텐츠를 실행합니다. 이 플러그인은 시작 프로세스 중에 내장 `PythonVirtualenvOperator`을 패치하여 Amazon MWAA와 호환되도록 합니다. 다음 단계는 사용자 지정 플러그인의 샘플 코드를 보여줍니다.

1. 명령 프롬프트에서 이전 섹션의 `plugins` 디렉터리로 이동합니다. 예:

   ```
   cd plugins
   ```

1. 다음 코드 샘플의 내용을 복사하고 로컬에서 `virtual_python_plugin.py`로 저장합니다.

   ```
   """
   Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
    
   Permission is hereby granted, free of charge, to any person obtaining a copy of
   this software and associated documentation files (the "Software"), to deal in
   the Software without restriction, including without limitation the rights to
   use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
   the Software, and to permit persons to whom the Software is furnished to do so.
    
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
   FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
   COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   """
   from airflow.plugins_manager import AirflowPlugin
   import airflow.utils.python_virtualenv 
   from typing import List
   
   def _generate_virtualenv_cmd(tmp_dir: str, python_bin: str, system_site_packages: bool) -> List[str]:
       cmd = ['python3','/usr/local/airflow/.local/lib/python3.7/site-packages/virtualenv', tmp_dir]
       if system_site_packages:
           cmd.append('--system-site-packages')
       if python_bin is not None:
           cmd.append(f'--python={python_bin}')
       return cmd
   
   airflow.utils.python_virtualenv._generate_virtualenv_cmd=_generate_virtualenv_cmd
   
   class VirtualPythonPlugin(AirflowPlugin):                
       name = 'virtual_python_plugin'
   ```

## Plugins.zip
<a name="samples-virtualenv-pluginszip"></a>

다음 단계에서는 `plugins.zip`을 생성하는 방법에 대해 설명합니다.

1. 명령 프롬프트에서 이전 섹션의 `virtual_python_plugin.py`를 포함한 디렉터리로 이동합니다. 예:

   ```
   cd plugins
   ```

1. `plugins` 폴더 내 콘텐츠를 압축합니다.

   ```
   zip plugins.zip virtual_python_plugin.py
   ```

## 코드 샘플
<a name="samples-virtualenv-code"></a>

다음 단계에서는 사용자 지정 플러그인의 DAG 코드를 생성하는 방법을 설명합니다.

1. 명령 프롬프트에서 DAG 코드가 저장된 디렉터리로 이동합니다. 예:

   ```
   cd dags
   ```

1. 다음 코드 샘플의 내용을 복사하고 로컬에서 `virtualenv_test.py`로 저장합니다.

   ```
   """
   Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
    
   Permission is hereby granted, free of charge, to any person obtaining a copy of
   this software and associated documentation files (the "Software"), to deal in
   the Software without restriction, including without limitation the rights to
   use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
   the Software, and to permit persons to whom the Software is furnished to do so.
    
   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
   FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
   COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
   IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
   CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   """
   from airflow import DAG
   from airflow.operators.python import PythonVirtualenvOperator
   from airflow.utils.dates import days_ago
   import os
   
   os.environ["PATH"] = os.getenv("PATH") + ":/usr/local/airflow/.local/bin"
   
   def virtualenv_fn():
       import boto3
       print("boto3 version ",boto3.__version__)
   
   with DAG(dag_id="virtualenv_test", schedule_interval=None, catchup=False, start_date=days_ago(1)) as dag:
       virtualenv_task = PythonVirtualenvOperator(
           task_id="virtualenv_task",
           python_callable=virtualenv_fn,
           requirements=["boto3>=1.17.43"],
           system_site_packages=False,
           dag=dag,
       )
   ```

## Airflow 구성 옵션
<a name="samples-virtualenv-airflow-config"></a>

Apache Airflow v2를 사용하는 경우 Apache Airflow 구성 옵션으로 `core.lazy_load_plugins : False`을 추가합니다. 자세한 내용은 [2에서 구성 옵션을 사용하여 플러그인 로드](configuring-env-variables.md#configuring-2.0-airflow-override)를 참조하세요.

## 다음 단계
<a name="samples-virtualenv-next-up"></a>
+ 이 예제의 `requirements.txt` 파일을 [Python 종속성 설치](working-dags-dependencies.md)의 Amazon S3 버킷에 업로드하는 방법을 알아봅니다.
+ 이 예제의 DAG 코드를 [DAG 추가 또는 업데이트](configuring-dag-folder.md)에서 Amazon S3 버킷의 `dags` 폴더에 업로드하는 방법을 알아봅니다.
+ 이 예제의 `plugins.zip` 파일을 [사용자 지정 플러그인 설치](configuring-dag-import-plugins.md)의 Amazon S3 버킷에 업로드하는 방법에 대해 자세히 알아봅니다.