

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 DAG 在 CLI 中匯入變數
<a name="samples-variables-import"></a>

下列範例程式碼會使用 Amazon Managed Workflows for Apache Airflow 上的 CLI 匯入變數。

**Topics**
+ [版本](#samples-variables-import-version)
+ [先決條件](#samples-variables-import-prereqs)
+ [權限](#samples-variables-import-permissions)
+ [相依性](#samples-variables-import-dependencies)
+ [範例程式碼](#samples-variables-import-code)
+ [後續步驟？](#samples-variables-import-next-up)

## 版本
<a name="samples-variables-import-version"></a>

您可以在 Python 3.10 中使用 **Apache Airflow v2** 和 Python 3.1[1](https://peps.python.org/pep-0664/) ****中使用此頁面的程式碼範例。 [https://peps.python.org/pep-0619/](https://peps.python.org/pep-0619/)

## 先決條件
<a name="samples-variables-import-prereqs"></a>

使用此頁面上的程式碼範例不需要額外的許可。

## 權限
<a name="samples-variables-import-permissions"></a>

您的 AWS 帳戶 需要存取 `AmazonMWAAAirflowCliAccess`政策。若要進一步了解，請參閱 [Apache Airflow CLI 政策：AmazonMWAAAirflowCliAccess](access-policies.md)。

## 相依性
<a name="samples-variables-import-dependencies"></a>

若要搭配 Apache Airflow v2 和更新版本使用此程式碼範例，不需要額外的相依性。使用 [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images) 來安裝 Apache Airflow。

## 範例程式碼
<a name="samples-variables-import-code"></a>

下列範例程式碼需要三個輸入：您的 Amazon MWAA 環境名稱 （在 中`mwaa_env`)、您環境 AWS 區域 的 （在 中`aws_region`)，以及包含您要匯入之變數的本機檔案 （在 中`var_file`)。

```
import boto3
import json
import requests 
import base64
import getopt
import sys

argv = sys.argv[1:]
mwaa_env=''
aws_region=''
var_file=''

try:
    opts, args = getopt.getopt(argv, 'e:v:r:', ['environment', 'variable-file','region'])
    #if len(opts) == 0 and len(opts) > 3:
    if len(opts) != 3:
        print ('Usage: -e MWAA environment -v variable file location and filename -r aws region')
    else:
        for opt, arg in opts:
            if opt in ("-e"):
                mwaa_env=arg
            elif opt in ("-r"):
                aws_region=arg
            elif opt in ("-v"):
                var_file=arg

        boto3.setup_default_session(region_name="{}".format(aws_region))
        mwaa_env_name = "{}".format(mwaa_env)

        client = boto3.client('mwaa')
        mwaa_cli_token = client.create_cli_token(
            Name=mwaa_env_name
        )
        
        with open ("{}".format(var_file), "r") as myfile:
            fileconf = myfile.read().replace('\n', '')

        json_dictionary = json.loads(fileconf)
        for key in json_dictionary:
            print(key, " ", json_dictionary[key])
            val = (key + " " + json_dictionary[key])
            mwaa_auth_token = 'Bearer ' + mwaa_cli_token['CliToken']
            mwaa_webserver_hostname = 'https://{0}/aws_mwaa/cli'.format(mwaa_cli_token['WebServerHostname'])
            raw_data = "variables set {0}".format(val)
            mwaa_response = requests.post(
                mwaa_webserver_hostname,
                headers={
                    'Authorization': mwaa_auth_token,
                    'Content-Type': 'text/plain'
                    },
                data=raw_data
                )
            mwaa_std_err_message = base64.b64decode(mwaa_response.json()['stderr']).decode('utf8')
            mwaa_std_out_message = base64.b64decode(mwaa_response.json()['stdout']).decode('utf8')
            print(mwaa_response.status_code)
            print(mwaa_std_err_message)
            print(mwaa_std_out_message)

except:
    print('Use this script with the following options: -e MWAA environment -v variable file location and filename -r aws region')
    print("Unexpected error:", sys.exc_info()[0])
    sys.exit(2)
```

## 後續步驟？
<a name="samples-variables-import-next-up"></a>
+ 了解如何在此範例中將 DAG 程式碼上傳至 Amazon S3 儲存貯體中的 `dags` 資料夾[新增或更新 DAGs](configuring-dag-folder.md)。