Como usar uma chave secreta em AWS Secrets Manager para uma conexão do Apache Airflow
O exemplo a seguir chama AWS Secrets Manager para obter uma chave secreta para uma conexão Apache Airflow no Amazon Managed Workflows for Apache Airflow. Pressupõe-se que você tenha concluído as etapas em Como configurar uma conexão do Apache Airflow usando um segredo AWS Secrets Manager.
Versão
É possível usar o exemplo de código nesta página com o Apache Airflow v2 no Python 3.10
Pré-requisitos
Para usar o código de amostra nesta página, você precisará do seguinte:
-
O backend do Secrets Manager como uma opção de configuração do Apache Airflow, conforme mostrado em Como configurar uma conexão do Apache Airflow usando um segredo AWS Secrets Manager.
-
Uma string de conexão do Apache Airflow no Secrets Manager, conforme mostrado em Como configurar uma conexão do Apache Airflow usando um segredo AWS Secrets Manager.
Permissões
-
As permissões do Secrets Manager, conforme mostrado em Como configurar uma conexão do Apache Airflow usando um segredo AWS Secrets Manager.
Requisitos
Para usar esse exemplo de código com o Apache Airflow v2 e versões posteriores, nenhuma dependência adicional é necessária. Use aws-mwaa-docker-images
Exemplo de código
As etapas a seguir descrevem como criar o código DAG que chama o Secrets Manager para obter o segredo.
-
No prompt de comando, navegue até o diretório em que o código do DAG está armazenado. Por exemplo:
cd dags -
Copie o conteúdo da amostra de código a seguir e salve localmente como
secrets-manager.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, settings, secrets from airflow.operators.python import PythonOperator from airflow.utils.dates import days_ago from airflow.providers.amazon.aws.hooks.base_aws import AwsBaseHook from datetime import timedelta import os ### The steps to create this secret key can be found at: https://docs.aws.amazon.com/mwaa/latest/userguide/connections-secrets-manager.html sm_secretId_name = 'airflow/connections/myconn' default_args = { 'owner': 'airflow', 'start_date': days_ago(1), 'depends_on_past': False } ### Gets the secret myconn from Secrets Manager def read_from_aws_sm_fn(**kwargs): ### set up Secrets Manager hook = AwsBaseHook(client_type='secretsmanager') client = hook.get_client_type(region_name='us-east-1') response = client.get_secret_value(SecretId=sm_secretId_name) myConnSecretString = response["SecretString"] return myConnSecretString ### 'os.path.basename(__file__).replace(".py", "")' uses the file name secrets-manager.py for a DAG ID of secrets-manager with DAG( dag_id=os.path.basename(__file__).replace(".py", ""), default_args=default_args, dagrun_timeout=timedelta(hours=2), start_date=days_ago(1), schedule_interval=None ) as dag: write_all_to_aws_sm = PythonOperator( task_id="read_from_aws_sm", python_callable=read_from_aws_sm_fn, provide_context=True )
Próximas etapas
-
Saiba como fazer o upload do código DAG neste exemplo para a pasta
dagsem seu bucket do Amazon S3 em Como adicionar ou atualizar DAGs.