

Les traductions sont fournies par des outils de traduction automatique. En cas de conflit entre le contenu d'une traduction et celui de la version originale en anglais, la version anglaise prévaudra.

# Utilisation d'une clé secrète AWS Secrets Manager pour une connexion Apache Airflow
<a name="samples-secrets-manager"></a>

Les exemples d'appels suivants AWS Secrets Manager pour obtenir une clé secrète pour une connexion Apache Airflow sur Amazon Managed Workflows for Apache Airflow. Cela suppose que vous avez terminé les étapes de[Configuration d'une connexion Apache Airflow à l'aide d'un secret AWS Secrets Manager](connections-secrets-manager.md).

**Topics**
+ [Version](#samples-secrets-manager-version)
+ [Prérequis](#samples-secrets-manager-prereqs)
+ [Autorisations](#samples-secrets-manager-permissions)
+ [Prérequis](#samples-hive-dependencies)
+ [Exemple de code](#samples-secrets-manager-code)
+ [Quelle est la prochaine étape ?](#samples-secrets-manager-next-up)

## Version
<a name="samples-secrets-manager-version"></a>

[Vous pouvez utiliser l'exemple de code présenté sur cette page avec **Apache Airflow v2** en [Python 3.10](https://peps.python.org/pep-0619/) et **Apache Airflow v3** en Python 3.11.](https://peps.python.org/pep-0664/)

## Prérequis
<a name="samples-secrets-manager-prereqs"></a>

Pour utiliser l'exemple de code présenté sur cette page, vous aurez besoin des éléments suivants :
+ Le backend Secrets Manager en tant qu'option de configuration d'Apache Airflow, comme indiqué dans. [Configuration d'une connexion Apache Airflow à l'aide d'un secret AWS Secrets Manager](connections-secrets-manager.md)
+ Une chaîne de connexion Apache Airflow dans Secrets Manager, comme indiqué dans. [Configuration d'une connexion Apache Airflow à l'aide d'un secret AWS Secrets Manager](connections-secrets-manager.md)

## Autorisations
<a name="samples-secrets-manager-permissions"></a>
+ Autorisations du Gestionnaire de Secrets Manager, telles qu'elles sont répertoriées dans[Configuration d'une connexion Apache Airflow à l'aide d'un secret AWS Secrets Manager](connections-secrets-manager.md).

## Prérequis
<a name="samples-hive-dependencies"></a>

Pour utiliser cet exemple de code avec Apache Airflow v2 et versions ultérieures, aucune dépendance supplémentaire n'est requise. [aws-mwaa-docker-images](https://github.com/aws/amazon-mwaa-docker-images)À utiliser pour installer Apache Airflow.

## Exemple de code
<a name="samples-secrets-manager-code"></a>

Les étapes suivantes décrivent comment créer le code DAG qui appelle Secrets Manager pour obtenir le secret.

1. Dans votre invite de commande, accédez au répertoire dans lequel votre code DAG est stocké. Exemples :

   ```
   cd dags
   ```

1. Copiez le contenu de l'exemple de code suivant et enregistrez-le localement sous`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
       )
   ```

## Quelle est la prochaine étape ?
<a name="samples-secrets-manager-next-up"></a>
+ Découvrez comment télécharger le code DAG dans cet exemple dans le `dags` dossier de votre compartiment Amazon S3 dans[Ajouter ou mettre à jour DAGs](configuring-dag-folder.md).