You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@airflow.apache.org by GitBox <gi...@apache.org> on 2022/03/15 22:16:55 UTC

[GitHub] [airflow] eladkal commented on a change in pull request #22295: Add docs and example dag for AWS Glue

eladkal commented on a change in pull request #22295:
URL: https://github.com/apache/airflow/pull/22295#discussion_r827459957



##########
File path: airflow/providers/amazon/aws/example_dags/example_glue.py
##########
@@ -0,0 +1,139 @@
+# Licensed to the Apache Software Foundation (ASF) under one
+# or more contributor license agreements.  See the NOTICE file
+# distributed with this work for additional information
+# regarding copyright ownership.  The ASF licenses this file
+# to you under the Apache License, Version 2.0 (the
+# "License"); you may not use this file except in compliance
+# with the License.  You may obtain a copy of the License at
+#
+#   http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing,
+# software distributed under the License is distributed on an
+# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+# KIND, either express or implied.  See the License for the
+# specific language governing permissions and limitations
+# under the License.
+import tempfile
+from datetime import datetime
+from os import getenv
+
+from airflow import DAG
+from airflow.models.baseoperator import chain
+from airflow.operators.python import PythonOperator
+from airflow.providers.amazon.aws.hooks.s3 import S3Hook
+from airflow.providers.amazon.aws.operators.glue import GlueJobOperator
+from airflow.providers.amazon.aws.operators.glue_crawler import GlueCrawlerOperator
+from airflow.providers.amazon.aws.sensors.glue import GlueJobSensor
+from airflow.providers.amazon.aws.sensors.glue_crawler import GlueCrawlerSensor
+
+GLUE_DATABASE_NAME = getenv('GLUE_DATABASE_NAME', 'glue_database_name')
+GLUE_EXAMPLE_S3_BUCKET = getenv('GLUE_EXAMPLE_S3_BUCKET', 'glue_example_s3_bucket')
+
+# Role needs putobject/getobject access to the above bucket as well as the glue
+# service role, see docs here: https://docs.aws.amazon.com/glue/latest/dg/create-an-iam-role.html
+GLUE_CRAWLER_ROLE = getenv('GLUE_CRAWLER_ROLE', 'glue_crawler_role')
+GLUE_CRAWLER_NAME = 'example_crawler'
+GLUE_CRAWLER_CONFIG = {
+    'Name': GLUE_CRAWLER_NAME,
+    'Role': GLUE_CRAWLER_ROLE,
+    'DatabaseName': GLUE_DATABASE_NAME,
+    'Targets': {
+        'S3Targets': [
+            {
+                'Path': f'{GLUE_EXAMPLE_S3_BUCKET}/input',
+            }
+        ]
+    },
+}
+
+# Example csv data used as input to the example AWS Glue Job.
+EXAMPLE_CSV = '''
+food,price
+apple,0.5
+milk,2.5
+bread,4.0
+'''
+
+# Example Spark script to operate on the above sample csv data.
+EXAMPLE_SCRIPT = f'''
+from pyspark.context import SparkContext
+from awsglue.context import GlueContext
+
+glueContext = GlueContext(SparkContext.getOrCreate())
+datasource = glueContext.create_dynamic_frame.from_catalog(
+             database='{GLUE_DATABASE_NAME}', table_name='input')
+print('There are %s items in the table' % datasource.count())
+
+datasource.toDF().write.format('csv').mode("append").save('s3://{GLUE_EXAMPLE_S3_BUCKET}/output')
+'''
+
+
+def _upload_from_tmp_file_to_glue_bucket(contents: str, s3_key: str):
+    '''Upload contents of string to S3 leveraging tempfiles to copy the data'''
+    with tempfile.NamedTemporaryFile(mode='a') as tmp:
+        tmp.write(contents.strip())
+        tmp.seek(0)
+        s3_hook = S3Hook()
+        s3_hook.load_file(
+            filename=tmp.name,
+            key=s3_key,
+            bucket_name=GLUE_EXAMPLE_S3_BUCKET,
+            replace=True,
+        )
+
+
+with DAG(
+    dag_id='example_glue',
+    schedule_interval=None,
+    start_date=datetime(2021, 1, 1),
+    tags=['example'],
+    catchup=False,
+) as glue_dag:
+
+    upload_csv = PythonOperator(
+        task_id='upload_csv',
+        python_callable=_upload_from_tmp_file_to_glue_bucket,
+        op_kwargs={'contents': EXAMPLE_CSV, 's3_key': 'input/input.csv'},
+    )
+    upload_etl_script = PythonOperator(
+        task_id='upload_etl_script',
+        python_callable=_upload_from_tmp_file_to_glue_bucket,
+        op_kwargs={'contents': EXAMPLE_SCRIPT, 's3_key': 'etl_script.py'},
+    )

Review comment:
       We can have less code lines with the python decorator




-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: commits-unsubscribe@airflow.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org