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 21:48:09 UTC

[GitHub] [airflow] o-nikolas opened a new pull request #22295: Add docs and example dag for AWS Glue

o-nikolas opened a new pull request #22295:
URL: https://github.com/apache/airflow/pull/22295


   Part of a project to add, simplify and standardize AWS sample dags and docs in preparation for adding System Testing.
   
   related: #21828
   related: #22010
   related: #21920
   <!--
   Thank you for contributing! Please make sure that your code changes
   are covered with tests. And in case of new features or big changes
   remember to adjust the documentation.
   
   Feel free to ping committers for the review!
   
   In case of existing issue, reference it using one of the following:
   
   closes: #ISSUE
   related: #ISSUE
   
   How to write a good git commit message:
   http://chris.beams.io/posts/git-commit/
   -->
   
   ---
   **^ Add meaningful description above**
   
   Read the **[Pull Request Guidelines](https://github.com/apache/airflow/blob/main/CONTRIBUTING.rst#pull-request-guidelines)** for more information.
   In case of fundamental code change, Airflow Improvement Proposal ([AIP](https://cwiki.apache.org/confluence/display/AIRFLOW/Airflow+Improvements+Proposals)) is needed.
   In case of a new dependency, check compliance with the [ASF 3rd Party License Policy](https://www.apache.org/legal/resolved.html#category-x).
   In case of backwards incompatible changes please leave a note in [UPDATING.md](https://github.com/apache/airflow/blob/main/UPDATING.md).
   


-- 
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



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

Posted by GitBox <gi...@apache.org>.
o-nikolas commented on a change in pull request #22295:
URL: https://github.com/apache/airflow/pull/22295#discussion_r828284103



##########
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:
       Sure, folks, I will make the change :) 




-- 
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



[GitHub] [airflow] potiuk merged pull request #22295: Add docs and example dag for AWS Glue

Posted by GitBox <gi...@apache.org>.
potiuk merged pull request #22295:
URL: https://github.com/apache/airflow/pull/22295


   


-- 
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



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

Posted by GitBox <gi...@apache.org>.
potiuk commented on a change in pull request #22295:
URL: https://github.com/apache/airflow/pull/22295#discussion_r827865243



##########
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:
       Agreed.




-- 
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



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

Posted by GitBox <gi...@apache.org>.
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



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

Posted by GitBox <gi...@apache.org>.
josh-fell commented on a change in pull request #22295:
URL: https://github.com/apache/airflow/pull/22295#discussion_r830403782



##########
File path: airflow/providers/amazon/aws/example_dags/example_glue.py
##########
@@ -0,0 +1,124 @@
+# 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.
+from datetime import datetime
+from os import getenv
+
+from airflow import DAG
+from airflow.decorators import task
+from airflow.models.baseoperator import chain
+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')
+'''
+
+
+@task(task_id='setup__upload_artifacts_to_s3')
+def upload_artifacts_to_s3():
+    '''Upload example CSV input data and an example Spark script to be used by the Glue Job'''
+    s3_hook = S3Hook()
+    s3_load_kwargs = {"replace": True, "bucket_name": GLUE_EXAMPLE_S3_BUCKET}
+    s3_hook.load_string(string_data=EXAMPLE_CSV, key='input/input.csv', **s3_load_kwargs)
+    s3_hook.load_string(string_data=EXAMPLE_SCRIPT, key='etl_script.py', **s3_load_kwargs)
+
+
+with DAG(
+    dag_id='example_glue',
+    schedule_interval=None,
+    start_date=datetime(2021, 1, 1),
+    tags=['example'],
+    catchup=False,
+) as glue_dag:
+
+    setup_upload_artifacts_to_s3 = upload_artifacts_to_s3()
+
+    # [START howto_operator_glue_crawler]
+    crawl_s3 = GlueCrawlerOperator(
+        task_id='crawl_s3',
+        config=GLUE_CRAWLER_CONFIG,
+        wait_for_completion=False,
+    )
+    # [END howto_operator_glue_crawler]
+
+    # [START howto_sensor_glue_crawler]
+    wait_for_crawl = GlueCrawlerSensor(task_id='wait_for_crawl', crawler_name=GLUE_CRAWLER_NAME)
+    # [END howto_sensor_glue_crawler]
+
+    # [START howto_operator_glue]
+    job_name = 'example_glue_job'
+    submit_glue_job = GlueJobOperator(
+        task_id='submit_glue_job',
+        job_name=job_name,
+        wait_for_completion=False,
+        script_location=f's3://{GLUE_EXAMPLE_S3_BUCKET}/etl_script.py',
+        s3_bucket=GLUE_EXAMPLE_S3_BUCKET,
+        iam_role_name=GLUE_CRAWLER_ROLE.split('/')[-1],
+        create_job_kwargs={'GlueVersion': '3.0', 'NumberOfWorkers': 2, 'WorkerType': 'G.1X'},
+    )
+    # [END howto_operator_glue]
+
+    # [START howto_sensor_glue]
+    wait_for_job = GlueJobSensor(
+        task_id='wait_for_job',
+        job_name=job_name,
+        # Job ID extracted from previous Glue Job Operator task
+        run_id="{{ ti.xcom_pull(task_ids='submit_glue_job') }}",

Review comment:
       ```suggestion
           run_id=submit_glue_job.output,
   ```
   Another perk of the TaskFlow API: using the `.output` property or [`XComArgs`](https://airflow.apache.org/docs/apache-airflow/stable/tutorial_taskflow_api.html#consuming-xcoms-between-decorated-and-traditional-tasks). This is a functional abstraction over the classic `"{{ ti.xcom_pull(...) }}"` approach to pull `XComs` from operators.




-- 
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



[GitHub] [airflow] github-actions[bot] commented on pull request #22295: Add docs and example dag for AWS Glue

Posted by GitBox <gi...@apache.org>.
github-actions[bot] commented on pull request #22295:
URL: https://github.com/apache/airflow/pull/22295#issuecomment-1068519653


   The PR is likely OK to be merged with just subset of tests for default Python and Database versions without running the full matrix of tests, because it does not modify the core of Airflow. If the committers decide that the full tests matrix is needed, they will add the label 'full tests needed'. Then you should rebase to the latest main or amend the last commit of the PR, and push it with --force-with-lease.


-- 
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



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

Posted by GitBox <gi...@apache.org>.
o-nikolas commented on a change in pull request #22295:
URL: https://github.com/apache/airflow/pull/22295#discussion_r831452635



##########
File path: airflow/providers/amazon/aws/example_dags/example_glue.py
##########
@@ -0,0 +1,124 @@
+# 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.
+from datetime import datetime
+from os import getenv
+
+from airflow import DAG
+from airflow.decorators import task
+from airflow.models.baseoperator import chain
+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')
+'''
+
+
+@task(task_id='setup__upload_artifacts_to_s3')
+def upload_artifacts_to_s3():
+    '''Upload example CSV input data and an example Spark script to be used by the Glue Job'''
+    s3_hook = S3Hook()
+    s3_load_kwargs = {"replace": True, "bucket_name": GLUE_EXAMPLE_S3_BUCKET}
+    s3_hook.load_string(string_data=EXAMPLE_CSV, key='input/input.csv', **s3_load_kwargs)
+    s3_hook.load_string(string_data=EXAMPLE_SCRIPT, key='etl_script.py', **s3_load_kwargs)
+
+
+with DAG(
+    dag_id='example_glue',
+    schedule_interval=None,
+    start_date=datetime(2021, 1, 1),
+    tags=['example'],
+    catchup=False,
+) as glue_dag:
+
+    setup_upload_artifacts_to_s3 = upload_artifacts_to_s3()
+
+    # [START howto_operator_glue_crawler]
+    crawl_s3 = GlueCrawlerOperator(
+        task_id='crawl_s3',
+        config=GLUE_CRAWLER_CONFIG,
+        wait_for_completion=False,
+    )
+    # [END howto_operator_glue_crawler]
+
+    # [START howto_sensor_glue_crawler]
+    wait_for_crawl = GlueCrawlerSensor(task_id='wait_for_crawl', crawler_name=GLUE_CRAWLER_NAME)
+    # [END howto_sensor_glue_crawler]
+
+    # [START howto_operator_glue]
+    job_name = 'example_glue_job'
+    submit_glue_job = GlueJobOperator(
+        task_id='submit_glue_job',
+        job_name=job_name,
+        wait_for_completion=False,
+        script_location=f's3://{GLUE_EXAMPLE_S3_BUCKET}/etl_script.py',
+        s3_bucket=GLUE_EXAMPLE_S3_BUCKET,
+        iam_role_name=GLUE_CRAWLER_ROLE.split('/')[-1],
+        create_job_kwargs={'GlueVersion': '3.0', 'NumberOfWorkers': 2, 'WorkerType': 'G.1X'},
+    )
+    # [END howto_operator_glue]
+
+    # [START howto_sensor_glue]
+    wait_for_job = GlueJobSensor(
+        task_id='wait_for_job',
+        job_name=job_name,
+        # Job ID extracted from previous Glue Job Operator task
+        run_id="{{ ti.xcom_pull(task_ids='submit_glue_job') }}",

Review comment:
       Sure, updated the PR with this suggestion :)
   
   Note: I also removed the header from the example CSV file since it was causing issues in the glue job, so when you see that in the diff, it was intentional :+1: 




-- 
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



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

Posted by GitBox <gi...@apache.org>.
josh-fell commented on a change in pull request #22295:
URL: https://github.com/apache/airflow/pull/22295#discussion_r827536792



##########
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 really should be using the TaskFlow API where possible. There was an effort a while back to transition the example DAGs to this approach. Related to #9415




-- 
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