Glue DG
Glue DG
Glue DG
Developer Guide
AWS Glue Developer Guide
Amazon's trademarks and trade dress may not be used in connection with any product or service that is not
Amazon's, in any manner that is likely to cause confusion among customers, or in any manner that disparages or
discredits Amazon. All other trademarks not owned by Amazon are the property of their respective owners, who may
or may not be affiliated with, connected to, or sponsored by Amazon.
AWS Glue Developer Guide
Table of Contents
What Is AWS Glue? ............................................................................................................................. 1
When Should I Use AWS Glue? .................................................................................................... 1
How It Works .................................................................................................................................... 3
Serverless ETL Jobs Run in Isolation ............................................................................................. 3
Concepts ................................................................................................................................... 4
AWS Glue Terminology ....................................................................................................... 5
Components .............................................................................................................................. 6
AWS Glue Console .............................................................................................................. 6
AWS Glue Data Catalog ...................................................................................................... 7
AWS Glue Crawlers and Classifiers ........................................................................................ 7
AWS Glue ETL Operations ................................................................................................... 7
The AWS Glue Jobs System ................................................................................................. 8
Converting Semi-Structured Schemas to Relational Schemas ........................................................... 8
Getting Started ................................................................................................................................ 10
Setting up IAM Permissions for AWS Glue ................................................................................... 10
Step 1: Create an IAM Policy for the AWS Glue Service .......................................................... 10
Step 2: Create an IAM Role for AWS Glue ............................................................................ 14
Step 3: Attach a Policy to IAM Users That Access AWS Glue ................................................... 15
Step 4: Create an IAM Policy for Notebook Servers ............................................................... 23
Step 5: Create an IAM Role for Notebook Servers ................................................................. 25
Step 6: Create an IAM Policy for Amazon SageMaker Notebooks ............................................. 26
Step 7: Create an IAM Role for Amazon SageMaker Notebooks ............................................... 28
Setting Up DNS in Your VPC ...................................................................................................... 29
Setting Up Your Environment to Access Data Stores ..................................................................... 29
Amazon VPC Endpoints for Amazon S3 ............................................................................... 30
Setting Up a VPC to Connect to JDBC Data Stores ................................................................ 31
Setting Up Your Environment for Development Endpoints ............................................................. 34
Setting Up Your Network for a Development Endpoint .......................................................... 34
Setting Up Amazon EC2 for a Notebook Server .................................................................... 35
Setting Up Encryption .............................................................................................................. 36
Console Workflow Overview ...................................................................................................... 38
Security ........................................................................................................................................... 40
Data Protection ........................................................................................................................ 40
Encryption at Rest ............................................................................................................ 40
Encryption in Transit ......................................................................................................... 46
Key Management ............................................................................................................. 46
Internetwork Traffic Privacy ............................................................................................... 46
AWS Glue Dependency on Other AWS Services .................................................................... 48
Development Endpoints .................................................................................................... 49
Identity and Access Management ............................................................................................... 49
Authentication ................................................................................................................. 49
Access Control Overview ................................................................................................... 51
Cross-Account Access ........................................................................................................ 60
Resource ARNs ................................................................................................................. 64
Policy Examples ............................................................................................................... 68
API Permissions Reference ................................................................................................. 83
Logging and Monitoring .......................................................................................................... 100
Compliance Validation ............................................................................................................. 100
Resilience .............................................................................................................................. 101
Infrastructure Security ............................................................................................................. 101
Using AWS Glue with VPC Endpoints ................................................................................ 101
Shared Amazon VPCs ...................................................................................................... 102
Populating the AWS Glue Data Catalog ............................................................................................. 103
Defining a Database in Your Data Catalog ................................................................................. 104
iii
AWS Glue Developer Guide
iv
AWS Glue Developer Guide
v
AWS Glue Developer Guide
Error: Job Run Failed Because the Role Passed Should Be Given Assume Role Permissions for
the AWS Glue Service ..................................................................................................... 289
Error: DescribeVpcEndpoints Action Is Unauthorized. Unable to Validate VPC ID vpc-id ............. 289
Error: DescribeRouteTables Action Is Unauthorized. Unable to Validate Subnet Id: subnet-id in
VPC id: vpc-id ................................................................................................................ 290
Error: Failed to Call ec2:DescribeSubnets ........................................................................... 290
Error: Failed to Call ec2:DescribeSecurityGroups ................................................................. 290
Error: Could Not Find Subnet for AZ ................................................................................. 290
Error: Job Run Exception When Writing to a JDBC Target ..................................................... 290
Error: Amazon S3 Timeout ............................................................................................... 291
Error: Amazon S3 Access Denied ....................................................................................... 291
Error: Amazon S3 Access Key ID Does Not Exist .................................................................. 291
Error: Job Run Fails When Accessing Amazon S3 with an s3a:// URI .................................... 291
Error: Amazon S3 Service Token Expired ............................................................................ 292
Error: No Private DNS for Network Interface Found ............................................................. 293
Error: Development Endpoint Provisioning Failed ................................................................ 293
Error: Notebook Server CREATE_FAILED ............................................................................. 293
Error: Local Notebook Fails to Start .................................................................................. 293
Error: Notebook Usage Errors ........................................................................................... 293
Error: Running Crawler Failed ........................................................................................... 294
Error: Upgrading Athena Data Catalog .............................................................................. 294
Error: A Job is Reprocessing Data When Job Bookmarks Are Enabled ..................................... 294
AWS Glue Limits ..................................................................................................................... 295
ETL Programming ........................................................................................................................... 296
General Information ................................................................................................................ 296
Special Parameters ......................................................................................................... 296
Connection Parameters ................................................................................................... 298
Format Options .............................................................................................................. 300
Managing Partitions ........................................................................................................ 303
Grouping Input Files ....................................................................................................... 304
Reading from JDBC in Parallel .......................................................................................... 305
Moving Data to and from Amazon Redshift ....................................................................... 306
Data Catalog Support for Spark SQL Jobs ......................................................................... 307
Excluding Amazon S3 Storage Classes ............................................................................... 309
Developing and Testing ETL Scripts Locally ........................................................................ 311
ETL Programming in Python .................................................................................................... 315
Using Python ................................................................................................................. 315
List of Extensions ........................................................................................................... 315
List of Transforms .......................................................................................................... 315
Python Setup ................................................................................................................. 316
Calling APIs ................................................................................................................... 316
Python Libraries ............................................................................................................. 318
Python Samples ............................................................................................................. 319
PySpark Extensions ......................................................................................................... 333
PySpark Transforms ........................................................................................................ 357
ETL Programming in Scala ....................................................................................................... 385
Using Scala .................................................................................................................... 390
Scala API List ................................................................................................................. 391
Machine Learning Transforms ........................................................................................................... 432
Types of Machine Learning Transforms ...................................................................................... 432
Find Matches Transform .................................................................................................. 433
Tuning Machine Learning Transforms ........................................................................................ 435
Machine Learning Measurements ...................................................................................... 435
Deciding Between Precision and Recall .............................................................................. 436
Deciding Between Accuracy and Cost ................................................................................ 437
Teaching the Find Matches Transform ............................................................................... 437
Machine Learning Transforms on the Console ............................................................................ 438
vi
AWS Glue Developer Guide
vii
AWS Glue Developer Guide
viii
AWS Glue Developer Guide
ix
AWS Glue Developer Guide
Issues with Development Endpoints Created with AWS Glue Version 1.0 ........................................ 620
AWS Glue Release Notes ................................................................................................................. 621
AWS Glue Versions ................................................................................................................. 621
Document History .......................................................................................................................... 622
Earlier Updates ....................................................................................................................... 628
AWS Glossary ................................................................................................................................. 629
x
AWS Glue Developer Guide
When Should I Use AWS Glue?
Use the AWS Glue console to discover data, transform it, and make it available for search and querying.
The console calls the underlying services to orchestrate the work required to transform your data. You
can also use the AWS Glue API operations to interface with AWS Glue services. Edit, debug, and test your
Python or Scala Apache Spark ETL code using a familiar development environment.
AWS Glue simplifies many tasks when you are building a data warehouse:
• Discovers and catalogs metadata about your data stores into a central catalog. You can process semi-
structured data, such as clickstream or process logs.
• Populates the AWS Glue Data Catalog with table definitions from scheduled crawler programs.
Crawlers call classifier logic to infer the schema, format, and data types of your data. This metadata is
stored as tables in the AWS Glue Data Catalog and used in the authoring process of your ETL jobs.
• Generates ETL scripts to transform, flatten, and enrich your data from source to target.
• Detects schema changes and adapts based on your preferences.
• Triggers your ETL jobs based on a schedule or event. You can initiate jobs automatically to move your
data into your data warehouse. Triggers can be used to create a dependency flow between jobs.
• Gathers runtime metrics to monitor the activities of your data warehouse.
• Handles errors and retries automatically.
• Scales resources, as needed, to run your jobs.
You can use AWS Glue when you run serverless queries against your Amazon S3 data lake. AWS Glue
can catalog your Amazon Simple Storage Service (Amazon S3) data, making it available for querying
with Amazon Athena and Amazon Redshift Spectrum. With crawlers, your metadata stays in sync with
the underlying data. Athena and Redshift Spectrum can directly query your Amazon S3 data lake using
the AWS Glue Data Catalog. With AWS Glue, you access and analyze data through one unified interface
without loading it into multiple data silos.
You can create event-driven ETL pipelines with AWS Glue. You can run your ETL jobs as soon as
new data becomes available in Amazon S3 by invoking your AWS Glue ETL jobs from an AWS Lambda
function. You can also register this new dataset in the AWS Glue Data Catalog as part of your ETL jobs.
1
AWS Glue Developer Guide
When Should I Use AWS Glue?
You can use AWS Glue to understand your data assets. You can store your data using various AWS
services and still maintain a unified view of your data using the AWS Glue Data Catalog. View the Data
Catalog to quickly search and discover the datasets that you own, and maintain the relevant metadata in
one central repository. The Data Catalog also serves as a drop-in replacement for your external Apache
Hive Metastore.
2
AWS Glue Developer Guide
Serverless ETL Jobs Run in Isolation
AWS Glue takes care of provisioning and managing the resources that are required to run your workload.
You don't need to create the infrastructure for an ETL tool because AWS Glue does it for you. When
resources are required, to reduce startup time, AWS Glue uses an instance from its warm pool of
instances to run your workload.
With AWS Glue, you create jobs using table definitions in your Data Catalog. Jobs consist of scripts that
contain the programming logic that performs the transformation. You use triggers to initiate jobs either
on a schedule or as a result of a specified event. You determine where your target data resides and which
source data populates your target. With your input, AWS Glue generates the code that's required to
transform your data from source to target. You can also provide scripts in the AWS Glue console or API to
process your data.
AWS Glue is available in several AWS Regions. For more information, see AWS Regions and Endpoints in
the Amazon Web Services General Reference.
Topics
• Serverless ETL Jobs Run in Isolation (p. 3)
• AWS Glue Concepts (p. 4)
• AWS Glue Components (p. 6)
• Converting Semi-Structured Schemas to Relational Schemas (p. 8)
During provisioning of an ETL job, you provide input data sources and output data targets in your virtual
private cloud (VPC). In addition, you provide the IAM role, VPC ID, subnet ID, and security group that
are needed to access data sources and targets. For each tuple (customer account ID, IAM role, subnet
ID, and security group), AWS Glue creates a new Spark environment that is isolated at the network and
management level from all other Spark environments inside the AWS Glue service account.
AWS Glue creates elastic network interfaces in your subnet using private IP addresses. Spark jobs use
these elastic network interfaces to access your data sources and data targets. Traffic in, out, and within
3
AWS Glue Developer Guide
Concepts
the Spark environment is governed by your VPC and networking policies with one exception: Calls made
to AWS Glue libraries can proxy traffic to AWS Glue API operations through the AWS Glue VPC. All AWS
Glue API calls are logged; thus, data owners can audit API access by enabling AWS CloudTrail, which
delivers audit logs to your account.
AWS Glue managed Spark environments that run your ETL jobs are protected with the same security
practices followed by other AWS services. Those practices are listed in the AWS Access section of the
Introduction to AWS Security Processes whitepaper.
You define jobs in AWS Glue to accomplish the work that's required to extract, transform, and load (ETL)
data from a data source to a data target. You typically perform the following actions:
• You define a crawler to populate your AWS Glue Data Catalog with metadata table definitions. You
point your crawler at a data store, and the crawler creates table definitions in the Data Catalog.
In addition to table definitions, the AWS Glue Data Catalog contains other metadata that is required to
define ETL jobs. You use this metadata when you define a job to transform your data.
• AWS Glue can generate a script to transform your data. Or, you can provide the script in the AWS Glue
console or API.
• You can run your job on demand, or you can set it up to start when a specified trigger occurs. The
trigger can be a time-based schedule or an event.
4
AWS Glue Developer Guide
AWS Glue Terminology
When your job runs, a script extracts data from your data source, transforms the data, and loads it to
your data target. The script runs in an Apache Spark environment in AWS Glue.
Important
Tables and databases in AWS Glue are objects in the AWS Glue Data Catalog. They contain
metadata; they don't contain data from a data store.
Text-based data, such as CSVs, must be encoded in UTF-8 for AWS Glue to process it successfully.
For more information, see UTF-8 in Wikipedia.
Classifier
Determines the schema of your data. AWS Glue provides classifiers for common file types, such as CSV,
JSON, AVRO, XML, and others. It also provides classifiers for common relational database management
systems using a JDBC connection. You can write your own classifier by using a grok pattern or by
specifying a row tag in an XML document.
Connection
Contains the properties that are required to connect to your data store.
Crawler
A program that connects to a data store (source or target), progresses through a prioritized list of
classifiers to determine the schema for your data, and then creates metadata tables in the AWS Glue
Data Catalog.
Database
A set of associated Data Catalog table definitions organized into a logical group in AWS Glue.
Development endpoint
An environment that you can use to develop and test your AWS Glue ETL scripts.
5
AWS Glue Developer Guide
Components
Job
The business logic that is required to perform ETL work. It is composed of a transformation script, data
sources, and data targets. Job runs are initiated by triggers that can be scheduled or triggered by events.
Notebook server
A web-based environment that you can use to run your PySpark statements. PySpark is a Python dialect
for ETL programming. For more information, see Apache Zeppelin. You can set up a notebook server on a
development endpoint to run PySpark statements with AWS Glue extensions.
Script
Code that extracts data from sources, transforms it, and loads it into targets. AWS Glue generates
PySpark or Scala scripts.
Table
The metadata definition that represents your data. Whether your data is in an Amazon Simple Storage
Service (Amazon S3) file, an Amazon Relational Database Service (Amazon RDS) table, or another set
of data, a table defines the schema of your data. A table in the AWS Glue Data Catalog consists of
the names of columns, data type definitions, partition information, and other metadata about a base
dataset. The schema of your data is represented in your AWS Glue table definition. The actual data
remains in its original data store, whether it be in a file or a relational database table. AWS Glue catalogs
your files and relational database tables in the AWS Glue Data Catalog. They are used as sources and
targets when you create an ETL job.
Transform
The code logic that is used to manipulate your data into a different format.
Trigger
Initiates an ETL job. Triggers can be defined based on a scheduled time or an event.
AWS Glue uses the AWS Glue Data Catalog to store metadata about data sources, transforms, and
targets. The Data Catalog is a drop-in replacement for the Apache Hive Metastore. The AWS Glue Jobs
system provides a managed infrastructure for defining, scheduling, and running ETL operations on your
data. For more information about the AWS Glue API, see AWS Glue API (p. 446).
6
AWS Glue Developer Guide
AWS Glue Data Catalog
• Define AWS Glue objects such as jobs, tables, crawlers, and connections.
• Schedule when crawlers run.
• Define events or schedules for job triggers.
• Search and filter lists of AWS Glue objects.
• Edit transformation scripts.
Each AWS account has one AWS Glue Data Catalog per AWS region. It provides a uniform repository
where disparate systems can store and find metadata to keep track of data in data silos, and use that
metadata to query and transform the data.
You can use AWS Identity and Access Management (IAM) policies to control access to the data sources
managed by the AWS Glue Data Catalog. These policies allow different groups in your enterprise to
safely publish data to the wider organization while protecting sensitive information. IAM policies let you
clearly and consistently define which users have access to which data, regardless of its location.
For information about how to use the AWS Glue Data Catalog, see Populating the AWS Glue Data
Catalog (p. 103). For information about how to program using the Data Catalog API, see Catalog
API (p. 461).
Other AWS services and open source projects can use the AWS Glue Data Catalog:
• Amazon Athena – for more information, see Understanding Tables, Databases, and the Data Catalog in
the Amazon Athena User Guide.
• Amazon Redshift Spectrum – for more information, see Using Amazon Redshift Spectrum to Query
External Data in the Amazon Redshift Database Developer Guide.
• Amazon EMR – for more information, see Use Resource-Based Policies for Amazon EMR Access to AWS
Glue Data Catalog in the Amazon EMR Management Guide.
• AWS Glue Data Catalog Client for Apache Hive Metastore – for more information about this GitHub
project, see AWS Glue Data Catalog Client for Apache Hive Metastore.
For information about how to set up crawlers and classifiers, see Defining Crawlers (p. 114). For
information about how to program crawlers and classifiers using the AWS Glue API, see Crawlers and
Classifiers API (p. 506).
7
AWS Glue Developer Guide
The AWS Glue Jobs System
different repository, where it can be queried and analyzed. Such a script might convert a CSV file into a
relational form and save it in Amazon Redshift.
For more information about how to use AWS Glue ETL capabilities, see Programming ETL
Scripts (p. 296).
For more information about using the AWS Glue Jobs system, see Running and Monitoring AWS
Glue (p. 216). For information about programming using the AWS Glue Jobs system API, see Jobs
API (p. 534).
Semi-structured data typically contains mark-up to identify entities within the data. It can have nested
data structures with no fixed schema. For more information about semi-structured data, see Semi-
structured data in Wikipedia.
Relational data is represented by tables that consist of rows and columns. Relationships between tables
can be represented by a primary key (PK) to foreign key (FK) relationship. For more information, see
Relational database in Wikipedia.
AWS Glue uses crawlers to infer schemas for semi-structured data. It then transforms the data to a
relational schema using an ETL (extract, transform, and load) job. For example, you might want to
parse JSON data from Amazon Simple Storage Service (Amazon S3) source files to Amazon Relational
Database Service (Amazon RDS) tables. Understanding how AWS Glue handles the differences between
schemas can help you understand the transformation process.
This diagram shows how AWS Glue transforms a semi-structured schema to a relational schema.
8
AWS Glue Developer Guide
Converting Semi-Structured
Schemas to Relational Schemas
9
AWS Glue Developer Guide
Setting up IAM Permissions for AWS Glue
Topics
• Setting up IAM Permissions for AWS Glue (p. 10)
• Setting Up DNS in Your VPC (p. 29)
• Setting Up Your Environment to Access Data Stores (p. 29)
• Setting Up Your Environment for Development Endpoints (p. 34)
• Setting Up Encryption in AWS Glue (p. 36)
• AWS Glue Console Workflow Overview (p. 38)
1. Create an IAM Policy for the AWS Glue Service (p. 10): Create a service policy that allows access to
AWS Glue resources.
2. Create an IAM Role for AWS Glue (p. 14): Create an IAM role, and attach the AWS Glue service policy
and a policy for your Amazon Simple Storage Service (Amazon S3) resources that are used by AWS
Glue.
3. Attach a Policy to IAM Users That Access AWS Glue (p. 15): Attach policies to any IAM user that
signs in to the AWS Glue console.
4. Create an IAM Policy for Notebooks (p. 23): Create a notebook server policy to use in the creation
of notebook servers on development endpoints.
5. Create an IAM Role for Notebooks (p. 25): Create an IAM role and attach the notebook server policy.
6. Create an IAM Policy for Amazon SageMaker Notebooks (p. 26): Create an IAM policy to use when
creating Amazon SageMaker notebooks on development endpoints.
7. Create an IAM Role for Amazon SageMaker Notebooks (p. 28): Create an IAM role and attach the
policy to grant permissions when creating Amazon SageMaker notebooks on development endpoints.
In this step, you create a policy that is similar to AWSGlueServiceRole. You can find the most current
version of AWSGlueServiceRole on the IAM console.
10
AWS Glue Developer Guide
Step 1: Create an IAM Policy for the AWS Glue Service
in this policy refer to default names that are used by AWS Glue for Amazon S3 buckets, Amazon S3 ETL
scripts, CloudWatch Logs, and Amazon EC2 resources. For simplicity, AWS Glue writes some Amazon S3
objects into buckets in your account prefixed with aws-glue-* by default.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the left navigation pane, choose Policies.
3. Choose Create Policy.
4. On the Create Policy screen, navigate to a tab to edit JSON. Create a policy document with the
following JSON statements, and then choose Review policy.
Note
Add any permissions needed for Amazon S3 resources. You might want to scope the
resources section of your access policy to only those resources that are required.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:*",
"s3:GetBucketLocation",
"s3:ListBucket",
"s3:ListAllMyBuckets",
"s3:GetBucketAcl",
"ec2:DescribeVpcEndpoints",
"ec2:DescribeRouteTables",
"ec2:CreateNetworkInterface",
"ec2:DeleteNetworkInterface",
"ec2:DescribeNetworkInterfaces",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcAttribute",
"iam:ListRolePolicies",
"iam:GetRole",
"iam:GetRolePolicy",
"cloudwatch:PutMetricData"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:CreateBucket"
],
"Resource": [
"arn:aws:s3:::aws-glue-*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject",
"s3:DeleteObject"
],
"Resource": [
"arn:aws:s3:::aws-glue-*/*",
"arn:aws:s3:::*/*aws-glue-*/*"
]
11
AWS Glue Developer Guide
Step 1: Create an IAM Policy for the AWS Glue Service
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject"
],
"Resource": [
"arn:aws:s3:::crawler-public*",
"arn:aws:s3:::aws-glue-*"
]
},
{
"Effect": "Allow",
"Action": [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents",
"logs:AssociateKmsKey"
],
"Resource": [
"arn:aws:logs:*:*:/aws-glue/*"
]
},
{
"Effect": "Allow",
"Action": [
"ec2:CreateTags",
"ec2:DeleteTags"
],
"Condition": {
"ForAllValues:StringEquals": {
"aws:TagKeys": [
"aws-glue-service-resource"
]
}
},
"Resource": [
"arn:aws:ec2:*:*:network-interface/*",
"arn:aws:ec2:*:*:security-group/*",
"arn:aws:ec2:*:*:instance/*"
]
}
]
}
12
AWS Glue Developer Guide
Step 1: Create an IAM Policy for the AWS Glue Service
13
AWS Glue Developer Guide
Step 2: Create an IAM Role for AWS Glue
5. On the Review Policy screen, type your Policy Name, for example GlueServiceRolePolicy. Type an
optional description, and when you're satisfied with the policy, then Create policy.
You provide those permissions by using AWS Identity and Access Management (IAM). Add a policy to the
IAM role that you pass to AWS Glue.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the left navigation pane, choose Roles.
3. Choose Create role.
4. For role type, choose AWS Service, find and choose Glue, and choose Next: Permissions.
5. On the Attach permissions policy page, choose the policies that contain the required permissions;
for example, the AWS managed policy AWSGlueServiceRole for general AWS Glue permissions and
the AWS managed policy AmazonS3FullAccess for access to Amazon S3 resources. Then choose
Next: Review.
Note
Ensure that one of the policies in this role grants permissions to your Amazon S3 sources
and targets. You might want to provide your own policy for access to specific Amazon S3
resources. Data sources require s3:ListBucket and s3:GetObject permissions. Data
targets require s3:ListBucket, s3:PutObject, and s3:DeleteObject permissions. For
more information about creating an Amazon S3 policy for your resources, see Specifying
Resources in a Policy. For an example Amazon S3 policy, see Writing IAM Policies: How to
Grant Access to an Amazon S3 Bucket.
If you plan to access Amazon S3 sources and targets that are encrypted with SSE-KMS, then
attach a policy that allows AWS Glue crawlers, jobs, and development endpoints to decrypt
the data. For more information, see Protecting Data Using Server-Side Encryption with AWS
KMS-Managed Keys (SSE-KMS). The following is an example:
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
14
AWS Glue Developer Guide
Step 3: Attach a Policy to IAM Users That Access AWS Glue
"kms:Decrypt"
],
"Resource":[
"arn:aws:kms:*:account-id-without-hyphens:key/key-id"
]
}
]
}
6. For Role name, type a name for your role; for example, AWSGlueServiceRoleDefault. Create the
role with the name prefixed with the string AWSGlueServiceRole to allow the role to be passed
from console users to the service. AWS Glue provided policies expect IAM service roles to begin with
AWSGlueServiceRole. Otherwise, you must add a policy to allow your users the iam:PassRole
permission for IAM roles to match your naming convention. Choose Create Role.
When you finish this step, your IAM user has the following policies attached:
You can attach an AWS managed policy or an inline policy to an IAM user to access the AWS Glue
console. Some of the resources specified in this policy refer to default names that are used by AWS Glue
for Amazon S3 buckets, Amazon S3 ETL scripts, CloudWatch Logs, AWS CloudFormation, and Amazon
EC2 resources. For simplicity, AWS Glue writes some Amazon S3 objects into buckets in your account
prefixed with aws-glue-* by default.
Note
You can skip this step if you use the AWS managed policy AWSGlueConsoleFullAccess.
Important
AWS Glue needs permission to assume a role that is used to perform work on your behalf. To
accomplish this, you add the iam:PassRole permissions to your AWS Glue users. This policy
grants permission to roles that begin with AWSGlueServiceRole for AWS Glue service roles,
and AWSGlueServiceNotebookRole for roles that are required when you create a notebook
server. You can also create your own policy for iam:PassRole permissions that follows your
naming convention.
In this step, you create a policy that is similar to AWSGlueConsoleFullAccess. You can find the most
current version of AWSGlueConsoleFullAccess on the IAM console.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the navigation pane, choose Users.
3. In the list, choose the name of the user to embed a policy in.
15
AWS Glue Developer Guide
Step 3: Attach a Policy to IAM Users That Access AWS Glue
4. Choose the Permissions tab and, if necessary, expand the Permissions policies section.
5. Choose the Add Inline policy link.
6. On the Create Policy screen, navigate to a tab to edit JSON. Create a policy document with the
following JSON statements, and then choose Review policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:*",
"redshift:DescribeClusters",
"redshift:DescribeClusterSubnetGroups",
"iam:ListRoles",
"iam:ListRolePolicies",
"iam:GetRole",
"iam:GetRolePolicy",
"iam:ListAttachedRolePolicies",
"ec2:DescribeSecurityGroups",
"ec2:DescribeSubnets",
"ec2:DescribeVpcs",
"ec2:DescribeVpcEndpoints",
"ec2:DescribeRouteTables",
"ec2:DescribeVpcAttribute",
"ec2:DescribeKeyPairs",
"ec2:DescribeInstances",
"rds:DescribeDBInstances",
"s3:ListAllMyBuckets",
"s3:ListBucket",
"s3:GetBucketAcl",
"s3:GetBucketLocation",
"cloudformation:DescribeStacks",
"cloudformation:GetTemplateSummary",
"dynamodb:ListTables",
"kms:ListAliases",
"kms:DescribeKey",
"cloudwatch:GetMetricData",
"cloudwatch:ListDashboards"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::aws-glue-*/*",
"arn:aws:s3:::*/*aws-glue-*/*",
"arn:aws:s3:::aws-glue-*"
]
},
{
"Effect": "Allow",
"Action": [
"tag:GetResources"
],
"Resource": [
"*"
]
16
AWS Glue Developer Guide
Step 3: Attach a Policy to IAM Users That Access AWS Glue
},
{
"Effect": "Allow",
"Action": [
"s3:CreateBucket"
],
"Resource": [
"arn:aws:s3:::aws-glue-*"
]
},
{
"Effect": "Allow",
"Action": [
"logs:GetLogEvents"
],
"Resource": [
"arn:aws:logs:*:*:/aws-glue/*"
]
},
{
"Effect": "Allow",
"Action": [
"cloudformation:CreateStack",
"cloudformation:DeleteStack"
],
"Resource": "arn:aws:cloudformation:*:*:stack/aws-glue*/*"
},
{
"Effect": "Allow",
"Action": [
"ec2:RunInstances"
],
"Resource": [
"arn:aws:ec2:*:*:instance/*",
"arn:aws:ec2:*:*:key-pair/*",
"arn:aws:ec2:*:*:image/*",
"arn:aws:ec2:*:*:security-group/*",
"arn:aws:ec2:*:*:network-interface/*",
"arn:aws:ec2:*:*:subnet/*",
"arn:aws:ec2:*:*:volume/*"
]
},
{
"Effect": "Allow",
"Action": [
"ec2:TerminateInstances",
"ec2:CreateTags",
"ec2:DeleteTags"
],
"Resource": [
"arn:aws:ec2:*:*:instance/*"
],
"Condition": {
"StringLike": {
"ec2:ResourceTag/aws:cloudformation:stack-id":
"arn:aws:cloudformation:*:*:stack/aws-glue-*/*"
},
"StringEquals": {
"ec2:ResourceTag/aws:cloudformation:logical-id": "ZeppelinInstance"
}
}
},
{
"Action": [
"iam:PassRole"
],
17
AWS Glue Developer Guide
Step 3: Attach a Policy to IAM Users That Access AWS Glue
"Effect": "Allow",
"Resource": "arn:aws:iam::*:role/AWSGlueServiceRole*",
"Condition": {
"StringLike": {
"iam:PassedToService": [
"glue.amazonaws.com"
]
}
}
},
{
"Action": [
"iam:PassRole"
],
"Effect": "Allow",
"Resource": "arn:aws:iam::*:role/AWSGlueServiceNotebookRole*",
"Condition": {
"StringLike": {
"iam:PassedToService": [
"ec2.amazonaws.com"
]
}
}
},
{
"Action": [
"iam:PassRole"
],
"Effect": "Allow",
"Resource": [
"arn:aws:iam::*:role/service-role/AWSGlueServiceRole*"
],
"Condition": {
"StringLike": {
"iam:PassedToService": [
"glue.amazonaws.com"
]
}
}
}
]
}
18
AWS Glue Developer Guide
Step 3: Attach a Policy to IAM Users That Access AWS Glue
• "glue:ListCrawlers"
• "glue:BatchGetCrawlers"
• "glue:ListTriggers"
• "glue:BatchGetTriggers"
• "glue:ListDevEndpoints"
• "glue:BatchGetDevEndpoints"
• "glue:ListJobs"
• "glue:BatchGetJobs"
19
AWS Glue Developer Guide
Step 3: Attach a Policy to IAM Users That Access AWS Glue
20
AWS Glue Developer Guide
Step 3: Attach a Policy to IAM Users That Access AWS Glue
7. On the Review policy screen, type a name for the policy, for example GlueConsoleAccessPolicy.
When you're satisfied with the policy, then choose Create policy. Ensure that no errors appear in a
red box at the top of the screen. Correct any that are reported.
Note
If Use autoformatting is selected, the policy is reformatted whenever you open a policy or
choose Validate Policy.
You can attach the AWSGlueConsoleFullAccess policy to provide permissions that are required by the
AWS Glue console user.
Note
You can skip this step if you created your own policy for AWS Glue console access.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the navigation pane, choose Policies.
3. In the list of policies, select the check box next to the AWSGlueConsoleFullAccess. You can use the
Filter menu and the search box to filter the list of policies.
4. Choose Policy actions, and then choose Attach.
5. Choose the user to attach the policy to. You can use the Filter menu and the search box to filter the
list of principal entities. After choosing the user to attach the policy to, choose Attach policy.
21
AWS Glue Developer Guide
Step 3: Attach a Policy to IAM Users That Access AWS Glue
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the navigation pane, choose Policies.
3. In the list of policies, select the check box next to the
AWSGlueConsoleSageMakerNotebookFullAccess. You can use the Filter menu and the search box
to filter the list of policies.
4. Choose Policy actions, and then choose Attach.
5. Choose the user to attach the policy to. You can use the Filter menu and the search box to filter the
list of principal entities. After choosing the user to attach the policy to, choose Attach policy.
You can attach the CloudWatchLogsReadOnlyAccess policy to a user to view the logs created by AWS
Glue on the CloudWatch Logs console.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the navigation pane, choose Policies.
3. In the list of policies, select the check box next to the CloudWatchLogsReadOnlyAccess. You can use
the Filter menu and the search box to filter the list of policies.
4. Choose Policy actions, and then choose Attach.
5. Choose the user to attach the policy to. You can use the Filter menu and the search box to filter the
list of principal entities. After choosing the user to attach the policy to, choose Attach policy.
You can attach the AWSCloudFormationReadOnlyAccess policy to a user to view the AWS
CloudFormation stacks used by AWS Glue on the AWS CloudFormation console.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the navigation pane, choose Policies.
3. In the list of policies, select the check box next to the AWSCloudFormationReadOnlyAccess. You
can use the Filter menu and the search box to filter the list of policies.
4. Choose Policy actions, and then choose Attach.
5. Choose the user to attach the policy to. You can use the Filter menu and the search box to filter the
list of principal entities. After choosing the user to attach the policy to, choose Attach policy.
You can attach the AmazonAthenaFullAccess policy to a user to view Amazon S3 data in the Athena
console.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
22
AWS Glue Developer Guide
Step 4: Create an IAM Policy for Notebook Servers
This policy grants permission for some Amazon S3 actions to manage resources in your account that are
needed by AWS Glue when it assumes the role using this policy. Some of the resources that are specified
in this policy refer to default names used by AWS Glue for Amazon S3 buckets, Amazon S3 ETL scripts,
and Amazon EC2 resources. For simplicity, AWS Glue defaults writing some Amazon S3 objects into
buckets in your account prefixed with aws-glue-*.
Note
You can skip this step if you use the AWS managed policy AWSGlueServiceNotebookRole.
In this step, you create a policy that is similar to AWSGlueServiceNotebookRole. You can find the
most current version of AWSGlueServiceNotebookRole on the IAM console.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the left navigation pane, choose Policies.
3. Choose Create Policy.
4. On the Create Policy screen, navigate to a tab to edit JSON. Create a policy document with the
following JSON statements, and then choose Review policy.
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"glue:CreateDatabase",
"glue:CreatePartition",
"glue:CreateTable",
"glue:DeleteDatabase",
"glue:DeletePartition",
"glue:DeleteTable",
"glue:GetDatabase",
"glue:GetDatabases",
"glue:GetPartition",
"glue:GetPartitions",
"glue:GetTable",
"glue:GetTableVersions",
"glue:GetTables",
"glue:UpdateDatabase",
"glue:UpdatePartition",
"glue:UpdateTable",
"glue:CreateBookmark",
"glue:GetBookmark",
23
AWS Glue Developer Guide
Step 4: Create an IAM Policy for Notebook Servers
"glue:UpdateBookmark",
"glue:GetMetric",
"glue:PutMetric",
"glue:CreateConnection",
"glue:CreateJob",
"glue:DeleteConnection",
"glue:DeleteJob",
"glue:GetConnection",
"glue:GetConnections",
"glue:GetDevEndpoint",
"glue:GetDevEndpoints",
"glue:GetJob",
"glue:GetJobs",
"glue:UpdateJob",
"glue:BatchDeleteConnection",
"glue:UpdateConnection",
"glue:GetUserDefinedFunction",
"glue:UpdateUserDefinedFunction",
"glue:GetUserDefinedFunctions",
"glue:DeleteUserDefinedFunction",
"glue:CreateUserDefinedFunction",
"glue:BatchGetPartition",
"glue:BatchDeletePartition",
"glue:BatchCreatePartition",
"glue:BatchDeleteTable",
"glue:UpdateDevEndpoint",
"s3:GetBucketLocation",
"s3:ListBucket",
"s3:ListAllMyBuckets",
"s3:GetBucketAcl"
],
"Resource":[
"*"
]
},
{
"Effect":"Allow",
"Action":[
"s3:GetObject"
],
"Resource":[
"arn:aws:s3:::crawler-public*",
"arn:aws:s3:::aws-glue*"
]
},
{
"Effect":"Allow",
"Action":[
"s3:PutObject",
"s3:DeleteObject"
],
"Resource":[
"arn:aws:s3:::aws-glue*"
]
},
{
"Effect":"Allow",
"Action":[
"ec2:CreateTags",
"ec2:DeleteTags"
],
"Condition":{
"ForAllValues:StringEquals":{
"aws:TagKeys":[
"aws-glue-service-resource"
]
24
AWS Glue Developer Guide
Step 5: Create an IAM Role for Notebook Servers
}
},
"Resource":[
"arn:aws:ec2:*:*:network-interface/*",
"arn:aws:ec2:*:*:security-group/*",
"arn:aws:ec2:*:*:instance/*"
]
}
]
}
25
AWS Glue Developer Guide
Step 6: Create an IAM Policy for
Amazon SageMaker Notebooks
Note
When you create an IAM role using the IAM console, the console creates an instance profile
automatically and gives it the same name as the role to which it corresponds.
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the left navigation pane, choose Roles.
3. Choose Create role.
4. For role type, choose AWS Service, find and choose EC2, and choose the EC2 use case, then choose
Next: Permissions.
5. On the Attach permissions policy page, choose the policies that contain the required permissions;
for example, AWSGlueServiceNotebookRole for general AWS Glue permissions and the AWS
managed policy AmazonS3FullAccess for access to Amazon S3 resources. Then choose Next:
Review.
Note
Ensure that one of the policies in this role grants permissions to your Amazon S3 sources
and targets. Also confirm that your policy allows full access to the location where you store
your notebook when you create a notebook server. You might want to provide your own
policy for access to specific Amazon S3 resources. For more information about creating an
Amazon S3 policy for your resources, see Specifying Resources in a Policy.
If you plan to access Amazon S3 sources and targets that are encrypted with SSE-KMS,
then attach a policy which allows notebooks to decrypt the data. For more information, see
Protecting Data Using Server-Side Encryption with AWS KMS-Managed Keys (SSE-KMS). For
example:
{
"Version":"2012-10-17",
"Statement":[
{
"Effect":"Allow",
"Action":[
"kms:Decrypt"
],
"Resource":[
"arn:aws:kms:*:account-id-without-hyphens:key/key-id"
]
}
]
}
6. For Role name, type a name for your role. Create the role with the name prefixed with the
string AWSGlueServiceNotebookRole to allow the role to be passed from console users
to the notebook server. AWS Glue provided policies expect IAM service roles to begin with
AWSGlueServiceNotebookRole. Otherwise you must add a policy to your users to allow the
iam:PassRole permission for IAM roles to match your naming convention. For example, type
AWSGlueServiceNotebookRoleDefault. Then choose Create role.
26
AWS Glue Developer Guide
Step 6: Create an IAM Policy for
Amazon SageMaker Notebooks
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the left navigation pane, choose Policies.
3. Choose Create Policy.
4. On the Create Policy page, navigate to a tab to edit the JSON. Create a policy document with the
following JSON statements. Edit bucket-name, region-code, account-id, and development-
endpoint-name for your environment. The development-endpoint-name must already exist
before you use this policy in an IAM role used to create an Amazon SageMaker notebook.
{
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:ListBucket"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::bucket-name"
]
},
{
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": [
"arn:aws:s3:::bucket-name*"
]
},
{
"Action": [
"logs:CreateLogStream",
"logs:DescribeLogStreams",
"logs:PutLogEvents",
"logs:CreateLogGroup"
],
"Effect": "Allow",
"Resource": [
"arn:aws:logs:region-code:account-id:log-group:/aws/sagemaker/*",
"arn:aws:logs:region-code:account-id:log-group:/aws/sagemaker/*:log-
stream:aws-glue-*"
]
},
{
"Action": [
"glue:UpdateDevEndpoint",
"glue:GetDevEndpoint",
"glue:GetDevEndpoints"
],
"Effect": "Allow",
"Resource": [
"arn:aws:glue:region-code:account-id:devEndpoint/development-endpoint-
name*"
]
}
]
}
27
AWS Glue Developer Guide
Step 7: Create an IAM Role for
Amazon SageMaker Notebooks
1. Sign in to the AWS Management Console and open the IAM console at https://
console.aws.amazon.com/iam/.
2. In the left navigation pane, choose Roles.
3. Choose Create role.
4. For role type, choose AWS Service, find and choose SageMaker, and then choose the SageMaker -
Execution use case. Then choose Next: Permissions.
5. On the Attach permissions policy page, choose the policies that contain the required permissions;
for example, AmazonSageMakerFullAccess. Choose Next: Review.
If you plan to access Amazon S3 sources and targets that are encrypted with SSE-KMS, attach a
policy that allows notebooks to decrypt the data, as shown in the following example. For more
information, see Protecting Data Using Server-Side Encryption with AWS KMS-Managed Keys (SSE-
KMS).
{
"Version":"2012-10-17",
"Statement":[
{
28
AWS Glue Developer Guide
Setting Up DNS in Your VPC
"Effect":"Allow",
"Action":[
"kms:Decrypt"
],
"Resource":[
"arn:aws:kms:*:account-id-without-hyphens:key/key-id"
]
}
]
}
6. For Role name, enter a name for your role. To allow the role to be passed from
console users to Amazon SageMaker, use a name that is prefixed with the string
AWSGlueServiceSageMakerNotebookRole. AWS Glue provided policies expect IAM roles to begin
with AWSGlueServiceSageMakerNotebookRole. Otherwise you must add a policy to your users to
allow the iam:PassRole permission for IAM roles to match your naming convention.
Open the role that you just created, AWSGlueServiceSageMakerNotebookRole-Default, and choose
Attach policies. Attach the policy that you created named AWSGlueSageMakerNotebook to the
role.
To set up DNS in your VPC, ensure that DNS hostnames and DNS resolution are both enabled in your
VPC. The VPC network attributes enableDnsHostnames and enableDnsSupport must be set to true.
To view and modify these attributes, go to the VPC console at https://console.aws.amazon.com/vpc/.
If a job needs to run in your VPC subnet—for example, transforming data from a JDBC data store in a
private subnet—AWS Glue sets up elastic network interfaces that enable your jobs to connect securely to
other resources within your VPC. Each elastic network interface is assigned a private IP address from the
IP address range within the subnet you specified. No public IP addresses are assigned. Security groups
29
AWS Glue Developer Guide
Amazon VPC Endpoints for Amazon S3
specified in the AWS Glue connection are applied on each of the elastic network interfaces. For more
information, see Setting Up a VPC to Connect to JDBC Data Stores (p. 31).
All JDBC data stores that are accessed by the job must be available from the VPC subnet. To access
Amazon S3 from within your VPC, a VPC endpoint (p. 30) is required. If your job needs to access both
VPC resources and the public internet, the VPC needs to have a Network Address Translation (NAT)
gateway inside the VPC.
A job or development endpoint can only access one VPC (and subnet) at a time. If you need to access
data stores in different VPCs, you have the following options:
• Use VPC peering to access the data stores. For more about VPC peering, see VPC Peering Basics
• Use an Amazon S3 bucket as an intermediary storage location. Split the work into two jobs, with the
Amazon S3 output of job 1 as the input to job 2.
For JDBC data stores, you create a connection in AWS Glue with the necessary properties to connect to
your data stores. For more information about the connection, see Adding a Connection to Your Data
Store (p. 109).
Note
Make sure you set up your DNS environment for AWS Glue. For more information, see Setting
Up DNS in Your VPC (p. 29).
Topics
• Amazon VPC Endpoints for Amazon S3 (p. 30)
• Setting Up a VPC to Connect to JDBC Data Stores (p. 31)
Many customers have legitimate privacy and security concerns about sending and receiving data across
the public internet. Customers can address these concerns by using a virtual private network (VPN) to
route all Amazon S3 network traffic through their own corporate network infrastructure. However, this
approach can introduce bandwidth and availability challenges.
VPC endpoints for Amazon S3 can alleviate these challenges. A VPC endpoint for Amazon S3 enables
AWS Glue to use private IP addresses to access Amazon S3 with no exposure to the public internet. AWS
Glue does not require public IP addresses, and you don't need an internet gateway, a NAT device, or a
virtual private gateway in your VPC. You use endpoint policies to control access to Amazon S3. Traffic
between your VPC and the AWS service does not leave the Amazon network.
When you create a VPC endpoint for Amazon S3, any requests to an Amazon S3 endpoint within the
Region (for example, s3.us-west-2.amazonaws.com) are routed to a private Amazon S3 endpoint within
the Amazon network. You don't need to modify your applications running on EC2 instances in your VPC
—the endpoint name remains the same, but the route to Amazon S3 stays entirely within the Amazon
network, and does not access the public internet.
For more information about VPC endpoints, see VPC Endpoints in the Amazon VPC User Guide.
30
AWS Glue Developer Guide
Setting Up a VPC to Connect to JDBC Data Stores
The following diagram shows how AWS Glue can use a VPC endpoint to access Amazon S3.
1. Sign in to the AWS Management Console and open the Amazon VPC console at https://
console.aws.amazon.com/vpc/.
2. In the left navigation pane, choose Endpoints.
3. Choose Create Endpoint, and follow the steps to create an Amazon S3 endpoint in your VPC.
1. Sign in to the AWS Management Console and open the Amazon Redshift console at https://
console.aws.amazon.com/redshift/.
2. In the left navigation pane, choose Clusters.
3. Choose the cluster name that you want to access from AWS Glue.
31
AWS Glue Developer Guide
Setting Up a VPC to Connect to JDBC Data Stores
4. In the Cluster Properties section, choose a security group in VPC security groups to allow AWS Glue
to use. Record the name of the security group that you chose for future reference. Choosing the
security group opens the Amazon EC2 console Security Groups list.
5. Choose the security group to modify and navigate to the Inbound tab.
6. Add a self-referencing rule to allow AWS Glue components to communicate. Specifically, add or
confirm that there is a rule of Type All TCP, Protocol is TCP, Port Range includes all ports, and
whose Source is the same security group name as the Group ID.
For example:
7. Add a rule for outbound traffic also. Either open outbound traffic to all ports, for example:
Or create a self-referencing rule where Type All TCP, Protocol is TCP, Port Range includes all
ports, and whose Destination is the same security group name as the Group ID. If using an Amazon
S3 VPC endpoint, also add an HTTPS rule for Amazon S3 access. The s3-prefix-list-id is
required in the security group rule to allow traffic from the VPC to the Amazon S3 VPC endpoint.
For example:
32
AWS Glue Developer Guide
Setting Up a VPC to Connect to JDBC Data Stores
1. Sign in to the AWS Management Console and open the Amazon RDS console at https://
console.aws.amazon.com/rds/.
2. In the left navigation pane, choose Instances.
3. Choose the Amazon RDS Engine and DB Instance name that you want to access from AWS Glue.
4. From Instance Actions, choose See Details. On the Details tab, find the Security Groups name you
will access from AWS Glue. Record the name of the security group for future reference.
5. Choose the security group to open the Amazon EC2 console.
6. Confirm that your Group ID from Amazon RDS is chosen, then choose the Inbound tab.
7. Add a self-referencing rule to allow AWS Glue components to communicate. Specifically, add or
confirm that there is a rule of Type All TCP, Protocol is TCP, Port Range includes all ports, and
whose Source is the same security group name as the Group ID.
For example:
8. Add a rule for outbound traffic also. Either open outbound traffic to all ports, for example:
Or create a self-referencing rule where Type All TCP, Protocol is TCP, Port Range includes all
ports, and whose Destination is the same security group name as the Group ID. If using an Amazon
S3 VPC endpoint, also add an HTTPS rule for Amazon S3 access. The s3-prefix-list-id is
required in the security group rule to allow traffic from the VPC to the Amazon S3 VPC endpoint.
For example:
33
AWS Glue Developer Guide
Setting Up Your Environment for Development Endpoints
Destination Target
10.0.0.0/16 local
0.0.0.0/0 igw-xxxx
To enable AWS Glue to communicate between its components, specify a security group with a self-
referencing inbound rule for all TCP ports. By creating a self-referencing rule, you can restrict the source
to the same security group in the VPC, and it's not open to all networks. The default security group for
your VPC might already have a self-referencing inbound rule for ALL Traffic.
1. Sign in to the AWS Management Console and open the Amazon EC2 console at https://
console.aws.amazon.com/ec2/.
2. In the left navigation pane, choose Security Groups.
3. Either choose an existing security group from the list, or Create Security Group to use with the
development endpoint.
4. In the security group pane, navigate to the Inbound tab.
34
AWS Glue Developer Guide
Setting Up Amazon EC2 for a Notebook Server
5. Add a self-referencing rule to allow AWS Glue components to communicate. Specifically, add or
confirm that there is a rule of Type All TCP, Protocol is TCP, Port Range includes all ports, and
whose Source is the same security group name as the Group ID.
6. Add a rule to for outbound traffic also. Either open outbound traffic to all ports, or create a self-
referencing rule of Type All TCP, Protocol is TCP, Port Range includes all ports, and whose Source
is the same security group name as the Group ID.
1. Sign in to the AWS Management Console and open the Amazon EC2 console at https://
console.aws.amazon.com/ec2/.
2. In the left navigation pane, choose Security Groups.
35
AWS Glue Developer Guide
Setting Up Encryption
3. Either choose an existing security group from the list, or Create Security Group to use with your
notebook server. The security group that is associated with your development endpoint is also used
to create your notebook server.
4. In the security group pane, navigate to the Inbound tab.
5. Add inbound rules similar to this:
The following shows an example of the inbound rules for the security group:
1. If the user of the AWS Glue console doesn't use a permissions policy that allows all AWS Glue API
operations (for example, "glue:*"), confirm that the following actions are allowed:
• "glue:GetDataCatalogEncryptionSettings"
• "glue:PutDataCatalogEncryptionSettings"
• "glue:CreateSecurityConfiguration"
• "glue:GetSecurityConfiguration"
• "glue:GetSecurityConfigurations"
• "glue:DeleteSecurityConfiguration"
2. Any client that accesses or writes to an encrypted catalog—that is, any console user, crawler, job, or
development endpoint—needs the following permissions:
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": [
"kms:GenerateDataKey",
"kms:Decrypt",
36
AWS Glue Developer Guide
Setting Up Encryption
"kms:Encrypt"
],
"Resource": "(key-arns-used-for-data-catalog)"
}
}
3. Any user or role that accesses an encrypted connection password needs the following permissions:
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": [
"kms:Decrypt"
],
"Resource": "(key-arns-used-for-password-encryption)"
}
}
4. The role of any extract, transform, and load (ETL) job that writes encrypted data to Amazon S3 needs
the following permissions:
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": [
"kms:Decrypt",
"kms:Encrypt",
"kms:GenerateDataKey"
],
"Resource": "(key-arns-used-for-s3)"
}
}
5. Any ETL job or crawler that writes encrypted Amazon CloudWatch Logs requires the following
permissions in the key policy (not IAM policy):
{
"Effect": "Allow",
"Principal": {
"Service": "logs.region.amazonaws.com"
},
"Action": [
"kms:Encrypt*",
"kms:Decrypt*",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:Describe*"
],
"Resource": "arn of key used for ETL/crawler cloudwatch encryption"
}
For more information about key policies, see Using Key Policies in AWS KMS in the AWS Key
Management Service Developer Guide.
6. Any ETL job that uses an encrypted job bookmark needs the following permissions:
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
37
AWS Glue Developer Guide
Console Workflow Overview
"Action": [
"kms:Decrypt",
"kms:Encrypt"
],
"Resource": "(key-arns-used-for-job-bookmark-encryption)"
}
}
7. On the AWS Glue console, choose Settings in the navigation pane. On the Data catalog settings page,
encrypt your Data Catalog by selecting the Metadata encryption check box. This option encrypts all
the objects in the Data Catalog with the AWS KMS key that you choose.
When encryption is enabled, the client that is accessing the Data Catalog must have AWS KMS
permissions.
8. In the navigation pane, choose Security configurations. A security configuration is a set of
security properties that can be used to configure AWS Glue processes. Then choose Add security
configuration. In the configuration, choose any of the following options:
a. Select the S3 encryption check box. For Encryption mode, choose SSE-KMS. For the AWS KMS
key, choose aws/s3 (ensure that the user has permission to use this key). This enables data written
by the job to Amazon S3 to use the AWS managed AWS Glue AWS KMS key.
b. Select the CloudWatch logs encryption check box, and choose an AWS managed AWS KMS
key (ensure that the user has permission to use this key). This enables data written by the job to
CloudWatch Logs with the AWS managed AWS Glue AWS KMS key.
c. Choose Advanced properties, and select the Job bookmark encryption check box. For the AWS
KMS key, choose aws/glue (ensure that the user has permission to use this key). This enables
encryption of job bookmarks written to Amazon S3 with the AWS Glue AWS KMS key.
9. In the navigation pane, choose Connections. Choose Add connection to create a connection to the
Java Database Connectivity (JDBC) data store that is the target of your ETL job. To enforce that Secure
Sockets Layer (SSL) encryption is used, select the Require SSL connection check box, and test your
connection.
10.In the navigation pane, choose Jobs. Choose Add job to create a job that transforms data. In the job
definition, choose the security configuration that you created.
11.On the AWS Glue console, run your job on demand. Verify that any Amazon S3 data written by the
job, the CloudWatch Logs written by the job, and the job bookmarks are all encrypted.
In the console, you can add a crawler to populate the AWS Glue Data Catalog. You can start the Add
crawler wizard from the list of tables or the list of crawlers. You choose one or more data stores for
your crawler to access. You can also create a schedule to determine the frequency of running your
crawler.
Optionally, you can provide a custom classifier that infers the schema of your data. You can create
custom classifiers using a grok pattern. However, AWS Glue provides built-in classifiers that are
automatically used by crawlers if a custom classifier does not recognize your data. When you define a
crawler, you don't have to select a classifier. For more information about classifiers in AWS Glue, see
Adding Classifiers to a Crawler (p. 127).
38
AWS Glue Developer Guide
Console Workflow Overview
Crawling some types of data stores requires a connection that provides authentication and location
information. If needed, you can create a connection that provides this required information in the AWS
Glue console.
The crawler reads your data store and creates data definitions and named tables in the AWS Glue Data
Catalog. These tables are organized into a database of your choosing. You can also populate the Data
Catalog with manually created tables. With this method, you provide the schema and other metadata
to create table definitions in the Data Catalog. Because this method can be a bit tedious and error
prone, it's often better to have a crawler create the table definitions.
For more information about populating the AWS Glue Data Catalog with table definitions, see
Defining Tables in the AWS Glue Data Catalog (p. 105).
2. Define a job that describes the transformation of data from source to target.
For more information about defining jobs in AWS Glue, see Authoring Jobs in AWS Glue (p. 160).
3. Run your job to transform your data.
You can run your job on demand, or start it based on a one of these trigger types:
• A trigger that is based on a cron schedule.
• A trigger that is event-based; for example, the successful completion of another job can start an
AWS Glue job.
• A trigger that starts a job on demand.
For more information about triggers in AWS Glue, see Triggering Jobs in AWS Glue (p. 179).
4. Monitor your scheduled crawlers and triggered jobs.
For more information about monitoring your crawlers and jobs in AWS Glue, see Running and
Monitoring AWS Glue (p. 216).
39
AWS Glue Developer Guide
Data Protection
Security is a shared responsibility between AWS and you. The shared responsibility model describes this
as security of the cloud and security in the cloud:
• Security of the cloud – AWS is responsible for protecting the infrastructure that runs AWS services in
the AWS Cloud. AWS also provides you with services that you can use securely. Third-party auditors
regularly test and verify the effectiveness of our security as part of the AWS compliance programs.
To learn about the compliance programs that apply to AWS Glue, see AWS Services in Scope by
Compliance Program.
• Security in the cloud – Your responsibility is determined by the AWS service that you use. You are also
responsible for other factors including the sensitivity of your data, your company’s requirements, and
applicable laws and regulations.
This documentation helps you understand how to apply the shared responsibility model when using AWS
Glue. The following topics show you how to configure AWS Glue to meet your security and compliance
objectives. You also learn how to use other AWS services that help you to monitor and secure your AWS
Glue resources.
Topics
• Data Protection in AWS Glue (p. 40)
• Identity and Access Management in AWS Glue (p. 49)
• Logging and Monitoring in AWS Glue (p. 100)
• Compliance Validation for AWS Glue (p. 100)
• Resilience in AWS Glue (p. 101)
• Infrastructure Security in AWS Glue (p. 101)
Topics
• Encryption at Rest (p. 40)
• Encryption in Transit (p. 46)
• Key Management (p. 46)
• Internetwork Traffic Privacy (p. 46)
• AWS Glue Dependency on Other AWS Services (p. 48)
• Development Endpoints (p. 49)
Encryption at Rest
Topics
• Encrypting Your Data Catalog (p. 41)
• Encrypting Connection Passwords (p. 42)
• Encrypting Data Written by Crawlers, Jobs, and Development Endpoints (p. 43)
40
AWS Glue Developer Guide
Encryption at Rest
AWS Glue supports data encryption at rest for Authoring Jobs in AWS Glue (p. 160) and Developing
Scripts Using Development Endpoints (p. 181). You can configure extract, transform, and load (ETL)
jobs and development endpoints to use AWS Key Management Service (AWS KMS) keys to write
encrypted data at rest. You can also encrypt the metadata stored in the AWS Glue Data Catalog (p. 7)
using keys that you manage with AWS KMS. Additionally, you can use AWS KMS keys to encrypt job
bookmarks and the logs generated by crawlers and ETL jobs.
As of September 4, 2018, AWS KMS (bring your own key and server-side encryption) for AWS Glue ETL and
the AWS Glue Data Catalog is supported.
You can encrypt metadata objects in your AWS Glue Data Catalog in addition to the data written to
Amazon Simple Storage Service (Amazon S3) and Amazon CloudWatch Logs by jobs, crawlers, and
development endpoints. You can enable encryption of the entire Data Catalog in your account. When you
create jobs, crawlers, and development endpoints in AWS Glue, you can provide encryption settings, such
as a security configuration, to configure encryption for that process.
With AWS Glue, you can encrypt data using keys that you manage with AWS Key Management Service
(AWS KMS). With encryption enabled, when you add Data Catalog objects, run crawlers, run jobs, or start
development endpoints, AWS KMS keys are used to write data at rest. In addition, you can configure
AWS Glue to only access Java Database Connectivity (JDBC) data stores through a trusted Secure Sockets
Layer (SSL) protocol.
For more information about how to set up encryption, see Setting Up Encryption in AWS Glue (p. 36).
• Databases
• Tables
• Partitions
• Table versions
• Connections
• User-defined functions
You can set this behavior using the AWS Management Console or AWS Command Line Interface (AWS
CLI).
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. Choose Settings in the navigation pane.
3. On the Data catalog settings page, select the Metadata encryption check box, and choose an AWS
KMS key.
41
AWS Glue Developer Guide
Encryption at Rest
When encryption is enabled, all future Data Catalog objects are encrypted. The default key is the AWS
Glue AWS KMS key that is created for your account by AWS. If you clear this setting, objects are no longer
encrypted when they are written to the Data Catalog. Any encrypted objects in the Data Catalog can
continue to be accessed with the key.
Important
The AWS KMS key must remain available in the AWS KMS key store for any objects that are
encrypted with it in the Data Catalog. If you remove the key, the objects can no longer be
decrypted. You might want this in some scenarios to prevent access to Data Catalog metadata.
When encryption is enabled, the client that is accessing the Data Catalog must have the following AWS
KMS permissions in its policy:
• kms:Decrypt
• kms:Encrypt
• kms:GenerateDataKey
For example, when you define a crawler or a job, the IAM role that you provide in the definition must
have these AWS KMS permissions:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"kms:Decrypt",
"kms:Encrypt",
"kms:GenerateDataKey"
],
"Resource": "ARN-of-key-used-to-encrypt-data-catalog"
}
]
}
On the AWS Glue console, you can enable this option on the Data catalog settings page:
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. Choose Settings in the navigation pane.
3. On the Data catalog settings page, select the Encrypt connection passwords check box.
42
AWS Glue Developer Guide
Encryption at Rest
For more information, see Working with Data Catalog Settings on the AWS Glue Console (p. 142).
• Attach a security configuration to an AWS Glue crawler to write encrypted Amazon CloudWatch Logs.
• Attach a security configuration to an extract, transform, and load (ETL) job to write encrypted Amazon
Simple Storage Service (Amazon S3) targets and encrypted CloudWatch Logs.
• Attach a security configuration to an ETL job to write its jobs bookmarks as encrypted Amazon S3
data.
• Attach a security configuration to a development endpoint to write encrypted Amazon S3 targets.
Important
Currently, a security configuration overrides any server-side encryption (SSE-S3) setting
that is passed as an ETL job parameter. Thus, if both a security configuration and an SSE-S3
parameter are associated with a job, the SSE-S3 parameter is ignored.
For more information about security configurations, see Working with Security Configurations on the
AWS Glue Console (p. 44).
Topics
• Setting Up AWS Glue to Use Security Configurations (p. 43)
• Creating a Route to AWS KMS for VPC Jobs and Crawlers (p. 44)
• Working with Security Configurations on the AWS Glue Console (p. 44)
1. Create or update your AWS Key Management Service (AWS KMS) keys to allow AWS KMS permissions
to the IAM roles that are passed to AWS Glue crawlers and jobs to encrypt CloudWatch Logs.
For more information, see Encrypt Log Data in CloudWatch Logs Using AWS KMS in the Amazon
CloudWatch Logs User Guide.
In the following example, "role1", "role2", and "role3" are IAM roles that are passed to
crawlers and jobs:
{
"Effect": "Allow",
"Principal": { "Service": "logs.region.amazonaws.com",
"AWS": [
"role1",
"role2",
"role3"
] },
"Action": [
"kms:Encrypt*",
43
AWS Glue Developer Guide
Encryption at Rest
"kms:Decrypt*",
"kms:ReEncrypt*",
"kms:GenerateDataKey*",
"kms:Describe*"
],
"Resource": "*"
}
job = Job(glueContext)
job.init(args['JOB_NAME'], args)
You can create an AWS KMS VPC endpoint within a VPC. Without this step, your jobs or crawlers might
fail with a kms timeout on jobs or an internal service exception on crawlers. For detailed
instructions, see Connecting to AWS KMS Through a VPC Endpoint in the AWS Key Management Service
Developer Guide.
As you follow these instructions, on the VPC console, you must do the following:
When you add a security configuration to a crawler or job that accesses JDBC data stores, AWS Glue must
have a route to the AWS KMS endpoint. You can provide the route with a network address translation
(NAT) gateway or with an AWS KMS VPC endpoint. To create a NAT gateway, see NAT Gateways in the
Amazon VPC User Guide.
To see a list of all the security configurations that you have created, open the AWS Glue console at
https://console.aws.amazon.com/glue/ and choose Security configurations in the navigation pane.
The Security configurations list displays the following properties about each configuration:
Name
The unique name you provided when you created the configuration.
44
AWS Glue Developer Guide
Encryption at Rest
S3 encryption mode
If enabled, the Amazon Simple Storage Service (Amazon S3) encryption mode such as SSE-KMS or
SSE-S3.
CloudWatch logs encryption mode
The date and time (UTC) that the configuration was created.
You can add or delete configurations in the Security configurations section on the console. To see more
details for a configuration, choose the configuration name in the list. Details include the information that
you defined when you created the configuration.
To add a security configuration using the AWS Glue console, on the Security configurations page,
choose Add security configuration. The wizard guides you through setting the required properties.
To set up encryption of data and metadata with AWS Key Management Service (AWS KMS) keys on the
AWS Glue console, add a policy to the console user. This policy must specify the allowed resources as key
ARNs that are used to encrypt Amazon S3 data stores, as in the following example:
{
"Version": "2012-10-17",
"Statement": {
"Effect": "Allow",
"Action": [
"kms:GenerateDataKey",
"kms:Decrypt",
"kms:Encrypt"],
"Resource": "arn:aws:kms:region:account-id:key/key-id"}
}
Important
When a security configuration is attached to a crawler or job, the IAM role that is passed must
have AWS KMS permissions. For more information, see Encrypting Data Written by Crawlers,
Jobs, and Development Endpoints (p. 43).
When you define a configuration, you can provide values for the following properties:
S3 encryption
When you are writing Amazon S3 data, you use either server-side encryption with Amazon S3
managed keys (SSE-S3) or server-side encryption with AWS KMS managed keys (SSE-KMS). This
field is optional. To enable access to Amazon S3, choose an AWS KMS key, or choose Enter a
key ARN and provide the Amazon Resource Name (ARN) for the key. Enter the ARN in the form
arn:aws:kms:region:account-id:key/key-id. You can also provide the ARN as a key alias,
such as arn:aws:kms:region:account-id:alias/alias-name.
CloudWatch Logs encryption
Server-side (SSE-KMS) encryption is used to encrypt CloudWatch Logs. This field is optional. To
enable it, choose an AWS KMS key, or choose Enter a key ARN and provide the ARN for the key.
45
AWS Glue Developer Guide
Encryption in Transit
Client-side (CSE-KMS) encryption is used to encrypt job bookmarks. This field is optional. The
bookmark data is encrypted before it is sent to Amazon S3 for storage. To enable it, choose an AWS
KMS key, or choose Enter a key ARN and provide the ARN for the key. Enter the ARN in the form
arn:aws:kms:region:account-id:key/key-id. You can also provide the ARN as a key alias,
such as arn:aws:kms:region:account-id:alias/alias-name.
For more information, see the following topics in the Amazon Simple Storage Service Developer Guide:
• For information about SSE-S3, see Protecting Data Using Server-Side Encryption with Amazon S3-
Managed Encryption Keys (SSE-S3).
• For information about SSE-KMS, see Protecting Data Using Server-Side Encryption with AWS KMS–
Managed Keys (SSE-KMS).
• For information about CSE-KMS, see Using an AWS KMS–Managed Customer Master Key (CMK).
Encryption in Transit
AWS provides Secure Sockets Layer (SSL) encryption for data in motion. You can configure encryption
settings for crawlers, ETL jobs, and development endpoints using security configurations in AWS Glue.
You can enable AWS Glue Data Catalog encryption via the settings for the Data Catalog.
As of September 4, 2018, AWS KMS (bring your own key and server-side encryption) for AWS Glue ETL and
the AWS Glue Data Catalog is supported.
Key Management
You can use AWS Identity and Access Management (IAM) with AWS Glue to define users, AWS resources,
groups, roles and fine-grained policies regarding access, denial, and more.
You can define the access to the metadata using both resource-based and identity-based policies,
depending on your organization’s needs. Resource-based policies list the principals that are allowed or
denied access to your resources, allowing you to set up policies such as cross-account access. Identity
policies are specifically attached to users, groups, and roles within IAM.
For a step-by-step example, see Restrict access to your AWS Glue Data Catalog with resource-level IAM
permissions and resource-based policies on the AWS Big Data Blog.
The fine-grained access portion of the policy is defined within the Resource clause. This portion defines
both the AWS Glue Data Catalog object that the action can be performed on, and what resulting objects
get returned by that operation.
A development endpoint is an environment that you can use to develop and test your AWS Glue scripts.
You can add, delete, or rotate the SSH key of a development endpoint.
As of September 4, 2018, AWS KMS (bring your own key and server-side encryption) for AWS Glue ETL and
the AWS Glue Data Catalog is supported.
46
AWS Glue Developer Guide
Internetwork Traffic Privacy
job logic, and create notifications to help you monitor your job runs. For more information, see AWS Glue
Dependency on Other AWS Services (p. 48).
The AWS Glue console connects these services into a managed application. The console performs
administrative and job development operations on your behalf. You supply credentials and other
properties to AWS Glue to access your data sources and write to your data warehouse. AWS Glue takes
care of provisioning and managing resources that are required to run your workload. When resources are
required, to reduce startup time, AWS Glue uses an instance from its warm pool of instances to run your
workload.
To start using AWS Glue, sign into the AWS Management Console. Under the Analytics category,
choose Glue. AWS Glue automatically discovers and profiles your data via the AWS Glue Data Catalog. It
recommends and generates ETL code to transform your source data into target schemas. It then runs the
ETL jobs on a fully managed, scale-out Apache Spark environment to load your data into its destination.
It also enables you to set up, orchestrate, and monitor complex data flows.
You can create jobs using table definitions in your Data Catalog. Jobs consist of scripts that contain
programming logic that performs the transformation. You use triggers to initiate jobs either on a
schedule or as a result of a specified event. You determine where your target data resides and which
source data populates your target. With your input, AWS Glue generates the code that's required to
transform your data from source to target. You can also provide scripts in the AWS Glue console or API to
process your data.
Topics
• AWS Glue Console (p. 47)
• AWS Glue Data Catalog (p. 47)
• AWS Glue Crawlers and Classifiers (p. 48)
• AWS Glue ETL Operations (p. 48)
• AWS Glue Jobs System (p. 48)
• Define AWS Glue objects such as jobs, tables, crawlers, and connections
• Schedule when crawlers run
• Define events or schedules for job triggers
• Search and filter lists of AWS Glue objects
• Edit transformation scripts AWS Glue Data Catalog
Each AWS account has one AWS Glue Data Catalog. It provides a uniform repository where disparate
systems can store and find metadata to keep track of data in data silos, and use that metadata to query
and transform the data.
AWS Identity and Access Management (IAM) policies control access to data sources managed by the AWS
Glue Data Catalog. These policies allow different groups in your enterprise to safely publish data to the
47
AWS Glue Developer Guide
AWS Glue Dependency on Other AWS Services
wider organization while protecting sensitive information. IAM policies let you clearly and consistently
define which users have access to which data, regardless of its location.
The Data Catalog also provides comprehensive audit and governance capabilities, with schema change
tracking, lineage of data, and data access controls. You can audit changes to data schemas and track
the movement of data across systems. This helps ensure that data is not inappropriately modified or
inadvertently shared.
For information about how to use the AWS Glue Data Catalog, see Populating the AWS Glue Data
Catalog (p. 103). For information about how to program using the Data Catalog API, see Catalog
API (p. 461).
For information about how to set up crawlers and classifiers, see Defining Crawlers (p. 114). For
information about how to program crawlers and classifiers using the AWS Glue API, see Crawlers and
Classifiers API (p. 506).
For more information about how to use AWS Glue ETL capabilities, see Programming ETL
Scripts (p. 296).
For more information about using the AWS Glue jobs system, see Running and Monitoring AWS
Glue (p. 216). For information about programming using the AWS Glue jobs system API, see Jobs
API (p. 534).
48
AWS Glue Developer Guide
Development Endpoints
• Amazon Simple Storage Service (Amazon S3) permissions to list buckets and objects, and to retrieve
and save scripts.
• Amazon Redshift permissions to work with clusters.
• Amazon Relational Database Service (Amazon RDS) permissions to list instances.
Development Endpoints
A development endpoint is an environment that you can use to develop and test your AWS Glue scripts.
You can use AWS Glue to create, edit, and delete development endpoints. The Dev Endpoints tab on the
AWS Glue console lists all the development endpoints that are created. You can add, delete, or rotate the
SSH key of a development endpoint. You can also create notebooks that use the development endpoint.
You provide configuration values to provision the development environments. These values tell AWS
Glue how to set up the network so that you can access the development endpoint securely, and so
that your endpoint can access your data stores. Then, you can create a notebook that connects to the
development endpoint. You use your notebook to author and test your ETL script.
Use an AWS Identity and Access Management (IAM) role with permissions similar to the IAM role that you
use to run AWS Glue ETL jobs. Use a virtual private cloud (VPC), a subnet, and a security group to create
a development endpoint that can connect to your data resources securely. You generate an SSH key pair
to connect to the development environment using SSH.
You can create development endpoints for Amazon S3 data and within a VPC that you can use to access
datasets using JDBC.
You can install an Apache Zeppelin notebook on your local machine and use it to debug and test ETL
scripts on a development endpoint. Or, you can host the Zeppelin notebook on an Amazon EC2 instance.
A notebook server is a web-based environment that you can use to run your PySpark statements.
AWS Glue tags Amazon EC2 instances with a name that is prefixed with aws-glue-dev-endpoint.
You can set up a notebook server on a development endpoint to run PySpark statements with AWS Glue
extensions. For more information about Zeppelin notebooks, see Apache Zeppelin.
Topics
• Authentication (p. 49)
• Managing Access Permissions for AWS Glue Resources (p. 51)
• Granting Cross-Account Access (p. 60)
• Specifying AWS Glue Resource ARNs (p. 64)
• AWS Glue Access Control Policy Examples (p. 68)
• AWS Glue API Permissions: Actions and Resources Reference (p. 83)
Authentication
You can access AWS as any of the following types of identities:
49
AWS Glue Developer Guide
Authentication
• AWS account root user – When you first create an AWS account, you begin with a single sign-in
identity that has complete access to all AWS services and resources in the account. This identity is
called the AWS account root user and is accessed by signing in with the email address and password
that you used to create the account. We strongly recommend that you do not use the root user for
your everyday tasks, even the administrative ones. Instead, adhere to the best practice of using the
root user only to create your first IAM user. Then securely lock away the root user credentials and use
them to perform only a few account and service management tasks.
• IAM user – An IAM user is an identity within your AWS account that has specific custom permissions
(for example, permissions to create a table in AWS Glue). You can use an IAM user name and password
to sign in to secure AWS webpages like the AWS Management Console, AWS Discussion Forums, or the
AWS Support Center.
In addition to a user name and password, you can also generate access keys for each user. You can
use these keys when you access AWS services programmatically, either through one of the several
SDKs or by using the AWS Command Line Interface (CLI). The SDK and CLI tools use the access keys
to cryptographically sign your request. If you don’t use AWS tools, you must sign the request yourself.
AWS Glue supports Signature Version 4, a protocol for authenticating inbound API requests. For more
information about authenticating requests, see Signature Version 4 Signing Process in the AWS General
Reference.
• IAM role – An IAM role is an IAM identity that you can create in your account that has specific
permissions. An IAM role is similar to an IAM user in that it is an AWS identity with permissions policies
that determine what the identity can and cannot do in AWS. However, instead of being uniquely
associated with one person, a role is intended to be assumable by anyone who needs it. Also, a role
does not have standard long-term credentials such as a password or access keys associated with it.
Instead, when you assume a role, it provides you with temporary security credentials for your role
session. IAM roles with temporary credentials are useful in the following situations:
• Federated user access – Instead of creating an IAM user, you can use existing identities from AWS
Directory Service, your enterprise user directory, or a web identity provider. These are known as
federated users. AWS assigns a role to a federated user when access is requested through an identity
provider. For more information about federated users, see Federated Users and Roles in the IAM User
Guide.
• AWS service access – A service role is an IAM role that a service assumes to perform actions in your
account on your behalf. When you set up some AWS service environments, you must define a role
for the service to assume. This service role must include all the permissions that are required for
the service to access the AWS resources that it needs. Service roles vary from service to service, but
many allow you to choose your permissions as long as you meet the documented requirements
for that service. Service roles provide access only within your account and cannot be used to grant
access to services in other accounts. You can create, modify, and delete a service role from within
IAM. For example, you can create a role that allows Amazon Redshift to access an Amazon S3 bucket
on your behalf and then load data from that bucket into an Amazon Redshift cluster. For more
information, see Creating a Role to Delegate Permissions to an AWS Service in the IAM User Guide.
• Applications running on Amazon EC2 – You can use an IAM role to manage temporary credentials
for applications that are running on an EC2 instance and making AWS CLI or AWS API requests. This
is preferable to storing access keys within the EC2 instance. To assign an AWS role to an EC2 instance
and make it available to all of its applications, you create an instance profile that is attached to
the instance. An instance profile contains the role and enables programs that are running on the
50
AWS Glue Developer Guide
Access Control Overview
EC2 instance to get temporary credentials. For more information, see Using an IAM Role to Grant
Permissions to Applications Running on Amazon EC2 Instances in the IAM User Guide.
Every AWS resource is owned by an AWS account, and permissions to create or access a resource are
governed by permissions policies. An account administrator can attach permissions policies to IAM
identities (that is, users, groups, and roles). Some services (such as AWS Glue and Amazon S3) also
support attaching permissions policies to the resources themselves.
Note
An account administrator (or administrator user) is a user who has administrative privileges. For
more information, see IAM Best Practices in the IAM User Guide.
When granting permissions, you decide who is getting the permissions, the resources they get
permissions for, and the specific actions that you want to allow on those resources.
Topics
• Using Permissions Policies to Manage Access to Resources (p. 51)
• AWS Glue Resources and Operations (p. 52)
• Understanding Resource Ownership (p. 52)
• Managing Access to Resources (p. 52)
• Specifying Policy Elements: Actions, Effects, and Principals (p. 53)
• Specifying Conditions in a Policy (p. 54)
• Identity-Based Policies (IAM Policies) for Access Control (p. 54)
• AWS Glue Resource Policies for Access Control (p. 58)
For a list showing all of the AWS Glue API operations and the resources that they apply to, see AWS Glue
API Permissions: Actions and Resources Reference (p. 83).
To learn more about IAM policy syntax and descriptions, see IAM JSON Policy Reference in the IAM User
Guide.
51
AWS Glue Developer Guide
Access Control Overview
By supporting both identity-based and resource policies, AWS Glue gives you fine-grained control over
who can access what metadata.
For more examples, see AWS Glue Resource-Based Access Control Policy Examples (p. 78).
• If you use the AWS account root user credentials of your AWS account to create a table, your AWS
account is the owner of the resource (in AWS Glue, the resource is a table).
• If you create an IAM user in your AWS account and grant permissions to create a table to that user,
the user can create a table. However, your AWS account, which the user belongs to, owns the table
resource.
• If you create an IAM role in your AWS account with permissions to create a table, anyone who can
assume the role can create a table. Your AWS account, to which the user belongs, owns the table
resource.
Policies that are attached to an IAM identity are referred to as identity-based policies (IAM policies).
Policies that are attached to a resource are referred to as resource-based policies.
Topics
• Identity-Based Policies (IAM Policies) (p. 52)
• Resource-Based Policies (p. 53)
• Attach a permissions policy to a user or a group in your account – To grant a user permissions to
create an AWS Glue resource, such as a table, you can attach a permissions policy to a user or group
that the user belongs to.
• Attach a permissions policy to a role (grant cross-account permissions) – You can attach an
identity-based permissions policy to an IAM role to grant cross-account permissions. For example,
52
AWS Glue Developer Guide
Access Control Overview
the administrator in account A can create a role to grant cross-account permissions to another AWS
account (for example, account B) or an AWS service as follows:
1. Account A administrator creates an IAM role and attaches a permissions policy to the role that
grants permissions on resources in account A.
2. Account A administrator attaches a trust policy to the role identifying account B as the principal
who can assume the role.
3. Account B administrator can then delegate permissions to assume the role to any users in account B.
Doing this allows users in account B to create or access resources in account A. The principal in the
trust policy can also be an AWS service principal if you want to grant an AWS service permissions to
assume the role.
For more information about using IAM to delegate permissions, see Access Management in the IAM
User Guide.
The following is an example identity-based policy that grants permissions for one AWS Glue action
(GetTables). The wildcard character (*) in the Resource value means that you are granting permission
to this action to obtain names and details of all the tables in a database in the Data Catalog. If the user
also has access to other catalogs through a resource policy, it is given access to these resources too.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTables",
"Effect": "Allow",
"Action": [
"glue:GetTables"
],
"Resource": "*"
}
]
}
For more information about using identity-based policies with AWS Glue, see Identity-Based Policies
(IAM Policies) for Access Control (p. 54). For more information about users, groups, roles, and
permissions, see Identities (Users, Groups, and Roles) in the IAM User Guide.
Resource-Based Policies
Other services, such as Amazon S3, also support resource-based permissions policies. For example, you
can attach a policy to an S3 bucket to manage access permissions to that bucket.
• Resource – You use an Amazon Resource Name (ARN) to identify the resource that the policy applies
to. For more information, see AWS Glue Resources and Operations (p. 52).
• Action – You use action keywords to identify resource operations that you want to allow or deny. For
example, you can use create to allow users to create a table.
53
AWS Glue Developer Guide
Access Control Overview
• Effect – You specify the effect, either allow or deny, when the user requests the specific action. If you
don't explicitly grant access to (allow) a resource, access is implicitly denied. You can also explicitly
deny access to a resource, which you might do to make sure that a user cannot access it, even if a
different policy grants access.
• Principal – In identity-based policies (IAM policies), the user that the policy is attached to is the
implicit principal. For resource-based policies, you specify the user, account, service, or other entity
that you want to receive permissions (applies to resource-based policies only). AWS Glue doesn't
support resource-based policies.
To learn more about IAM policy syntax and descriptions, see IAM JSON Policy Reference in the IAM User
Guide.
For a list showing all of the AWS Glue API operations and the resources that they apply to, see AWS Glue
API Permissions: Actions and Resources Reference (p. 83).
To express conditions, you use predefined condition keys. There are AWS-wide condition keys and AWS
Glue–specific keys that you can use as appropriate. For a complete list of AWS-wide keys, see Available
Keys for Conditions in the IAM User Guide.
AWS Glue supports identity-based policies (IAM policies) for all AWS Glue operations. By attaching a
policy to a user or a group in your account, you can grant them permissions to create, access, or modify
an AWS Glue resource, such as a table in the AWS Glue Data Catalog.
By attaching a policy to an IAM role, you can grant cross-account access permissions to IAM identities in
other AWS accounts. For more information, see Granting Cross-Account Access (p. 60).
The following is an example identity-based policy that grants permissions for AWS Glue actions
(glue:GetTable, GetTables, GetDatabase, and GetDatabases). The wildcard character (*) in the
Resource value means that you are granting permission to these actions to obtain names and details of
all the tables and databases in the Data Catalog. If the user also has access to other catalogs through a
resource policy, then it is given access to these resources too.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTables",
"Effect": "Allow",
"Action": [
"glue:GetTable",
"glue:GetTables",
"glue:GetDatabase",
"glue:GetDataBases"
],
"Resource": "*"
54
AWS Glue Developer Guide
Access Control Overview
}
]
}
Here is another example, targeting the us-west-2 Region and using a placeholder for the specific AWS
account number.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTablesActionOnBooks",
"Effect": "Allow",
"Action": [
"glue:GetTable",
"glue:GetTables"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:database/db1",
"arn:aws:glue:us-west-2:123456789012:table/db1/books"
]
}
]
}
This policy grants read-only permission to a table named books in the database named db1. Notice
that to grant Get permission to a table that permission to the catalog and database resources is also
required.
To deny access to a table, requires that you create a policy to deny a user access to the table, or its
parent database or catalog. This allows you to easily deny access to a specific resource that cannot
be circumvented with a subsequent allow permission. For example, if you deny access to table books
in database db1, then if you grant access to database db1, access to table books is still denied.
The following is an example identity-based policy that denies permissions for AWS Glue actions
(glue:GetTables and GetTable) to database db1 and all of the tables within it.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DenyGetTablesToDb1",
"Effect": "Deny",
"Action": [
"glue:GetTables",
"glue:GetTable"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:database/db1"
]
}
]
}
For more policy examples, see Identity-Based Policy Examples (p. 68).
55
AWS Glue Developer Guide
Access Control Overview
You can use the Condition element along with the glue:resourceTag context key in an IAM user
policy to allow or deny access based on keys associated with crawlers, jobs, triggers, and development
endpoints. For example:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "glue:*",
"Resource": "*",
"Condition": {
"StringEquals": {
"glue:resourceTag/Name": "Tom"
}
}
}
]
}
Important
The condition context keys apply only to those AWS Glue API actions on crawlers, jobs, triggers,
and development endpoints. For more information about which APIs are affected, see AWS Glue
API Permissions: Actions and Resources Reference (p. 83).
For information about how to control access using tags, see AWS Glue Identity-Based (IAM) Access
Control Policy with Tags Examples (p. 73).
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:GetClassifier*",
"glue:GetJobRun*"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"glue:Get*"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:catalog",
"arn:aws:glue:us-east-1:123456789012:database/default",
"arn:aws:glue:us-east-1:123456789012:table/default/e*1*",
"arn:aws:glue:us-east-1:123456789012:connection/connection2"
]
}
]
}
56
AWS Glue Developer Guide
Access Control Overview
For a list of AWS Glue objects that allow ARNs, see Resource ARNs (p. 64).
For more information about the permissions that users require to view and work with the AWS Glue
console, see Step 3: Attach a Policy to IAM Users That Access AWS Glue (p. 15).
If you create an IAM policy that is more restrictive than the minimum required permissions, the console
won't function as intended for users with that IAM policy. To ensure that those users can still use the
AWS Glue console, also attach the AWSGlueConsoleFullAccess managed policy to the user, as
described in AWS Managed (Predefined) Policies for AWS Glue (p. 57).
You don't need to allow minimum console permissions for users that are making calls only to the AWS
CLI or the AWS Glue API.
The following AWS managed policies, which you can attach to users in your account, are specific to AWS
Glue and are grouped by use case scenario:
• AWSGlueConsoleFullAccess – Grants full access to AWS Glue resources when using the AWS
Management Console. If you follow the naming convention for resources specified in this policy, users
have full console capabilities. This policy is typically attached to users of the AWS Glue console.
• AWSGlueServiceRole – Grants access to resources that various AWS Glue processes require to run on
your behalf. These resources include AWS Glue, Amazon S3, IAM, CloudWatch Logs, and Amazon EC2.
If you follow the naming convention for resources specified in this policy, AWS Glue processes have the
required permissions. This policy is typically attached to roles specified when defining crawlers, jobs,
and development endpoints.
• AWSGlueServiceNotebookRole – Grants access to resources required when creating a notebook
server. These resources include AWS Glue, Amazon S3, and Amazon EC2. If you follow the naming
convention for resources specified in this policy, AWS Glue processes have the required permissions.
This policy is typically attached to roles specified when creating a notebook server on a development
endpoint.
• AWSGlueConsoleSageMakerNotebookFullAccess – Grants full access to AWS Glue and Amazon
SageMaker resources when using the AWS Management Console. If you follow the naming convention
for resources specified in this policy, users have full console capabilities. This policy is typically
attached to users of the AWS Glue console who manage Amazon SageMaker notebooks.
57
AWS Glue Developer Guide
Access Control Overview
Note
You can review these permissions policies by signing in to the IAM console and searching for
specific policies there.
You can also create your own custom IAM policies to allow permissions for AWS Glue actions and
resources. You can attach these custom policies to the IAM users or groups that require those
permissions.
An AWS Glue resource policy can only be used to manage permissions for Data Catalog resources. You
can't attach it to any other AWS Glue resources such as jobs, triggers, development endpoints, crawlers,
or classifiers.
A resource policy is attached to a catalog, which is a virtual container for all the kinds of Data Catalog
resources mentioned previously. Each AWS account owns a single catalog in an AWS Region whose
catalog ID is the same as the AWS account ID. A catalog cannot be deleted or modified.
A resource policy is evaluated for all API calls to the catalog where the caller principal is included in the
"Principal" block of the policy document.
Note
Currently, only one resource policy is allowed per catalog, and its size is limited to 10 KB.
You use a policy document written in JSON format to create or modify a resource policy. The policy
syntax is the same as for an IAM policy (see IAM JSON Policy Reference), with the following exceptions:
*arn:aws:glue:%s:%s:(\*|[a-zA-Z\*]+\/?.*)
As an example, suppose that the following policy is attached to the catalog in Account A. It grants to the
IAM identity dev in Account A permission to create any table in database db1 in Account A. It also grants
the same permission to the root user in Account B.
{
"Version": "2012-10-17",
"Statement": [
58
AWS Glue Developer Guide
Access Control Overview
{
"Effect": "Allow",
"Action": [
"glue:CreateTable"
],
"Principal": {"AWS": [
"arn:aws:iam::account-A-id:user/dev",
"arn:aws:iam::account-B-id:root"
]},
"Resource": [
"arn:aws:glue:us-east-1:account-A-id:table/db1/*",
"arn:aws:glue:us-east-1:account-A-id:database/db1",
"arn:aws:glue:us-east-1:account-A-id:catalog"
]
}
]
}
The following are some examples of resource policy documents that are not valid.
For example, a policy is not valid if it specifies a user that does not exist in the account of the catalog to
which it is attached.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:CreateTable"
],
"Principal": {"AWS": [
"arn:aws:iam::account-A-id:user/(non-existent-user)"
]},
"Resource": [
"arn:aws:glue:us-east-1:account-A-id:table/db1/tbl1",
"arn:aws:glue:us-east-1:account-A-id:database/db1",
"arn:aws:glue:us-east-1:account-A-id:catalog"
]
}
]
}
A policy is not valid if it contains a resource ARN for a resource in a different account than the catalog to
which it is attached. In the following example, this is an incorrect policy if attached to account-A.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:CreateTable"
],
"Principal": {"AWS": [
"arn:aws:iam::account-A-id:user/dev"
]},
"Resource": [
"arn:aws:glue:us-east-1:account-B-id:table/db1/tbl1",
"arn:aws:glue:us-east-1:account-B-id:database/db1",
"arn:aws:glue:us-east-1:account-B-id:catalog"
]
}
59
AWS Glue Developer Guide
Cross-Account Access
]
}
A policy is not valid if it contains a resource ARN for a resource that is not an AWS Glue resource (in this
case, an Amazon S3 bucket).
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:CreateTable"
],
"Principal": {"AWS": [
"arn:aws:iam::account-A-id:user/dev"
]},
"Resource": [
"arn:aws:glue:us-east-1:account-A-id:table/db1/tbl1",
"arn:aws:glue:us-east-1:account-A-id:database/db1",
"arn:aws:glue:us-east-1:account-A-id:catalog",
"arn:aws:s3:::bucket/my-bucket"
]
}
]
}
You can also use the AWS Glue console to view and edit a resource policy. For more information, see
Working with Data Catalog Settings on the AWS Glue Console (p. 142).
1. An administrator (or other authorized identity) in Account A attaches a resource policy to the Data
Catalog in Account A. This policy grants Account B specific cross-account permissions to perform
operations on a resource in Account A's catalog.
2. An administrator in Account B attaches an IAM policy to a user or other IAM identity in Account B
that delegates the permissions received from Account A.
3. The user or other identity in Account B now has access to the specified resource in Account A.
The user needs permission from both the resource owner (Account A) and their parent account
(Account B) to be able to access the resource.
60
AWS Glue Developer Guide
Cross-Account Access
1. An administrator (or other authorized identity) in the account that owns the resource (Account A)
creates an IAM role.
2. The administrator in Account A attaches a policy to the role that grants cross-account permissions
for access to the resource in question.
3. The administrator in Account A attaches a trust policy to the role that identifies an IAM identity in a
different account (Account B) as the principal who can assume the role.
The principal in the trust policy can also be an AWS service principal if you want to grant an AWS
service permission to assume the role.
4. An administrator in Account B now delegates permissions to one or more IAM identities in Account B
so that they can assume that role. Doing so gives those identities in Account B access to the resource
in account A.
For more information about using IAM to delegate permissions, see Access Management in the IAM
User Guide. For more information about users, groups, roles, and permissions, see Identities (Users,
Groups, and Roles) in the IAM User Guide.
For a comparison of these two approaches, see How IAM Roles Differ from Resource-based Policies in the
IAM User Guide. AWS Glue supports both options, with the restriction that a resource policy can grant
access only to Data Catalog resources.
For example, to give user Bob in Account B access to database db1 in Account A, attach the following
resource policy to the catalog in Account A.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:GetDatabase"
],
"Principal": {"AWS": [
"arn:aws:iam::account-B-id:user/Bob"
]},
"Resource": [
"arn:aws:glue:us-east-1:account-A-id:catalog",
"arn:aws:glue:us-east-1:account-A-id:database/db1"
]
}
]
}
In addition, Account B would have to attach the following IAM policy to Bob before he would actually get
access to db1 in Account A.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:GetDatabase"
],
"Resource": [
"arn:aws:glue:us-east-1:account-A-id:catalog",
"arn:aws:glue:us-east-1:account-A-id:database/db1"
]
61
AWS Glue Developer Guide
Cross-Account Access
}
]
}
If no CatalogId value is provided, AWS Glue uses the caller's own account ID by default, and the call is
not cross-account.
If no catalog ID value is provided, AWS Glue uses the caller's own account ID by default, and the call is
not cross-account.
For PySpark APIs that support catalog_id, see GlueContext Class (p. 352). For Scala APIs that support
catalogId, see AWS Glue Scala GlueContext APIs (p. 412).
The following example shows the permissions required by the grantee to run an ETL job. In this example,
grantee-account-id is the catalog-id of the client running the job and grantor-account-id
is the owner of the resource. This example grants permission to all catalog resources in the grantor's
account. To limit the scope of resources granted, you can provide specific ARNs for the catalog, database,
table, and connection.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:GetConnection",
"glue:GetDatabase",
"glue:GetTable",
"glue:GetPartition"
],
"Principal": {"AWS": ["arn:aws:iam:grantee-account-id:root"]},
"Resource": [
"arn:aws:glue:us-east-1:grantor-account-id:*"
]
}
]
}
Note
If a table in the grantor's account points to an Amazon S3 location that is also in the grantor's
account, the IAM role used to run an ETL job in the grantee's account must have permission to
list and get objects from the grantor's account.
Given that the client in Account A already has permission to create and run ETL jobs, the following are
the basic steps to set up an ETL job for cross-account access:
1. Allow cross-account data access (skip this step if Amazon S3 cross-account access is already set up).
62
AWS Glue Developer Guide
Cross-Account Access
a. Update the Amazon S3 bucket policy in Account B to allow cross-account access from Account
A.
b. Update the IAM policy in Account A to allow access to the bucket in Account B.
2. Allow cross-account Data Catalog access.
a. Create or update the resource policy attached to the Data Catalog in Account B to allow access
from Account A.
b. Update the IAM policy in Account A to allow access to the Data Catalog in Account B.
• If you use your AWS account root user credentials to create a table in your Data Catalog, your AWS
account is the owner of the resource.
• If you create an IAM user in your AWS account and grant permissions to that user to create a table,
every table that the user creates is owned by your AWS account, to which the user belongs.
• If you create an IAM role in your AWS account with permissions to create a table, anyone who can
assume the role can create a table. But again, your AWS account owns the table resources that are
created using that role.
For each AWS Glue resource, the service defines a set of API operations that apply to it. To grant
permissions for these API operations, AWS Glue defines a set of actions that you can specify in a policy.
Some API operations can require permissions for more than one action in order to perform the API
operation.
Storage costs and other costs that are directly associated with the new resource are billed to Account
B, the resource owner. The cost of requests from the user who created the resource are billed to the
requester's account, Account A.
For more information about AWS Glue billing and pricing, see How AWS Pricing Works.
• Cross-account access to AWS Glue is not allowed if the resource owner account has not migrated
the Amazon Athena data catalog to AWS Glue. You can find the current migration status using the
GetCatalogImportStatus (get_catalog_import_status) (p. 506). For more details on how to migrate
an Athena catalog to AWS Glue, see Upgrading to the AWS Glue Data Catalog Step-by-Step in the
Amazon Athena User Guide.
• Cross-account access is only supported for Data Catalog resources, including databases, tables, user-
defined functions, and connections.
63
AWS Glue Developer Guide
Resource ARNs
• Cross-account access to the Data Catalog is not supported when using an AWS Glue crawler, or
Amazon Athena.
Topics
• Data Catalog ARNs (p. 64)
• ARNs for Non-Catalog Objects (p. 66)
• Access Control for AWS Glue Non-Catalog Singular API Operations (p. 66)
• Access Control for AWS Glue Non-Catalog API Operations That Retrieve Multiple Items (p. 67)
• Access Control for AWS Glue Non-Catalog Batch Get API Operations (p. 67)
arn:aws:glue:region:account-id:catalog
Each AWS account has a single Data Catalog in an AWS Region with the 12-digit account ID as the
catalog ID. Resources have unique ARNs associated with them, as shown in the following table.
Catalog arn:aws:glue:region:account-id:catalog
64
AWS Glue Developer Guide
Resource ARNs
To enable fine-grained access control, you can use these ARNs in your IAM policies and resource policies
to grant and deny access to specific resources. Wildcards are allowed in the policies. For example, the
following ARN matches all tables in database default.
arn:aws:glue:us-east-1:123456789012:table/default/*
Important
All operations performed on a Data Catalog resource require permission on the resource
and all the ancestors of that resource. For example, to create a partition for a table requires
permission on the table, database, and catalog where the table is located. The following
example shows the permission required to create partitions on table PrivateTable in
database PrivateDatabase in the Data Catalog.
{
"Sid": "GrantCreatePartitions",
"Effect": "Allow",
"Action": [
"glue:BatchCreatePartitions"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:table/PrivateDatabase/PrivateTable",
"arn:aws:glue:us-east-1:123456789012:database/PrivateDatabase",
"arn:aws:glue:us-east-1:123456789012:catalog"
]
}
In addition to permission on the resource and all its ancestors, all delete operations require
permission on all children of that resource. For example, deleting a database requires permission
on all the tables and user-defined functions in the database, in addition to the database and the
catalog where the database is located. The following example shows the permission required to
delete database PrivateDatabase in the Data Catalog.
{
"Sid": "GrantDeleteDatabase",
"Effect": "Allow",
"Action": [
"glue:DeleteDatabase"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:table/PrivateDatabase/*",
"arn:aws:glue:us-east-1:123456789012:userDefinedFunction/PrivateDatabase/*",
"arn:aws:glue:us-east-1:123456789012:database/PrivateDatabase",
"arn:aws:glue:us-east-1:123456789012:catalog"
]
}
65
AWS Glue Developer Guide
Resource ARNs
Crawler arn:aws:glue:region:account-id:crawler/crawler-name
Job arn:aws:glue:region:account-id:job/job-name
Trigger arn:aws:glue:region:account-id:trigger/trigger-name
Suppose that you want to allow a user to call the GetDevEndpoint operation. The following policy
grants the minimum necessary permissions to an endpoint named myDevEndpoint-1.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Minimum permissions",
"Effect": "Allow",
"Action": "glue:GetDevEndpoint",
"Resource": "arn:aws:glue:us-east-1:123456789012:devEndpoint/myDevEndpoint-1"
}
]
}
The following policy allows UpdateDevEndpoint access to resources that match myDevEndpoint-
with a wildcard (*).
{
"Version": "2012-10-17",
"Statement": [
{
66
AWS Glue Developer Guide
Resource ARNs
You can combine the two policies as in the following example. You might see
EntityNotFoundException for any development endpoint whose name begins with A. However, an
access denied error is returned when you try to access other development endpoints.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Combined permissions",
"Effect": "Allow",
"Action": [
"glue:UpdateDevEndpoint",
"glue:GetDevEndpoint"
],
"Resource": "arn:aws:glue:us-east-1:123456789012:devEndpoint/A*"
}
]
}
For example, to include GetDevEndpoints in the policy, the resource must be scoped to the wildcard
(*). The singular operations (GetDevEndpoint, CreateDevEndpoint, and DeleteDevendpoint) are
also scoped to all (*) resources in the example.
{
"Sid": "Plural API included",
"Effect": "Allow",
"Action": [
"glue:GetDevEndpoints",
"glue:GetDevEndpoint",
"glue:CreateDevEndpoint",
"glue:UpdateDevEndpoint"
],
"Resource": [
"*"
]
}
67
AWS Glue Developer Guide
Policy Examples
{
"Sid": "BatchGet API included",
"Effect": "Allow",
"Action": [
"glue:BatchGetDevEndpoints"
],
"Resource": [
"arn:aws:glue:us-east-1:123456789012:devEndpoint/de1"
]
}
With this policy, you can successfully access the development endpoint named de1. However, if you try
to access the development endpoint named de2, an error is returned.
Important
For alternative approaches to setting up IAM policies, such as using List and BatchGet
API operations, see AWS Glue Identity-Based (IAM) Access Control Policy with Tags
Examples (p. 73).
Topics
• AWS Glue Identity-Based (IAM) Access Control Policy Examples (p. 68)
• AWS Glue Identity-Based (IAM) Access Control Policy with Tags Examples (p. 73)
• AWS Glue Resource-Based Access Control Policy Examples (p. 78)
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTablesActionOnBooks",
"Effect": "Allow",
68
AWS Glue Developer Guide
Policy Examples
"Action": [
"glue:GetTables",
"glue:GetTable"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:database/db1",
"arn:aws:glue:us-west-2:123456789012:table/db1/books"
]
}
]
}
This policy grants read-only permission to a table named books in the database named db1. Notice
that to grant Get permission to a table that permission to the catalog and database resources is also
required.
The following policy grants the minimum necessary permissions to create table tb1 in database db1:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"glue:CreateTable"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:table/db1/tbl1",
"arn:aws:glue:us-west-2:123456789012:database/db1",
"arn:aws:glue:us-west-2:123456789012:catalog"
]
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTablesExample",
"Effect": "Allow",
"Action": [
"glue:GetTables"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:database/db1",
"arn:aws:glue:us-west-2:123456789012:table/db1/store_sales",
"arn:aws:glue:us-west-2:123456789012:table/db1/stores"
]
}
]
}
69
AWS Glue Developer Guide
Policy Examples
You can simplify the preceding policy by using store* to match any table names that start with store.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTablesExample2",
"Effect": "Allow",
"Action": [
"glue:GetTables"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:database/db1",
"arn:aws:glue:us-west-2:123456789012:table/db1/store*"
]
}
]
}
Similarly, using /db1/* to match all tables in db1, the following policy grants GetTables access to all
the tables in db1.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTablesReturnAll",
"Effect": "Allow",
"Action": [
"glue:GetTables"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:database/db1",
"arn:aws:glue:us-west-2:123456789012:table/db1/*"
]
}
]
}
If no table ARN is provided, a call to GetTables succeeds, but it returns an empty list.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTablesEmptyResults",
"Effect": "Allow",
"Action": [
"glue:GetTables"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:database/db1"
]
}
]
}
If the database ARN is missing in the policy, a call to GetTables fails with an
AccessDeniedException.
70
AWS Glue Developer Guide
Policy Examples
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "GetTablesAccessDeny",
"Effect": "Allow",
"Action": [
"glue:GetTables"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:table/db1/*"
]
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "FullAccessOnTable",
"Effect": "Allow",
"Action": [
"glue:CreateTable",
"glue:GetTable",
"glue:GetTables",
"glue:UpdateTable",
"glue:DeleteTable",
"glue:BatchDeleteTable",
"glue:GetTableVersion",
"glue:GetTableVersions",
"glue:DeleteTableVersion",
"glue:BatchDeleteTableVersion",
"glue:CreatePartition",
"glue:BatchCreatePartition",
"glue:GetPartition",
"glue:GetPartitions",
"glue:BatchGetPartition",
"glue:UpdatePartition",
"glue:DeletePartition",
"glue:BatchDeletePartition"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:database/db1",
"arn:aws:glue:us-west-2:123456789012:table/db1/books"
]
}
]
}
{
"Version": "2012-10-17",
"Statement": [
71
AWS Glue Developer Guide
Policy Examples
{
"Sid": "FullAccessOnTable",
"Effect": "Allow",
"Action": [
"glue:*Table*",
"glue:*Partition*"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:database/db1",
"arn:aws:glue:us-west-2:123456789012:table/db1/books"
]
}
]
}
Notice that the minimum granularity of fine-grained access control is at the table level. This means that
you can't grant a user access to some partitions in a table but not others, or to some table columns but
not to others. A user either has access to all of a table, or to none of it.
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "DevAndProdFullAccess",
"Effect": "Allow",
"Action": [
"glue:*Database*",
"glue:*Table*",
"glue:*Partition*",
"glue:*UserDefinedFunction*",
"glue:*Connection*"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:catalog",
"arn:aws:glue:us-west-2:123456789012:database/dev-*",
"arn:aws:glue:us-west-2:123456789012:database/prod-*",
"arn:aws:glue:us-west-2:123456789012:table/dev-*/*",
"arn:aws:glue:us-west-2:123456789012:table/*/dev-*",
"arn:aws:glue:us-west-2:123456789012:table/prod-*/*",
"arn:aws:glue:us-west-2:123456789012:table/*/prod-*",
"arn:aws:glue:us-west-2:123456789012:userDefinedFunction/dev-*/*",
"arn:aws:glue:us-west-2:123456789012:userDefinedFunction/*/dev-*",
"arn:aws:glue:us-west-2:123456789012:userDefinedFunction/prod-*/*",
"arn:aws:glue:us-west-2:123456789012:userDefinedFunction/*/prod-*",
"arn:aws:glue:us-west-2:123456789012:connection/dev-*",
"arn:aws:glue:us-west-2:123456789012:connection/prod-*"
]
},
{
"Sid": "ProdWriteDeny",
"Effect": "Deny",
"Action": [
"glue:*Create*",
"glue:*Update*",
72
AWS Glue Developer Guide
Policy Examples
"glue:*Delete*"
],
"Resource": [
"arn:aws:glue:us-west-2:123456789012:database/prod-*",
"arn:aws:glue:us-west-2:123456789012:table/prod-*/*",
"arn:aws:glue:us-west-2:123456789012:table/*/prod-*",
"arn:aws:glue:us-west-2:123456789012:userDefinedFunction/prod-*/*",
"arn:aws:glue:us-west-2:123456789012:userDefinedFunction/*/prod-*",
"arn:aws:glue:us-west-2:123456789012:connection/prod-*"
]
}
]
}
The second statement in the preceding policy uses explicit deny. You can use explicit deny to overwrite
any allow permissions that are granted to the principal. This lets you lock down access to critical
resources and prevent another policy from accidentally granting access to them.
In the preceding example, even though the first statement grants full access to prod- resources, the
second statement explicitly revokes write access to them, leaving only read access to prod- resources.
You can control access to crawlers, jobs, triggers, and development endpoints by attaching tags and
specifying resourceTag conditions in IAM policies.
73
AWS Glue Developer Guide
Policy Examples
The AWS Glue administrator attached a tag value Tom (glue:resourceTag/Name": "Tom") to trigger
t2. The AWS Glue administrator also gave Tom an IAM policy with a condition statement based on the
tag. As a result, Tom can only use an AWS Glue operation that acts on resources with the tag value Tom.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "glue:*",
"Resource": "*",
"Condition": {
"StringEquals": {
"glue:resourceTag/Name": "Tom"
}
}
}
]
}
When Tom tries to access the trigger t1, he receives an access denied message. Meanwhile, he can
successfully retrieve trigger t2.
Tom can't use the plural GetTriggers API to list triggers because this API operation doesn't support
filtering on tags.
To give Tom access to GetTriggers, the AWS Glue administrator creates a policy that splits the
permissions into two sections. One section allows Tom access to all triggers with the GetTriggers API
operation. The second section allows Tom access to API operations that are tagged with the value Tom.
With this policy, Tom is allowed both GetTriggers and GetTrigger access to trigger t2.
{
"Version": "2012-10-17",
"Statement": [
74
AWS Glue Developer Guide
Policy Examples
{
"Effect": "Allow",
"Action": "glue:GetTriggers",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": "glue:*",
"Resource": "*",
"Condition": {
"StringEquals": {
"glue:resourceTag/Name": "Tom"
}
}
}
]
}
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "glue:*",
"Resource": "*"
},
{
"Effect": "Deny",
"Action": [
"glue:*"
],
"Resource": [
"*"
],
"Condition": {
"StringEquals": {
"glue:resourceTag/Name": "Tom"
}
}
}
]
}
Using the same triggers as the previous example, Sam can access trigger t1, but not trigger t2. The
following example shows the results when Sam tries to access t1 and t2.
75
AWS Glue Developer Guide
Policy Examples
{
"JobName": "j1"
}
],
"Schedule": "cron(0 0/1 * * ? *)"
}
}
Important
An explicit denial policy does not work for plural APIs. Even with the attachment of tag
value Tom to trigger t2, Sam can still call GetTriggers to view trigger t2. Because of this,
the administrator might not want to allow access to the GetTriggers API operations. The
following example shows the results when Sam runs the GetTriggers API.
Example Access Control Using Tags with List and Batch API Operations
A third approach to writing a resource policy is to allow access to resources using a List API operation
to list out resources for a tag value. Then, use the corresponding Batch API operation to allow access to
details of specific resources. With this approach, the administrator doesn't need to allow access to the
plural GetCrawlers, GetDevEndpoints, GetJobs, or GetTriggers API operations. Instead, you can
allow the ability to list the resources with the following API operations:
• ListCrawlers
• ListDevEndpoints
• ListJobs
• ListTriggers
76
AWS Glue Developer Guide
Policy Examples
And, you can allow the ability to get details about individual resources with the following API operations:
• BatchGetCrawlers
• BatchGetDevEndpoints
• BatchGetJobs
• BatchGetTriggers
For example, when calling the ListCrawlers operation, provide a tag value to match the user name.
Then the result is a list of crawlers that match the provided tag values. Provide the list of names to the
BatchGetCrawlers to get details about each crawler with the given tag.
For example, if Tom should only be able to retrieve details of triggers that are tagged with Tom, the
administrator can add tags to triggers for Tom, deny access to the GetTriggers API operation to all
users and allow access to all users to ListTriggers and BatchGetTriggers. The following is the
resource policy that the AWS Glue administrator grants to Tom. In the first section of the policy, AWS
Glue API operations are denied for GetTriggers. In the second section of the policy, ListTriggers
is allowed for all resources. However, in the third section, those resources tagged with Tom are allowed
access with the BatchGetTriggers access.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Deny",
"Action": "glue:GetTriggers",
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"glue:ListTriggers"
],
"Resource": [
"*"
]
},
{
"Effect": "Allow",
"Action": [
"glue:BatchGetTriggers"
],
"Resource": [
"*"
],
"Condition": {
"StringEquals": {
77
AWS Glue Developer Guide
Policy Examples
"glue:resourceTag/Name": "Tom"
}
}
}
]
}
Using the same triggers as the previous example, Tom can access trigger t2, but not trigger t1. The
following example shows the results when Tom tries to access t1 and t2 with BatchGetTriggers.
The following example shows the results when Tom tries to access both trigger t2 and trigger t3 (which
does not exist) in the same BatchGetTriggers call. Notice that because Tom has access to trigger t2
and it exists, only t2 is returned. Although Tom is allowed to access trigger t3, trigger t3 does not exist,
so t3 is returned in the response in a list of "TriggersNotFound": [].
78
AWS Glue Developer Guide
Policy Examples
Note
Both IAM policies and an AWS Glue resource policy take a few seconds to propagate. After you
attach a new policy, you might notice that the old policy is still in effect until the new policy has
propagated through the system.
The following examples use the AWS Command Line Interface (AWS CLI) to interact with AWS Glue
service APIs. You can perform the same operations on the AWS Glue console or using one of the AWS
SDKs.
1. Install the AWS CLI by following the instructions in Installing the AWS Command Line Interface in
the AWS Command Line Interface User Guide.
2. Configure the AWS CLI by following the instructions in Configuration and Credential Files. Create an
admin profile using your AWS account administrator credentials. Configure the default AWS Region
to us-west-2 (or a Region that you use), and set the default output format to JSON.
3. Test access to the AWS Glue API by running the following command (replacing Alice with a real
IAM user or role in your account).
4. Configure a user profile for each IAM user in the accounts that you use for testing your resource
policy and cross-account access.
To do this, the administrator user runs the following AWS CLI command.
79
AWS Glue Developer Guide
Policy Examples
]
},
"Effect": "Allow",
"Action": [
"glue:*"
],
"Resource": [
"arn:aws:glue:us-west-2:account-A-id:*"
]
}
]
}'
Instead of entering the JSON policy document as a part of your AWS CLI command, you can save a
policy document in a file and reference the file path in the AWS CLI command, prefixed by file://. The
following is an example of how you might do that.
$ echo '{
"Version": "2012-10-17",
"Statement": [
{
"Principal": {
"AWS": [
"arn:aws:iam::account-A-id:user/Alice"
]
},
"Effect": "Allow",
"Action": [
"glue:*"
],
"Resource": [
"arn:aws:glue:us-west-2:account-A-id:*"
]
}
]
}' > /temp/policy.json
After this resource policy has propagated, Alice can access all AWS Glue resources in Account A, as
follows.
$ aws glue get-table --profile alice --region us-west-2 --database-name "default" --table-
name "tbl1"}
In response to Alice's get-table call, the AWS Glue service returns the following.
{
"Table": {
"Name": "tbl1",
"PartitionKeys": [],
"StorageDescriptor": {
......
},
80
AWS Glue Developer Guide
Policy Examples
......
}
}
1. Verify that Account A has migrated its Amazon Athena data catalog to AWS Glue.
Cross-account access to AWS Glue is not allowed if the resource-owner account has not migrated its
Athena data catalog to AWS Glue. For more details on how to migrate the Athena catalog to AWS
Glue, see Upgrading to the AWS Glue Data Catalog Step-by-Step in the Amazon Athena User Guide.
# Verify that the value "ImportCompleted" is true. This value is region specific.
$ aws glue get-catalog-import-status --profile admin1 --region us-west-2
{
"ImportStatus": {
"ImportCompleted": true,
"ImportTime": 1502512345.0,
"ImportedBy": "StatusSetByDefault"
}
}
81
AWS Glue Developer Guide
Policy Examples
"Resource": [
"arn:aws:glue:us-west-2:account-A-id:*"
]
}
]
}'
# This call fails with access denied, because Bob has only been granted read access.
$ aws glue create-database --profile bob --region us-west-2 --catalog-id account-A-id
--database-input '{
"Name": "new_database2",
"Description": "A new database created by Bob",
"LocationUri": "s3://my-bucket2"
}'
In step 2, the administrator in Account A grants permission to the root user of Account B. The root user
can then delegate the permissions it owns to all IAM principals (users, roles, groups, and so forth) by
attaching IAM policies to them. Because an admin user already has a full-access IAM policy attached, an
administrator automatically owns the permissions granted to the root user, and also the permission to
delegate permissions to other IAM users in the account.
Alternatively, in step 2, you could grant permission to the Amazon Resource Name (ARN) of user Bob
directly. This restricts the cross-account access permission to Bob alone. However, step 3 is still required
for Bob to actually gain the cross-account access. For cross-account access, both the resource policy
in the resource account and an IAM policy in the user's account are required for access to work. This is
different from the same-account access in Example 1, where either the resource policy or the IAM policy
can grant access without needing the other.
82
AWS Glue Developer Guide
API Permissions Reference
Actions on some AWS Glue resources require that ancestor and child resource ARNs are also included in
the policy's Resource field. For more information, see Data Catalog ARNs (p. 64).
Generally, you can replace ARN segments with wildcards. For more information, see IAM JSON Policy
Elements in the IAM User Guide.
Condition keys for IAM policies are listed by API operation. You can use AWS-wide condition keys in your
AWS Glue policies to express conditions. For a complete list of AWS-wide keys, see AWS Global Condition
Keys in the IAM User Guide.
Note
To specify an action, use the glue: prefix followed by the API operation name (for example,
glue:GetTable).
Action(s): glue:BatchCreatePartition
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:BatchDeleteConnection
Resource:
arn:aws:glue:region:account-id:connection/connection-name
arn:aws:glue:region:account-id:catalog
Note
All the connection deletions to be performed by the call must be authorized by IAM. If any
of these deletions is not authorized, the call fails and no connections are deleted.
BatchDeletePartition (batch_delete_partition) (p. 488)
Action(s): glue:BatchDeletePartition
Resource:
83
AWS Glue Developer Guide
API Permissions Reference
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Note
All the partition deletions to be performed by the call must be authorized by IAM. If any of
these deletions is not authorized, the call fails and no partitions are deleted.
BatchDeleteTable (batch_delete_table) (p. 476)
Action(s): glue:BatchDeleteTable
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Note
All the table deletions to be performed by the call must be authorized by IAM. If any of
these deletions is not authorized, the call fails and no tables are deleted.
BatchDeleteTableVersion (batch_delete_table_version) (p. 480)
Action(s): glue:BatchDeletetTableVersion
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:BatchGetCrawlers
Resource:
arn:aws:glue:region:account-id:crawler/crawler-name
Action(s): glue:BatchGetDevEndpoints
Resource:
arn:aws:glue:region:account-id:devEndpoint/development-endpoint-name
84
AWS Glue Developer Guide
API Permissions Reference
Action(s): glue:BatchGetJobs
Resource:
arn:aws:glue:region:account-id:job/job-name
Action(s): glue:BatchGetPartition
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:BatchGetTriggers
Resource:
arn:aws:glue:region:account-id:trigger/trigger-name
Action(s): glue:BatchStopJobRun
Resource:
*
CreateClassifier (create_classifier) (p. 513)
Action(s): glue:CreateClassifier
Resource:
*
CreateConnection (create_connection) (p. 496)
Action(s): glue:CreateConnection
Resource:
arn:aws:glue:region:account-id:connection/connection-name
arn:aws:glue:region:account-id:catalog
85
AWS Glue Developer Guide
API Permissions Reference
Action(s): glue:CreateCrawler
Resource:
arn:aws:glue:region:account-id:crawler/crawler-name
or
arn:aws:glue:region:account-id:crawler/*
Action(s):glue:CreateDatabase
Resource:
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:CreateDevEndpoint
Resource:
arn:aws:glue:region:account-id:devEndpoint/development-endpoint-name
or
arn:aws:glue:region:account-id:devEndpoint/*
Action(s): glue:CreateJob
Resource:
arn:aws:glue:region:account-id:job/job-name
or
arn:aws:glue:region:account-id:job/*
Action(s): glue:CreatePartition
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
86
AWS Glue Developer Guide
API Permissions Reference
arn:aws:glue:region:account-id:catalog
Action(s): glue:CreateScript
Resource:
*
CreateSecurityConfiguration (create_security_configuration) (p. 459)
Action(s): glue:CreateSecurityConfiguration
Resource:
*
CreateTable (create_table) (p. 473)
Action(s): glue:CreateTable
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:CreateTrigger
Resource:
arn:aws:glue:region:account-id:trigger/trigger-name
or
arn:aws:glue:region:account-id:trigger/*
Action(s): glue:CreateUserDefinedFunction
Resource:
arn:aws:glue:region:account-id:userDefinedFunction/database-name/user-defined-function-
name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:DeleteClassifier
Resource:
87
AWS Glue Developer Guide
API Permissions Reference
*
DeleteConnection (delete_connection) (p. 497)
Action(s): glue:DeleteConnection
Resource:
arn:aws:glue:region:account-id:connection/connection-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:DeleteCrawler
Resource:
arn:aws:glue:region:account-id:crawler/crawler-name
or
arn:aws:glue:region:account-id:crawler/*
Action(s): glue:DeleteDatabase
Resource:
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:userDefinedFunction/database-name/*
arn:aws:glue:region:account-id:table/database-name/*
arn:aws:glue:region:account-id:catalog
Action(s): glue:DeleteDevEndpoint
Resource:
arn:aws:glue:region:account-id:devEndpoint/development-endpoint-name
or
arn:aws:glue:region:account-id:devEndpoint/*
Action(s): glue:DeleteJob
Resource:
arn:aws:glue:region:account-id:job/job-name
or
88
AWS Glue Developer Guide
API Permissions Reference
arn:aws:glue:region:account-id:job/*
Action(s): glue:UpdatePartition
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:DeleteResourcePolicy
Resource:
*
DeleteSecurityConfiguration (delete_security_configuration) (p. 460)
Action(s): glue:DeleteSecurityConfiguration
Resource:
*
DeleteTable (delete_table) (p. 475)
Action(s): glue:DeleteTable
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:DeleteTableVersion
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:DeleteTrigger
Resource:
arn:aws:glue:region:account-id:trigger/trigger-name
89
AWS Glue Developer Guide
API Permissions Reference
or
arn:aws:glue:region:account-id:trigger/*
Action(s): glue:DeleteUserDefinedFunction
Resource:
arn:aws:glue:region:account-id:userDefinedFunction/database-name/user-defined-function-
name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetCatalogImportStatus
Resource:
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetClassifier
Resource:
*
GetClassifiers (get_classifiers) (p. 515)
Action(s): glue:GetClassifiers
Resource:
*
GetConnection (get_connection) (p. 497)
Action(s): glue:GetConnection
Resource:
arn:aws:glue:region:account-id:connection/connection-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetConnections
arn:aws:glue:region:account-id:connection/connection-names
90
AWS Glue Developer Guide
API Permissions Reference
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetCrawler
Resource:
arn:aws:glue:region:account-id:crawler/crawler-name
or
arn:aws:glue:region:account-id:crawler/*
GetCrawlerMetrics (get_crawler_metrics) (p. 523)
Action(s): glue:GetCrawlerMetrics
Resource:
*
GetCrawlers (get_crawlers) (p. 523)
Action(s): glue:GetCrawlers
Resource:
Action(s): glue:GetDatabase
Resource:
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetDatabases
Resource:
arn:aws:glue:region:account-id:database/database-names
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetDataCatalogEncryptionSettings
Resource:
91
AWS Glue Developer Guide
API Permissions Reference
Action(s): glue:GetDataflowGraph
Resource:
*
GetDevEndpoint (get_dev_endpoint) (p. 583)
Action(s): glue:GetDevEndpoint
Resource:
arn:aws:glue:region:account-id:devEndpoint/development-endpoint-name
or
arn:aws:glue:region:account-id:devEndpoint/*
Action(s): glue:GetDevEndpoints
Resource:
*
GetJob (get_job) (p. 543)
Action(s): glue:GetJob
Resource:
arn:aws:glue:region:account-id:job/job-name
or
arn:aws:glue:region:account-id:job/*
Action(s): glue:GetJobRun
Resource:
*
GetJobRuns (get_job_runs) (p. 552)
Action(s): glue:GetJobRuns
Resource:
*
GetJobs (get_jobs) (p. 543)
Action(s): glue:GetJobs
Resource:
92
AWS Glue Developer Guide
API Permissions Reference
*
GetMapping (get_mapping) (p. 533)
Action(s): glue:GetMapping
Resource:
*
GetPartition (get_partition) (p. 489)
Action(s): glue:GetPartition
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetPartitions
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetPlan
Resource:
*
GetResourcePolicy (get_resource_policy) (p. 458)
Action(s): glue:GetResourcePolicy
Resource:
*
GetSecurityConfiguration (get_security_configuration) (p. 460)
Action(s): glue:GetSecurityConfiguration
Resource:
*
GetSecurityConfigurations (get_security_configurations) (p. 461)
Action(s): glue:GetSecurityConfigurations
Resource:
93
AWS Glue Developer Guide
API Permissions Reference
*
GetTable (get_table) (p. 476)
Action(s): glue:GetTable
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetTables
Resource:
arn:aws:glue:region:account-id:table/database-name/table-names
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetTableVersion
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetTableVersions
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetTags
Resource:
*
GetTrigger (get_trigger) (p. 560)
Action(s): glue:GetTrigger
94
AWS Glue Developer Guide
API Permissions Reference
Resource:
arn:aws:glue:region:account-id:trigger/trigger-name
or
arn:aws:glue:region:account-id:trigger/*
Action(s): glue:GetTriggers
Resource:
*
GetUserDefinedFunction (get_user_defined_function) (p. 503)
Action(s): glue:GetUserDefinedFunction
Resource:
arn:aws:glue:region:account-id:userDefinedFunction/database-name/user-defined-function-
name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:GetUserDefinedFunctions
Resource:
arn:aws:glue:region:account-id:userDefinedFunction/database-name/user-defined-function-
names
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:ImportCatalogToGlue
Resource:
arn:aws:glue:region:account-id:catalog
Action(s): glue:ListCrawlers
Resource:
95
AWS Glue Developer Guide
API Permissions Reference
Action(s): glue:ListDevEndpoints
Resource:
*
ListJobs (list_jobs) (p. 544)
Action(s): glue:ListJobs
Resource:
*
ListTriggers (list_triggers) (p. 562)
Action(s): glue:ListTriggers
Resource:
*
PutDataCatalogEncryptionSettings (put_data_catalog_encryption_settings) (p. 457)
Action(s): glue:PutDataCatalogEncryptionSettings
Resource:
*
PutResourcePolicy (put_resource_policy) (p. 457)
Action(s): glue:PutResourcePolicy
Resource:
*
ResetJobBookmark (reset_job_bookmark) (p. 554)
Action(s): glue:ResetJobBookmark
Resource:
*
StartCrawler (start_crawler) (p. 525)
Action(s): glue:StartCrawler
Resource:
arn:aws:glue:region:account-id:crawler/crawler-name
or
arn:aws:glue:region:account-id:crawler/*
Action(s): glue:StartCrawlerSchedule
Resource:
96
AWS Glue Developer Guide
API Permissions Reference
*
StartJobRun (start_job_run) (p. 550)
Action(s): glue:StartJobRun
Resource:
*
StartTrigger (start_trigger) (p. 559)
Action(s): glue:StartTrigger
Resource:
arn:aws:glue:region:account-id:trigger/trigger-name
or
arn:aws:glue:region:account-id:trigger/*
Action(s): glue:StopCrawler
Resource:
arn:aws:glue:region:account-id:crawler/crawler-name
or
arn:aws:glue:region:account-id:crawler/*
Action(s): glue:StopCrawlerSchedule
Resource:
*
StopTrigger (stop_trigger) (p. 561)
Action(s): glue:StopTrigger
Resource:
arn:aws:glue:region:account-id:trigger/trigger-name
or
arn:aws:glue:region:account-id:trigger/*
Action(s): glue:TagResource
Resource:
97
AWS Glue Developer Guide
API Permissions Reference
Action(s): glue:UntagResource
Resource:
Action(s): glue:UpdateClassifier
Resource:
*
UpdateConnection (update_connection) (p. 499)
Action(s): glue:UpdateConnection
Resource:
arn:aws:glue:region:account-id:connection/connection-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:UpdateCrawler
Resource:
arn:aws:glue:region:account-id:crawler/crawler-name
or
arn:aws:glue:region:account-id:crawler/*
Action(s): glue:UpdateCrawlerSchedule
Resource:
*
UpdateDatabase (update_database) (p. 464)
Action(s): glue:UpdateDatabase
Resource:
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
98
AWS Glue Developer Guide
API Permissions Reference
Action(s): glue:UpdateDevEndpoint
Resource:
arn:aws:glue:region:account-id:devEndpoint/development-endpoint-name
or
arn:aws:glue:region:account-id:devEndpoint/*
Action(s): glue:UpdateJob
Resource:
arn:aws:glue:region:account-id:job/job-name
or
arn:aws:glue:region:account-id:job/*
Action(s): glue:UpdatePartition
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:UpdateTable
Resource:
arn:aws:glue:region:account-id:table/database-name/table-name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Action(s): glue:UpdateTrigger
Resource:
arn:aws:glue:region:account-id:trigger/trigger-name
or
arn:aws:glue:region:account-id:trigger/*
99
AWS Glue Developer Guide
Logging and Monitoring
Action(s): glue:UpdateUserDefinedFunction
Resource:
arn:aws:glue:region:account-id:userDefinedFunction/database-name/user-defined-function-
name
arn:aws:glue:region:account-id:database/database-name
arn:aws:glue:region:account-id:catalog
Related Topics
• Identity and Access Management (p. 49)
AWS Glue is integrated with AWS CloudTrail, a service that provides a record of actions taken by a user,
role, or AWS service in AWS Glue. If you create a trail, you can enable continuous delivery of CloudTrail
events to an Amazon Simple Storage Service (Amazon S3) bucket, Amazon CloudWatch Logs, and
Amazon CloudWatch Events. Every event or log entry contains information about who generated the
request.
Use Amazon CloudWatch Events to automate your AWS services and respond automatically to system
events such as application availability issues or resource changes. Events from AWS services are delivered
to CloudWatch Events in near-real time. You can write simple rules to indicate which events are of
interest and what automated actions to take when an event matches a rule.
For more information, see Automating AWS Glue with CloudWatch Events (p. 226).
For a list of AWS services in scope of specific compliance programs, see AWS Services in Scope by
Compliance Program. For general information, see AWS Compliance Programs.
You can download third-party audit reports using AWS Artifact. For more information, see Downloading
Reports in AWS Artifact in the AWS Artifact User Guide.
Your compliance responsibility when using AWS Glue is determined by the sensitivity of your data, your
company's compliance objectives, and applicable laws and regulations. If your use of AWS Glue is subject
to compliance with standards such as HIPAA, PCI, or FedRAMP, AWS provides resources to help:
100
AWS Glue Developer Guide
Resilience
• Security and Compliance Quick Start Guides – These deployment guides discuss architectural
considerations and provide steps for deploying security- and compliance-focused baseline
environments on AWS.
• Architecting for HIPAA Security and Compliance Whitepaper – This whitepaper describes how
companies can use AWS to create HIPAA-compliant applications.
• AWS Compliance Resources – This collection of workbooks and guides might apply to your industry
and location.
• AWS Config – This AWS service assesses how well your resource configurations comply with internal
practices, industry guidelines, and regulations.
• AWS Security Hub – This AWS service provides a comprehensive view of your security state within AWS
that helps you check your compliance with security industry standards and best practices.
For more information about AWS Regions and Availability Zones, see AWS Global Infrastructure.
In addition to the AWS global infrastructure, AWS Glue offers several features to help support your data
resiliency and backup needs.
You use AWS published API calls to access AWS Glue through the network. Clients must support
Transport Layer Security (TLS) 1.0 or later. We recommend TLS 1.2 or later. Clients must also support
cipher suites with perfect forward secrecy (PFS) such as Ephemeral Diffie-Hellman (DHE) or Elliptic Curve
Ephemeral Diffie-Hellman (ECDHE). Most modern systems such as Java 7 and later support these modes.
Additionally, requests must be signed by using an access key ID and a secret access key that is associated
with an IAM principal. Or you can use the AWS Security Token Service (AWS STS) to generate temporary
security credentials to sign requests.
Topics
• Using AWS Glue with VPC Endpoints (p. 101)
• Shared Amazon VPCs (p. 102)
Amazon VPC is an AWS service that you can use to launch AWS resources in a virtual network that you
define. With a VPC, you have control over your network settings, such the IP address range, subnets,
101
AWS Glue Developer Guide
Shared Amazon VPCs
route tables, and network gateways. To connect your VPC to AWS Glue, you define an interface VPC
endpoint for AWS Glue. When you use a VPC interface endpoint, communication between your VPC and
AWS Glue is conducted entirely and securely within the AWS network.
You can use AWS Glue with VPC endpoints in all AWS Regions that support both AWS Glue and Amazon
VPC endpoints.
For more information, see these topics in the Amazon VPC User Guide:
In AWS Glue, to create a connection with a shared subnet, you must create a security group within your
account and attach the security group to the shared subnet.
102
AWS Glue Developer Guide
The following workflow diagram shows how AWS Glue crawlers interact with data stores and other
elements to populate the Data Catalog.
The following is the general workflow for how a crawler populates the AWS Glue Data Catalog:
1. A crawler runs any custom classifiers that you choose to infer the format and schema of your data. You
provide the code for custom classifiers, and they run in the order that you specify.
The first custom classifier to successfully recognize the structure of your data is used to create a
schema. Custom classifiers lower in the list are skipped. If no custom classifier matches your data's
103
AWS Glue Developer Guide
Defining a Database in Your Data Catalog
schema, built-in classifiers try to recognize your data's schema. An example of a built-in classifier is
one that recognizes JSON.
2. The crawler connects to the data store. Some data stores require connection properties for crawler
access.
3. The inferred schema is created for your data.
4. The crawler writes metadata to the Data Catalog. A table definition contains metadata about the
data in your data store. The table is written to a database, which is a container of tables in the Data
Catalog. Attributes of a table include classification, which is a label created by the classifier that
inferred the table schema.
Topics
• Defining a Database in Your Data Catalog (p. 104)
• Defining Tables in the AWS Glue Data Catalog (p. 105)
• Adding a Connection to Your Data Store (p. 109)
• Defining Crawlers (p. 114)
• Adding Classifiers to a Crawler (p. 127)
• Working with Data Catalog Settings on the AWS Glue Console (p. 142)
• Populating the Data Catalog Using AWS CloudFormation Templates (p. 143)
Your database can contain tables that define data from many different data stores. This data can include
objects in Amazon Simple Storage Service (Amazon S3) and relational tables in Amazon Relational
Database Service.
Note
When you delete a database, all the tables in the database are also deleted.
For more information about defining a database using the AWS Glue console, see Working with
Databases on the AWS Glue Console (p. 104).
To view the list of databases, sign in to the AWS Management Console and open the AWS Glue console at
https://console.aws.amazon.com/glue/. Choose Databases, and then choose a database name in the list
to view the details.
From the Databases tab in the AWS Glue console, you can add, edit, and delete databases:
• To create a new database, choose Add database and provide a name and description. For compatibility
with other metadata stores, such as Apache Hive, the name is folded to lowercase characters.
Note
If you plan to access the database from Amazon Athena, then provide a name with only
alphanumeric and underscore characters. For more information, see Athena names.
104
AWS Glue Developer Guide
Defining Tables in the AWS Glue Data Catalog
• To edit the description for a database, select the check box next to the database name and choose
Action, Edit database.
• To delete a database, select the check box next to the database name and choose Action, Delete
database.
• To display the list of tables contained in the database, select the check box next to the database name
and choose View tables.
To change the database that a crawler writes to, you must change the crawler definition. For more
information, see Defining Crawlers (p. 114).
• Run a crawler that connects to one or more data stores, determines the data structures, and
writes tables into the Data Catalog. The crawler uses built-in or custom classifiers to recognize the
structure of the data. You can run your crawler on a schedule. For more information, see Defining
Crawlers (p. 114).
• Use the AWS Glue console to manually create a table in the AWS Glue Data Catalog. For more
information, see Working with Tables on the AWS Glue Console (p. 106).
• Use the CreateTable operation in the AWS Glue API (p. 446) to create a table in the AWS Glue Data
Catalog. For more information, see CreateTable Action (Python: create_table) (p. 473).
• Use AWS CloudFormation templates. For more information, see Populating the Data Catalog Using
AWS CloudFormation Templates (p. 143).
• Migrate an Apache Hive metastore. For more information, see Migration between the Hive Metastore
and the AWS Glue Data Catalog on GitHub.
When you define a table manually using the console or an API, you specify the table schema and the
value of a classification field that indicates the type and format of the data in the data source. If a
crawler creates the table, the data format and schema are determined by either a built-in classifier or a
custom classifier. For more information about creating a table using the AWS Glue console, see Working
with Tables on the AWS Glue Console (p. 106).
Table Partitions
An AWS Glue table definition of an Amazon Simple Storage Service (Amazon S3) folder can describe
a partitioned table. For example, to improve query performance, a partitioned table might separate
monthly data into different files using the name of the month as a key. In AWS Glue, table definitions
include the partitioning key of a table. When AWS Glue evaluates the data in Amazon S3 folders to
catalog a table, it determines whether an individual table or a partitioned table is added.
All the following conditions must be true for AWS Glue to create a partitioned table for an Amazon S3
folder:
For example, you might own an Amazon S3 bucket named my-app-bucket, where you store both
iOS and Android app sales data. The data is partitioned by year, month, and day. The data files for iOS
and Android sales have the same schema, data format, and compression format. In the AWS Glue Data
105
AWS Glue Developer Guide
Updating Manually Created Tables with Crawlers
Catalog, the AWS Glue crawler creates one table definition with partitioning keys for year, month, and
day.
The following Amazon S3 listing of my-app-bucket shows some of the partitions. The = symbol is used
to assign partition key values.
my-app-bucket/Sales/year='2010'/month='feb'/day='1'/iOS.csv
my-app-bucket/Sales/year='2010'/month='feb'/day='1'/Android.csv
my-app-bucket/Sales/year='2010'/month='feb'/day='2'/iOS.csv
my-app-bucket/Sales/year='2010'/month='feb'/day='2'/Android.csv
...
my-app-bucket/Sales/year='2017'/month='feb'/day='4'/iOS.csv
my-app-bucket/Sales/year='2017'/month='feb'/day='4'/Android.csv
To do this, when you define a crawler, instead of specifying one or more data stores as the source of
a crawl, you specify one or more existing Data Catalog tables. The crawler then crawls the data stores
specified by the catalog tables. In this case, no new tables are created; instead, your manually created
tables are updated.
The following are other reasons why you might want to manually create catalog tables and specify
catalog tables as the crawler source:
• You want to choose the catalog table name and not rely on the catalog table naming algorithm.
• You want to prevent new tables from being created in the case where files with a format that could
disrupt partition detection are mistakenly saved in the data source path.
To get started, sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/. Choose the Tables tab, and use the Add tables button to create tables
either with a crawler or by manually typing attributes.
If you know the attributes that are required to create an Amazon Simple Storage Service (Amazon S3)
table definition in your Data Catalog, you can create it with the table wizard. Choose Add tables, Add
table manually, and follow the instructions in the Add table wizard.
106
AWS Glue Developer Guide
Working with Tables on the Console
When adding a table manually through the console, consider the following:
• If you plan to access the table from Amazon Athena, then provide a name with only alphanumeric and
underscore characters. For more information, see Athena names.
• The location of your source data must be an Amazon S3 path.
• The data format of the data must match one of the listed formats in the wizard. The corresponding
classification, SerDe, and other table properties are automatically populated based on the format
chosen. You can define tables with the following formats:
JSON
Character separated values. You also specify the delimiter of either comma, pipe, semicolon, tab,
or Ctrl-A.
Parquet
Extensible Markup Language format. Specify the XML tag that defines a row in the data. Columns
are defined within row tags.
• You can define a partition key for the table.
• Currently, partitioned tables that you create with the console cannot be used in ETL jobs.
Table Attributes
The following are some important attributes of your table:
Table name
The name is determined when the table is created, and you can't change it. You refer to a table
name in many AWS Glue operations.
Database
The container object where your table resides. This object contains an organization of your tables
that exists within the AWS Glue Data Catalog and might differ from an organization in your data
store. When you delete a database, all tables contained in the database are also deleted from the
Data Catalog.
Location
The pointer to the location of the data in a data store that this table definition represents.
Classification
A categorization value provided when the table was created. Typically, this is written when a crawler
runs and specifies the format of the source data.
Last updated
The time and date (UTC) that this table was updated in the Data Catalog.
Date added
The time and date (UTC) that this table was added to the Data Catalog.
107
AWS Glue Developer Guide
Working with Tables on the Console
Description
The description of the table. You can write a description to help you understand the contents of the
table.
Deprecated
If AWS Glue discovers that a table in the Data Catalog no longer exists in its original data store, it
marks the table as deprecated in the data catalog. If you run a job that references a deprecated
table, the job might fail. Edit jobs that reference deprecated tables to remove them as sources and
targets. We recommend that you delete deprecated tables when they are no longer needed.
Connection
If AWS Glue requires a connection to your data store, the name of the connection is associated with
the table.
The table details include properties of your table and its schema. This view displays the schema of
the table, including column names in the order defined for the table, data types, and key columns
for partitions. If a column is a complex type, you can choose View properties to display details of the
structure of that field, as shown in the following example:
{
"StorageDescriptor": {
"cols": {
"FieldSchema": [
{
"name": "primary-1",
"type": "CHAR",
"comment": ""
},
{
"name": "second ",
"type": "STRING",
"comment": ""
}
]
},
"location": "s3://aws-logs-111122223333-us-east-1",
"inputFormat": "",
"outputFormat": "org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat",
"compressed": "false",
"numBuckets": "0",
"SerDeInfo": {
"name": "",
"serializationLib": "org.apache.hadoop.hive.serde2.OpenCSVSerde",
"parameters": {
"separatorChar": "|"
}
},
"bucketCols": [],
"sortCols": [],
"parameters": {},
"SkewedInfo": {},
"storedAsSubDirectories": "false"
},
"parameters": {
"classification": "csv"
108
AWS Glue Developer Guide
Adding a Connection to Your Data Store
}
}
For more information about the properties of a table, such as StorageDescriptor, see
StorageDescriptor Structure (p. 470).
To change the schema of a table, choose Edit schema to add and remove columns, change column
names, and change data types.
To compare different versions of a table, including its schema, choose Compare versions to see a side-
by-side comparison of two versions of the schema for a table.
To display the files that make up an Amazon S3 partition, choose View partition. For Amazon S3 tables,
the Key column displays the partition keys that are used to partition the table in the source data store.
Partitioning is a way to divide a table into related parts based on the values of a key column, such as
date, location, or department. For more information about partitions, search the internet for information
about "hive partitioning."
Note
To get step-by-step guidance for viewing the details of a table, see the Explore table tutorial in
the console.
After AWS Glue connects to a JDBC data store, it must have permission from the data store to perform
operations. The username you provide with the connection must have the required permissions or
privileges. For example, a crawler requires SELECT privileges to retrieve metadata from a JDBC data
store. Likewise, a job that writes to a JDBC target requires the necessary privileges to INSERT, UPDATE,
and DELETE data into an existing table.
AWS Glue can connect to the following data stores by using the JDBC protocol:
• Amazon Redshift
• Amazon Relational Database Service
• Amazon Aurora
• MariaDB
• Microsoft SQL Server
• MySQL
• Oracle
109
AWS Glue Developer Guide
Connecting to a JDBC Data Store in a VPC
• PostgreSQL
• Publicly accessible databases
• Amazon Aurora
• MariaDB
• Microsoft SQL Server
• MySQL
• Oracle
• PostgreSQL
A connection is not typically required for Amazon S3. However, to access Amazon S3 from within your
virtual private cloud (VPC), an Amazon S3 VPC endpoint is required. For more information, see Amazon
VPC Endpoints for Amazon S3 (p. 30).
In your connection information, you also must consider whether data is accessed through a VPC and then
set up network parameters accordingly. AWS Glue requires a private IP for JDBC endpoints. Connections
to databases can be over a VPN and DirectConnect as they provide private IP access to on-premises
databases.
For information about how to connect to on-premises databases, see the blog post How to access and
analyze on-premises data stores using AWS Glue.
To allow AWS Glue to communicate with its components, specify a security group with a self-referencing
inbound rule for all TCP ports. By creating a self-referencing rule, you can restrict the source to the same
security group in the VPC and not open it to all networks. The default security group for your VPC might
already have a self-referencing inbound rule for ALL Traffic.
You can create rules in the Amazon VPC console. To update rule settings via the AWS Management
Console, navigate to the VPC console (https://console.aws.amazon.com/vpc/), and select the
appropriate security group. Specify the inbound rule for ALL TCP to have as its source the same security
group name. For more information about security group rules, see Security Groups for Your VPC.
Each elastic network interface is assigned a private IP address from the IP address range in the subnets
that you specify. The network interface is not assigned any public IP addresses. AWS Glue requires
internet access (for example, to access AWS services that don't have VPC endpoints). You can configure
a network address translation (NAT) instance inside your VPC, or you can use the Amazon VPC NAT
gateway. For more information, see NAT Gateways in the Amazon VPC User Guide. You can't directly use
110
AWS Glue Developer Guide
Working with Connections on the Console
an internet gateway attached to your VPC as a route in your subnet route table because that requires the
network interface to have public IP addresses.
The VPC network attributes enableDnsHostnames and enableDnsSupport must be set to true. For
more information, see Using DNS with your VPC.
Important
Don't put your data store in a public subnet or in a private subnet that doesn't have internet
access. Instead, attach it only to private subnets that have internet access through a NAT
instance or an Amazon VPC NAT gateway.
VPC
The security groups that are associated with your data store. AWS Glue associates these security
groups with the elastic network interface that is attached to your VPC subnet. To allow AWS Glue
components to communicate and also prevent access from other networks, at least one chosen
security group must specify a self-referencing inbound rule for all TCP ports.
For information about managing a VPC with Amazon Redshift, see Managing Clusters in an Amazon
Virtual Private Cloud (VPC).
For information about managing a VPC with Amazon RDS, see Working with an Amazon RDS DB Instance
in a VPC.
The Connections list displays the following properties about each connection:
Name
The data store type and the properties that are required for a successful connection. AWS Glue uses
the JDBC protocol to access several types of data stores.
Date created
The date and time (UTC) that the connection was created.
Last updated
The date and time (UTC) that the connection was last updated.
Updated by
111
AWS Glue Developer Guide
Working with Connections on the Console
From the Connections tab in the AWS Glue console, you can add, edit, and delete connections. To see
more details for a connection, choose the connection name in the list. Details include the information
you defined when you created the connection.
As a best practice, before you use a data store connection in an ETL job, choose Test connection. AWS
Glue uses the parameters in your connection to confirm that it can access your data store and reports
back any errors. Connections are required for Amazon Redshift, Amazon Relational Database Service
(Amazon RDS), and JDBC data stores. For more information, see Connecting to a JDBC Data Store in a
VPC (p. 110).
Important
Currently, an ETL job can use only one JDBC connection. If you have multiple data stores in a
job, they must be on the same subnet.
When you define a connection, values for the following properties are required:
Connection name
Select this option to require AWS Glue to verify that the JDBC database connection is connected
over a trusted Secure Socket Layer (SSL). This option is optional. If not selected, AWS Glue can
ignore failures when it uses SSL to encrypt a connection to a JDBC database. See the documentation
for your database for configuration instructions. When you select this option, if AWS Glue cannot
connect using SSL, the job run, crawler, or ETL statements in a development endpoint fail.
This option is validated on the AWS Glue client side. AWS Glue only connects to JDBC over SSL with
certificate and host name validation. Support is available for:
• Oracle
• Microsoft SQL Server
• PostgreSQL
• Amazon Redshift
• MySQL (Amazon RDS instances only)
• Aurora MySQL (Amazon RDS instances only)
• Aurora Postgres (Amazon RDS instances only)
Note
To enable an Amazon RDS Oracle data store to use Require SSL connection, you need to
create and attach an option group to the Oracle instance.
1. Sign in to the AWS Management Console and open the Amazon RDS console at https://
console.aws.amazon.com/rds/.
112
AWS Glue Developer Guide
Working with Connections on the Console
2. Add an Option group to the Amazon RDS Oracle instance. For more information about
how to add an option group on the Amazon RDS console, see Creating an Option Group
3. Add an Option to the option group for SSL. The Port you specify for SSL is later used
when you create an AWS Glue JDBC connection URL for the Amazon RDS Oracle instance.
For more information about how to add an option on the Amazon RDS console, see
Adding an Option to an Option Group. For more information about the Oracle SSL
option, see Oracle SSL.
4. On the AWS Glue console, create a connection to the Amazon RDS Oracle instance. In
the connection definition, select Require SSL connection, and when requested, enter the
Port you used in the Amazon RDS Oracle SSL option.
Custom certificate fields (optional)
If you have a certificate that you are currently using for SSL communication with your on-premise
or cloud databases, you can use that certificate for SSL connections to AWS Glue data sources or
targets. The following optional fields are available when you select Require SSL connection:
Custom JDBC certificate
Enter an Amazon S3 location containing a custom root certificate. AWS Glue uses this certificate
to establish an SSL connection to the database. AWS Glue handles only X.509 certificates. The
certificate must be DER-encoded and supplied in Base64 encoding PEM format.
Select this check box to skip validation of the custom certificate by AWS Glue. If you choose to
validate, AWS Glue validates the signature algorithm and subject public key algorithm for the
certificate. If the certificate fails validation, any ETL job or crawler that uses the connection fails.
Enter database-specific certificate information. This is a string that is used for domain
matching or distinguished name (DN) matching. For Oracle Database, this maps to the
SSL_SERVER_CERT_DN parameter in the security section of the tnsnames.ora file. For
Microsoft SQL Server, this is used as hostNameInCertificate.
cn=sales,cn=OracleContext,dc=us,dc=example,dc=com
JDBC URL
Type the URL for your JDBC data store. For most database engines, this field is in the following
format.
jdbc:protocol://host:port/db_name
Depending on the database engine, a different JDBC URL format might be required. This format can
have slightly different use of the colon (:) and slash (/) or different keywords to specify databases.
For JDBC to connect to the data store, a db_name in the data store is required. The db_name is used
to establish a network connection with the supplied username and password. When connected,
AWS Glue can access other databases in the data store to run a crawler or run an ETL job.
The following JDBC URL examples show the syntax for several database engines.
• To connect to an Amazon Redshift cluster data store with a dev database:
jdbc:redshift://xxx.us-east-1.redshift.amazonaws.com:8192/dev
113
AWS Glue Developer Guide
Defining Crawlers
• To connect to an Amazon RDS for MySQL data store with an employee database:
jdbc:mysql://xxx-cluster.cluster-xxx.us-east-1.rds.amazonaws.com:3306/
employee
• To connect to an Amazon RDS for PostgreSQL data store with an employee database:
jdbc:postgresql://xxx-cluster.cluster-xxx.us-
east-1.rds.amazonaws.com:5432/employee
• To connect to an Amazon RDS for Oracle data store with an employee service name:
jdbc:oracle:thin://@xxx-cluster.cluster-xxx.us-
east-1.rds.amazonaws.com:1521/employee
The syntax for Amazon RDS for Oracle can follow the following patterns:
• jdbc:oracle:thin://@host:port/service_name
• jdbc:oracle:thin://@host:port:SID
• To connect to an Amazon RDS for Microsoft SQL Server data store with an employee database:
jdbc:sqlserver://xxx-cluster.cluster-xxx.us-
east-1.rds.amazonaws.com:1433;databaseName=employee
The syntax for Amazon RDS for SQL Server can follow the following patterns:
• jdbc:sqlserver://server_name:port;database=db_name
• jdbc:sqlserver://server_name:port;databaseName=db_name
Username
Provide a user name that has permission to access the JDBC data store.
Password
Type the password for the user name that has access permission to the JDBC data store.
Port
Type the port used in the JDBC URL to connect to an Amazon RDS Oracle instance. This field is only
shown when Require SSL connection is selected for an Amazon RDS Oracle instance.
VPC
Choose the name of the virtual private cloud (VPC) that contains your data store. The AWS Glue
console lists all VPCs for the current region.
Subnet
Choose the subnet within the VPC that contains your data store. The AWS Glue console lists all
subnets for the data store in your VPC.
Security groups
Choose the security groups that are associated with your data store. AWS Glue requires one or more
security groups with an inbound source rule that allows AWS Glue to connect. The AWS Glue console
lists all security groups that are granted inbound access to your VPC. AWS Glue associates these
security groups with the elastic network interface that is attached to your VPC subnet.
Defining Crawlers
You can use a crawler to populate the AWS Glue Data Catalog with tables. This is the primary method
used by most AWS Glue users. A crawler can crawl multiple data stores in a single run. Upon completion,
the crawler creates or updates one or more tables in your Data Catalog. Extract, transform, and load
114
AWS Glue Developer Guide
Which Data Stores Can I Crawl?
(ETL) jobs that you define in AWS Glue use these Data Catalog tables as sources and targets. The ETL job
reads from and writes to the data stores that are specified in the source and target Data Catalog tables.
For more information about using the AWS Glue console to add a crawler, see Working with Crawlers on
the AWS Glue Console (p. 125).
Crawlers can crawl the following data stores through their respective native interfaces:
Crawlers can crawl the following data stores through a JDBC connection:
• Amazon Redshift
• Amazon Relational Database Service (Amazon RDS)
• Amazon Aurora
• MariaDB
• Microsoft SQL Server
• MySQL
• Oracle
• PostgreSQL
• Publicly accessible databases
• Aurora
• MariaDB
• SQL Server
• MySQL
• Oracle
• PostgreSQL
For Amazon S3 and Amazon DynamoDB, crawlers use an AWS Identity and Access Management (IAM)
role for permission to access your data stores. The role you pass to the crawler must have permission to
access Amazon S3 paths and Amazon DynamoDB tables that are crawled. For JDBC connections, crawlers
use user name and password credentials. For more information, see Adding a Connection to Your Data
Store (p. 109).
When you define an Amazon S3 data store to crawl, you can choose whether to crawl a path in your
account or another account. The output of the crawler is one or more metadata tables defined in the
AWS Glue Data Catalog. A table is created for one or more files found in your data store. If all the
Amazon S3 files in a folder have the same schema, the crawler creates one table. Also, if the Amazon S3
object is partitioned, only one metadata table is created.
If the data store that is being crawled is a relational database, the output is also a set of metadata
tables defined in the AWS Glue Data Catalog. When you crawl a relational database, you must provide
authorization credentials for a connection to read objects in the database engine. Depending on the type
of database engine, you can choose which objects are crawled, such as databases, schemas, and tables.
If the data store that is being crawled is one or more Amazon DynamoDB tables, the output is one or
more metadata tables in the AWS Glue Data Catalog. When defining a crawler using the AWS Glue
console, you specify a DynamoDB table. If you're using the AWS Glue API, you specify a list of tables.
115
AWS Glue Developer Guide
What Happens When a Crawler Runs?
• Classifies data to determine the format, schema, and associated properties of the raw data – You
can configure the results of classification by creating a custom classifier.
• Groups data into tables or partitions – Data is grouped based on crawler heuristics.
• Writes metadata to the Data Catalog – You can configure how the crawler adds, updates, and deletes
tables and partitions.
The metadata tables that a crawler creates are contained in a database when you define a crawler. If your
crawler does not define a database, your tables are placed in the default database. In addition, each table
has a classification column that is filled in by the classifier that first successfully recognized the data
store.
If the file that is crawled is compressed, the crawler must download it to process it. When a crawler runs,
it interrogates files to determine their format and compression type and writes these properties into
the Data Catalog. Some file formats (for example, Apache Parquet) enable you to compress parts of the
file as it is written. For these files, the compressed data is an internal component of the file, and AWS
Glue does not populate the compressionType property when it writes tables into the Data Catalog.
In contrast, if an entire file is compressed by a compression algorithm (for example, gzip), then the
compressionType property is populated when tables are written into the Data Catalog.
The crawler generates the names for the tables that it creates. The names of the tables that are stored in
the AWS Glue Data Catalog follow these rules:
If your crawler runs more than once, perhaps on a schedule, it looks for new or changed files or tables in
your data store. The output of the crawler includes new tables and partitions found since a previous run.
s3://bucket01/folder1/table1/partition1/file.txt
s3://bucket01/folder1/table1/partition2/file.txt
s3://bucket01/folder1/table1/partition3/file.txt
s3://bucket01/folder1/table2/partition4/file.txt
s3://bucket01/folder1/table2/partition5/file.txt
If the schemas for table1 and table2 are similar, and a single data store is defined in the crawler
with Include path s3://bucket01/folder1/, the crawler creates a single table with two partition
116
AWS Glue Developer Guide
Crawler Properties
columns. One partition column contains table1 and table2, and a second partition column contains
partition1 through partition5. To create two separate tables, define the crawler with two data
stores. In this example, define the first Include path as s3://bucket01/folder1/table1/ and the
second as s3://bucket01/folder1/table2.
Note
In Amazon Athena, each table corresponds to an Amazon S3 prefix with all the objects in it. If
objects have different schemas, Athena does not recognize different objects within the same
prefix as separate tables. This can happen if a crawler creates multiple tables from the same
Amazon S3 prefix. This might lead to queries in Athena that return zero results. For Athena
to properly recognize and query tables, create the crawler with a separate Include path for
each different table schema in the Amazon S3 folder structure. For more information, see Best
Practices When Using Athena with AWS Glue and this AWS Knowledge Center article.
Crawler Properties
When defining a crawler using the AWS Glue console or the AWS Glue API, you specify the following
information:
Settings include tags, security configuration, and custom classifiers. You define custom classifiers
before defining crawlers. For more information, see the following:
• AWS Tags in AWS Glue (p. 224)
• Adding Classifiers to a Crawler (p. 127)
Crawler source type
The crawler can access data stores directly as the source of the crawl, or it can use existing catalog
tables as the source. If the crawler uses existing catalog tables, it crawls the data stores that are
specified by those catalog tables. For more information, see Crawler Source Type (p. 118).
Crawler sources (Choose one of the following two types.)
• One or more data stores
A crawler can crawl multiple data stores of different types (Amazon S3, Amazon DynamoDB, and
JDBC) in a single run.
• List of Data Catalog tables
The catalog tables specify the data stores to crawl. The crawler can crawl only catalog tables in a
single run; it can't mix in other source types.
Exclude patterns
These enable you to exclude certain files or tables from the crawl. For more information, see Include
and Exclude Patterns (p. 118).
IAM role or JDBC credentials for accessing the data stores
For more information, see Managing Access Permissions for AWS Glue Resources (p. 51)
Crawler schedule
You can run a crawler on demand or define a schedule for automatic running of the crawler. For
more information, see Scheduling an AWS Glue Crawler (p. 125).
Destination database within the Data Catalog for the created catalog tables
For more information, see Defining a Database in Your Data Catalog (p. 104).
Crawler configuration options
Options include how the crawler should handle detected schema changes, deleted objects in the
data store, and more. For more information, see Configuring a Crawler (p. 121).
117
AWS Glue Developer Guide
Crawler Properties
When you define a crawler, you choose one or more classifiers that evaluate the format of your data to
infer a schema. When the crawler runs, the first classifier in your list to successfully recognize your data
store is used to create a schema for your table. You can use built-in classifiers or define your own. You
define your custom classifiers in a separate operation, before you define the crawlers. AWS Glue provides
built-in classifiers to infer schemas from common files with formats that include JSON, CSV, and Apache
Avro. For the current list of built-in classifiers in AWS Glue, see Built-In Classifiers in AWS Glue (p. 128).
A common reason to specify a catalog table as the source is that you created the table manually
(because you already knew the structure of the data store) and you want a crawler to keep the table
updated, including adding new partitions. For a discussion of other reasons, see Updating Manually
Created Data Catalog Tables Using Crawlers (p. 106).
When you specify existing tables as the crawler source type, the following conditions apply:
A crawler connects to a JDBC data store using an AWS Glue connection that contains a JDBC URI
connection string. The crawler only has access to objects in the database engine using the JDBC user
name and password in the AWS Glue connection. The crawler can only create tables that it can access
through the JDBC connection. After the crawler accesses the database engine with the JDBC URI, the
include path is used to determine which tables in the database engine are created in the Data Catalog.
For example, with MySQL, if you specify an include path of MyDatabase/%, then all tables within
MyDatabase are created in the Data Catalog. When accessing Amazon Redshift, if you specify an include
path of MyDatabase/%, then all tables within all schemas for database MyDatabase are created in the
118
AWS Glue Developer Guide
Crawler Properties
Data Catalog. If you specify an include path of MyDatabase/MySchema/%, then all tables in database
MyDatabase and schema MySchema are created.
After you specify an include path, you can then exclude objects from the crawl that your include
path would otherwise include by specifying one or more Unix-style glob exclude patterns. These
patterns are applied to your include path to determine which objects are excluded. These patterns
are also stored as a property of tables created by the crawler. AWS Glue PySpark extensions, such as
create_dynamic_frame.from_catalog, read the table properties and exclude objects defined by the
exclude pattern.
AWS Glue supports the following kinds of glob patterns in the exclude pattern.
• The slash (/) character is the delimiter to separate Amazon S3 keys into a folder hierarchy.
• The asterisk (*) character matches zero or more characters of a name component without crossing
folder boundaries.
• A double asterisk (**) matches zero or more characters crossing folder or schema boundaries.
• The question mark (?) character matches exactly one character of a name component.
• The backslash (\) character is used to escape characters that otherwise can be interpreted as special
characters. The expression \\ matches a single backslash, and \{ matches a left brace.
• Brackets [ ] create a bracket expression that matches a single character of a name component out
of a set of characters. For example, [abc] matches a, b, or c. The hyphen (-) can be used to specify
a range, so [a-z] specifies a range that matches from a through z (inclusive). These forms can be
mixed, so [abce-g] matches a, b, c, e, f, or g. If the character after the bracket ([) is an exclamation
point (!), the bracket expression is negated. For example, [!a-c] matches any character except a, b,
or c.
119
AWS Glue Developer Guide
Crawler Properties
Within a bracket expression, the *, ?, and \ characters match themselves. The hyphen (-) character
matches itself if it is the first character within the brackets, or if it's the first character after the ! when
you are negating.
• Braces ({ }) enclose a group of subpatterns, where the group matches if any subpattern in the group
matches. A comma (,) character is used to separate the subpatterns. Groups cannot be nested.
• Leading period or dot characters in file names are treated as normal characters in match operations.
For example, the * exclude pattern matches the file name .hidden.
Each exclude pattern is evaluated against the include path. For example, suppose that you have the
following Amazon S3 directory structure:
/mybucket/myfolder/
departments/
finance.json
market-us.json
market-emea.json
market-ap.json
employees/
hr.json
john.csv
jane.csv
juan.txt
Given the include path s3://mybucket/myfolder/, the following are some sample results for exclude
patterns:
Suppose that your data is partitioned by day, so that each day in a year is in a separate Amazon S3
partition. For January 2015, there are 31 partitions. Now, to crawl data for only the first week of January,
you must exclude all partitions except days 1 through 7:
Take a look at the parts of this glob pattern. The first part, 2015/01/{[!0],0[8-9]}**, excludes all
days that don't begin with a "0" in addition to day 08 and day 09 from month 01 in year 2015. Notice
that "**" is used as the suffix to the day number pattern and crosses folder boundaries to lower-level
folders. If "*" is used, lower folder levels are not excluded.
120
AWS Glue Developer Guide
Configuring a Crawler
The second part, 2015/0[2-9]/**, excludes days in months 02 to 09, in year 2015.
The third part, 2015/1[0-2]/**, excludes days in months 10, 11, and 12, in year 2015.
MyDatabase/MySchema/
HR_us
HR_fr
Employees_Table
Finance
Market_US_Table
Market_EMEA_Table
Market_AP_Table
Given the include path MyDatabase/MySchema/%, the following are some sample results for exclude
patterns:
Configuring a Crawler
When a crawler runs, it might encounter changes to your data store that result in a schema or partition
that is different from a previous crawl. You can use the AWS Management Console or the AWS Glue API
to configure how your crawler processes certain types of changes.
Topics
• Configuring a Crawler on the AWS Glue Console (p. 121)
• Configuring a Crawler Using the API (p. 122)
• How to Prevent the Crawler from Changing an Existing Schema (p. 123)
• How to Create a Single Schema for Each Amazon S3 Include Path (p. 124)
When a crawler runs against a previously crawled data store, it might discover that a schema has
changed or that some objects in the data store have been deleted. The crawler logs changes to a schema.
Depending on the source type for the crawler, new tables and partitions might be created regardless of
the schema change policy.
To specify what the crawler does when it finds changes in the schema, you can choose one of the
following actions on the console:
121
AWS Glue Developer Guide
Configuring a Crawler
• Update the table definition in the Data Catalog – Add new columns, remove missing columns, and
modify the definitions of existing columns in the AWS Glue Data Catalog. Remove any metadata that is
not set by the crawler. This is the default setting.
• Add new columns only – For tables that map to an Amazon S3 data store, add new columns as they
are discovered, but don't remove or change the type of existing columns in the Data Catalog. Choose
this option when the current columns in the Data Catalog are correct and you don't want the crawler
to remove or change the type of the existing columns. If a fundamental Amazon S3 table attribute
changes, such as classification, compression type, or CSV delimiter, mark the table as deprecated.
Maintain input format and output format as they exist in the Data Catalog. Update SerDe parameters
only if the parameter is one that is set by the crawler. For all other data stores, modify existing column
definitions.
• Ignore the change and don't update the table in the Data Catalog – Only new tables and partitions
are created.
A crawler might also discover new or changed partitions. By default, new partitions are added and
existing partitions are updated if they have changed. In addition, you can set a crawler configuration
option to Update all new and existing partitions with metadata from the table on the AWS Glue
console. When this option is set, partitions inherit metadata properties—such as their classification,
input format, output format, SerDe information, and schema—from their parent table. Any changes to
these properties in a table are propagated to its partitions. When this configuration option is set on an
existing crawler, existing partitions are updated to match the properties of their parent table the next
time the crawler runs.
To specify what the crawler does when it finds a deleted object in the data store, choose one of the
following actions:
When a crawler runs, new tables and partitions are always created regardless of the schema
change policy. You can choose one of the following actions in the UpdateBehavior field in the
SchemaChangePolicy structure to determine what the crawler does when it finds a changed table
schema:
• UPDATE_IN_DATABASE – Update the table in the AWS Glue Data Catalog. Add new columns, remove
missing columns, and modify the definitions of existing columns. Remove any metadata that is not set
by the crawler.
• LOG – Ignore the changes, and don't update the table in the Data Catalog.
You can also override the SchemaChangePolicy structure using a JSON object supplied in the crawler
API Configuration field. This JSON object can contain a key-value pair to set the policy to not update
existing columns and only add new columns. For example, provide the following JSON object as a string:
{
"Version": 1.0,
"CrawlerOutput": {
"Tables": { "AddOrUpdateBehavior": "MergeNewColumns" }
}
122
AWS Glue Developer Guide
Configuring a Crawler
This option corresponds to the Add new columns only option on the AWS Glue console. It overrides
the SchemaChangePolicy structure for tables that result from crawling Amazon S3 data stores only.
Choose this option if you want to maintain the metadata as it exists in the Data Catalog (the source
of truth). New columns are added as they are encountered, including nested data types. But existing
columns are not removed, and their type is not changed. If an Amazon S3 table attribute changes
significantly, mark the table as deprecated, and log a warning that an incompatible attribute needs to be
resolved.
When a crawler runs against a previously crawled data store, it might discover new or changed partitions.
By default, new partitions are added and existing partitions are updated if they have changed. In
addition, you can set a crawler configuration option to InheritFromTable (corresponding to the
Update all new and existing partitions with metadata from the table option on the AWS Glue console).
When this option is set, partitions inherit metadata properties from their parent table, such as their
classification, input format, output format, SerDe information, and schema. Any property changes to the
parent table are propagated to its partitions.
When this configuration option is set on an existing crawler, existing partitions are updated to match
the properties of their parent table the next time the crawler runs. This behavior is set crawler API
Configuration field. For example, provide the following JSON object as a string:
{
"Version": 1.0,
"CrawlerOutput": {
"Partitions": { "AddOrUpdateBehavior": "InheritFromTable" }
}
}
The crawler API Configuration field can set multiple configuration options. For example, to configure
the crawler output for both partitions and tables, you can provide a string representation of the
following JSON object:
{
"Version": 1.0,
"CrawlerOutput": {
"Partitions": { "AddOrUpdateBehavior": "InheritFromTable" },
"Tables": {"AddOrUpdateBehavior": "MergeNewColumns" }
}
}
You can choose one of the following actions to determine what the crawler does when it finds a deleted
object in the data store. The DeleteBehavior field in the SchemaChangePolicy structure in the
crawler API sets the behavior of the crawler when it discovers a deleted object.
123
AWS Glue Developer Guide
Configuring a Crawler
If you don't want a table schema to change at all when a crawler runs, set the schema change policy to
LOG. You can also set a configuration option that sets partition schemas to inherit from the table.
If you are configuring the crawler on the console, you can choose the following actions:
• Ignore the change and don't update the table in the Data Catalog
• Update all new and existing partitions with metadata from the table
When you configure the crawler using the API, set the following parameters:
{
"Version": 1.0,
"CrawlerOutput": {
"Partitions": { "AddOrUpdateBehavior": "InheritFromTable" }
}
}
You can configure a crawler to CombineCompatibleSchemas into a common table definition when
possible. With this option, the crawler still considers data compatibility, but ignores the similarity of the
specific schemas when evaluating Amazon S3 objects in the specified include path.
If you are configuring the crawler on the console, to combine schemas, select the crawler option Create a
single schema for each S3 path.
When you configure the crawler using the API, set the following configuration option:
• Set the Configuration field with a string representation of the following JSON object in the crawler
API; for example:
{
"Version": 1.0,
"Grouping": {
"TableGroupingPolicy": "CombineCompatibleSchemas" }
}
To help illustrate this option, suppose that you define a crawler with an include path s3://bucket/
table1/. When the crawler runs, it finds two JSON files with the following characteristics:
• File 1 – S3://bucket/table1/year=2017/data1.json
• File content – {“A”: 1, “B”: 2}
• Schema – A:int, B:int
124
AWS Glue Developer Guide
Scheduling a Crawler
• File 2 – S3://bucket/table1/year=2018/data2.json
• File content – {“C”: 3, “D”: 4}
• Schema – C: int, D: int
By default, the crawler creates two tables, named year_2017 and year_2018 because the schemas
are not sufficiently similar. However, if the option Create a single schema for each S3 path is
selected, and if the data is compatible, the crawler creates one table. The table has the schema
A:int,B:int,C:int,D:int and partitionKey year:string.
When you create a crawler based on a schedule, you can specify certain constraints, such as the
frequency the crawler runs, which days of the week it runs, and at what time. These constraints are based
on cron. When setting up a crawler schedule, you should consider the features and limitations of cron.
For example, if you choose to run your crawler on day 31 each month, keep in mind that some months
don't have 31 days.
For more information about using cron to schedule jobs and crawlers, see Time-Based Schedules for Jobs
and Crawlers (p. 217).
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/. Choose Crawlers in the navigation pane.
2. Choose Add crawler, and follow the instructions in the Add crawler wizard.
Note
To get step-by-step guidance for adding a crawler, choose Add crawler under Tutorials
in the navigation pane. You can also use the Add crawler wizard to create and modify an
IAM role that attaches a policy that includes permissions for your Amazon Simple Storage
Service (Amazon S3) data stores.
Optionally, you can tag your crawler with a Tag key and optional Tag value. Once created, tag
keys are read-only. Use tags on some resources to help you organize and identify them. For more
information, see AWS Tags in AWS Glue (p. 224).
Optionally, you can add a security configuration to a crawler to specify at-rest encryption options.
When a crawler runs, the provided IAM role must have permission to access the data store that is
crawled. For an Amazon S3 data store, you can use the AWS Glue console to create a policy or add a
policy similar to the following:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
125
AWS Glue Developer Guide
Working with Crawlers on the Console
"Action": [
"s3:GetObject",
"s3:PutObject"
],
"Resource": [
"arn:aws:s3:::bucket/object*"
]
}
]
}
If the crawler reads KMS encrypted Amazon S3 data, then the IAM role must have decrypt permission on
the KMS key. For more information, see Step 2: Create an IAM Role for AWS Glue (p. 14).
For an Amazon DynamoDB data store, you can use the AWS Glue console to create a policy or add a
policy similar to the following:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:DescribeTable",
"dynamodb:Scan"
],
"Resource": [
"arn:aws:dynamodb:region:account-id:table/table-name*"
]
}
]
}
For Amazon S3 data stores, an exclude pattern is relative to the include path. For more information
about glob patterns, see Which Data Stores Can I Crawl? (p. 115).
When you crawl a JDBC data store, a connection is required. For more information, see Working with
Connections on the AWS Glue Console (p. 111). An exclude path is relative to the include path. For
example, to exclude a table in your JDBC data store, type the table name in the exclude path.
When you crawl DynamoDB tables, you can choose one table name from the list of DynamoDB tables in
your account.
To see details of a crawler, choose the crawler name in the list. Crawler details include the information
you defined when you created the crawler with the Add crawler wizard. When a crawler run completes,
choose Tables in the navigation pane to see the tables that were created by your crawler in the database
that you specified.
Note
The crawler assumes the permissions of the IAM role that you specify when you define it. This
IAM role must have permissions to extract data from your data store and write to the Data
Catalog. The AWS Glue console lists only IAM roles that have attached a trust policy for the AWS
126
AWS Glue Developer Guide
Adding Classifiers to a Crawler
Glue principal service. From the console, you can also create an IAM role with an IAM policy to
access Amazon S3 data stores accessed by the crawler. For more information about providing
roles for AWS Glue, see Identity-Based Policies (p. 54).
The following are some important properties and metrics about the last run of a crawler:
Name
You can choose to run your crawler on demand or choose a frequency with a schedule. For more
information about scheduling a crawler, see Scheduling a Crawler (p. 125).
Status
A crawler can be ready, starting, stopping, scheduled, or schedule paused. A running crawler
progresses from starting to stopping. You can resume or pause a schedule attached to a crawler.
Logs
Links to any available logs from the last run of the crawler.
Last runtime
The amount of time it took the crawler to run when it last ran.
Median runtime
The median amount of time it took the crawler to run since it was created.
Tables updated
The number of tables in the AWS Glue Data Catalog that were updated by the latest run of the
crawler.
Tables added
The number of tables that were added into the AWS Glue Data Catalog by the latest run of the
crawler.
AWS Glue provides a set of built-in classifiers, but you can also create custom classifiers. AWS Glue
invokes custom classifiers first, in the order that you specify in your crawler definition. Depending on
the results that are returned from custom classifiers, AWS Glue might also invoke built-in classifiers. If a
classifier returns certainty=1.0 during processing, it indicates that it's 100 percent certain that it can
create the correct schema. AWS Glue then uses the output of that classifier.
If no classifier returns certainty=1.0, AWS Glue uses the output of the classifier that has the highest
certainty. If no classifier returns a certainty greater than 0.0, AWS Glue returns the default classification
string of UNKNOWN.
127
AWS Glue Developer Guide
Custom Classifiers
not 100 percent certain, the crawler invokes the next classifier in the list to determine whether it can
recognize the data.
For more information about creating a classifier using the AWS Glue console, see Working with Classifiers
on the AWS Glue Console (p. 141).
Custom Classifiers
The output of a classifier includes a string that indicates the file's classification or format (for example,
json) and the schema of the file. For custom classifiers, you define the logic for creating the schema
based on the type of classifier. Classifier types include defining schemas based on grok patterns, XML
tags, and JSON paths.
If you change a classifier definition, any data that was previously crawled using the classifier is not
reclassified. A crawler keeps track of previously crawled data. New data is classified with the updated
classifier, which might result in an updated schema. If the schema of your data has evolved, update the
classifier to account for any schema changes when your crawler runs. To reclassify data to correct an
incorrect classifier, create a new crawler with the updated classifier.
For more information about creating custom classifiers in AWS Glue, see Writing Custom
Classifiers (p. 130).
Note
If your data format is recognized by one of the built-in classifiers, you don't need to create a
custom classifier.
If AWS Glue doesn't find a custom classifier that fits the input data format with 100 percent certainty, it
invokes the built-in classifiers in the order shown in the following table. The built-in classifiers return a
result to indicate whether the format matches (certainty=1.0) or does not match (certainty=0.0).
The first classifier that has certainty=1.0 provides the classification string and schema for a metadata
table in your Data Catalog.
Apache Avro avro Reads the schema at the beginning of the file to
determine format.
Apache Parquet parquet Reads the schema at the end of the file to determine
format.
Binary JSON bson Reads the beginning of the file to determine format.
128
AWS Glue Developer Guide
Built-In Classifiers in AWS Glue
Amazon Ion ion Reads the beginning of the file to determine format.
Linux kernel log linux_kernel Determines log formats through a grok pattern.
Ruby log ruby_logger Reads the beginning of the file to determine format.
Squid 3.x log squid Reads the beginning of the file to determine format.
Redis monitor log redismonlog Reads the beginning of the file to determine format.
Redis log redislog Reads the beginning of the file to determine format.
CSV csv Checks for the following delimiters: comma (,), pipe (|),
tab (\t), semicolon (;), and Ctrl-A (\u0001). Ctrl-A is the
Unicode control character for Start Of Heading.
• ZIP (supported for archives containing only a single file). Note that Zip is not well-supported in other
services (because of the archive).
• BZIP
• GZIP
• LZ4
• Snappy (as standard Snappy format, not as Hadoop native Snappy format)
• Comma (,)
• Pipe (|)
• Tab (\t)
• Semicolon (;)
• Ctrl-A (\u0001)
129
AWS Glue Developer Guide
Writing Custom Classifiers
To be classified as CSV, the table schema must have at least two columns and two rows of data. The
CSV classifier uses a number of heuristics to determine whether a header is present in a given file. If the
classifier can't determine a header from the first row of data, column headers are displayed as col1,
col2, col3, and so on. The built-in CSV classifier determines whether to infer a header by evaluating the
following characteristics of the file:
Note
If the built-in CSV classifier does not create your AWS Glue table as you want, you might be able
to use one of the following alternatives:
• Change the column names in the Data Catalog, set the SchemaChangePolicy to LOG, and
set the partition output configuration to InheritFromTable for future crawler runs.
• Create a custom grok classifier to parse the data and assign the columns that you want.
• The built-in CSV classifier creates tables referencing the LazySimpleSerDe as the
serialization library, which is a good choice for type inference. However, if the CSV
data contains quoted strings, edit the table definition and change the SerDe library to
OpenCSVSerDe. Adjust any inferred types to STRING, set the SchemaChangePolicy to LOG,
and set the partitions output configuration to InheritFromTable for future crawler runs.
For more information about SerDe libraries, see SerDe Reference in the Amazon Athena User
Guide.
For more information about creating a classifier using the AWS Glue console, see Working with Classifiers
on the AWS Glue Console (p. 141).
AWS Glue runs custom classifiers before built-in classifiers, in the order you specify. When a crawler finds
a classifier that matches the data, the classification string and schema are used in the definition of tables
that are written to your AWS Glue Data Catalog.
Topics
• Writing Grok Custom Classifiers (p. 131)
• Writing XML Custom Classifiers (p. 134)
• Writing JSON Custom Classifiers (p. 135)
• Writing CSV Custom Classifiers (p. 140)
130
AWS Glue Developer Guide
Writing Custom Classifiers
AWS Glue provides many built-in patterns, or you can define your own. You can create a grok pattern
using built-in patterns and custom patterns in your custom classifier definition. You can tailor a grok
pattern to classify custom text file formats.
Note
AWS Glue grok custom classifiers use the GrokSerDe serialization library for tables created
in the AWS Glue Data Catalog. If you are using the AWS Glue Data Catalog with Amazon
Athena, Amazon EMR, or Redshift Spectrum, check the documentation about those services
for information about support of the GrokSerDe. Currently, you might encounter problems
querying tables created with the GrokSerDe from Amazon EMR and Redshift Spectrum.
The following is the basic syntax for the components of a grok pattern:
%{PATTERN:field-name}
Data that matches the named PATTERN is mapped to the field-name column in the schema, with
a default data type of string. Optionally, the data type for the field can be cast to byte, boolean,
double, short, int, long, or float in the resulting schema.
%{PATTERN:field-name:data-type}
For example, to cast a num field to an int data type, you can use this pattern:
%{NUMBER:num:int}
Patterns can be composed of other patterns. For example, you can have a pattern for a SYSLOG
timestamp that is defined by patterns for month, day of the month, and time (for example, Feb 1
06:25:43). For this data, you might define the following pattern:
Note
Grok patterns can process only one line at a time. Multiple-line patterns are not supported. Also,
line breaks within a pattern are not supported.
Name
The text string that is written to describe the format of the data that is classified; for example,
special-logs.
131
AWS Glue Developer Guide
Writing Custom Classifiers
Grok pattern
The set of patterns that are applied to the data store to determine whether there is a match. These
patterns are from AWS Glue built-in patterns (p. 132) and any custom patterns that you define.
%{TIMESTAMP_ISO8601:timestamp} \[%{MESSAGEPREFIX:message_prefix}\]
%{CRAWLERLOGLEVEL:loglevel} : %{GREEDYDATA:message}
When the data matches TIMESTAMP_ISO8601, a schema column timestamp is created. The
behavior is similar for the other named patterns in the example.
Custom patterns
Optional custom patterns that you define. These patterns are referenced by the grok pattern that
classifies your data. You can reference these custom patterns in the grok pattern that is applied to
your data. Each custom component pattern must be on a separate line. Regular expression (regex)
syntax is used to define the pattern.
CRAWLERLOGLEVEL (BENCHMARK|ERROR|WARN|INFO|TRACE)
MESSAGEPREFIX .*-.*-.*-.*-.*
The first custom named pattern, CRAWLERLOGLEVEL, is a match when the data matches one of the
enumerated strings. The second custom pattern, MESSAGEPREFIX, tries to match a message prefix
string.
AWS Glue keeps track of the creation time, last update time, and version of your classifier.
The following list consists of a line for each pattern. In each line, the pattern name is followed its
definition. Regular expression (regex) syntax is used in defining the pattern.
POSINT \b(?:[1-9][0-9]*)\b
NONNEGINT \b(?:[0-9]+)\b
WORD \b\w+\b
NOTSPACE \S+
SPACE \s*
DATA .*?
GREEDYDATA .*
#QUOTEDSTRING (?:(?<!\\)(?:"(?:\\.|[^\\"])*"|(?:'(?:\\.|[^\\'])*')|(?:`(?:\\.|[^\\`])*`)))
132
AWS Glue Developer Guide
Writing Custom Classifiers
QUOTEDSTRING (?>(?<!\\)(?>"(?>\\.|[^\\"]+)+"|""|(?>'(?>\\.|[^\\']+)+')|''|(?>`(?>\\.|[^\
\`]+)+`)|``))
UUID [A-Fa-f0-9]{8}-(?:[A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}
# Networking
MAC (?:%{CISCOMAC:UNWANTED}|%{WINDOWSMAC:UNWANTED}|%{COMMONMAC:UNWANTED})
CISCOMAC (?:(?:[A-Fa-f0-9]{4}\.){2}[A-Fa-f0-9]{4})
WINDOWSMAC (?:(?:[A-Fa-f0-9]{2}-){5}[A-Fa-f0-9]{2})
COMMONMAC (?:(?:[A-Fa-f0-9]{2}:){5}[A-Fa-f0-9]{2})
IPV6 ((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-
f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|
(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.
(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4})
{1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|
[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4})
{0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|
(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|
2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:)
{1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?
\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-
Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d))
{3}))|:)))(%.+)?
IPV4 (?<![0-9])(?:(?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?
[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]{1,2})[.](?:25[0-5]|2[0-4][0-9]|[0-1]?[0-9]
{1,2}))(?![0-9])
IP (?:%{IPV6:UNWANTED}|%{IPV4:UNWANTED})
HOSTNAME \b(?:[0-9A-Za-z][0-9A-Za-z-_]{0,62})(?:\.(?:[0-9A-Za-z][0-9A-Za-z-_]
{0,62}))*(\.?|\b)
HOST %{HOSTNAME:UNWANTED}
IPORHOST (?:%{HOSTNAME:UNWANTED}|%{IP:UNWANTED})
HOSTPORT (?:%{IPORHOST}:%{POSINT:PORT})
# paths
PATH (?:%{UNIXPATH}|%{WINPATH})
UNIXPATH (?>/(?>[\w_%!$@:.,~-]+|\\.)*)+
#UNIXPATH (?<![\w\/])(?:/[^\/\s?*]*)+
TTY (?:/dev/(pts|tty([pq])?)(\w+)?/?(?:[0-9]+))
WINPATH (?>[A-Za-z]+:|\\)(?:\\[^\\?*]*)+
URIPROTO [A-Za-z]+(\+[A-Za-z+]+)?
URIHOST %{IPORHOST}(?::%{POSINT:port})?
# uripath comes loosely from RFC1738, but mostly from what Firefox
# doesn't turn into %XX
URIPATH (?:/[A-Za-z0-9$.+!*'(){},~:;=@#%_\-]*)+
#URIPARAM \?(?:[A-Za-z0-9]+(?:=(?:[^&]*))?(?:&(?:[A-Za-z0-9]+(?:=(?:[^&]*))?)?)*)?
URIPARAM \?[A-Za-z0-9$.+!*'|(){},~@#%&/=:;_?\-\[\]]*
URIPATHPARAM %{URIPATH}(?:%{URIPARAM})?
URI %{URIPROTO}://(?:%{USER}(?::[^@]*)?@)?(?:%{URIHOST})?(?:%{URIPATHPARAM})?
# Years?
YEAR (?>\d\d){1,2}
# Time: HH:MM:SS
#TIME \d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?
# TIME %{POSINT<24}:%{POSINT<60}(?::%{POSINT<60}(?:\.%{POSINT})?)?
HOUR (?:2[0123]|[01]?[0-9])
MINUTE (?:[0-5][0-9])
133
AWS Glue Developer Guide
Writing Custom Classifiers
# Shortcuts
QS %{QUOTEDSTRING:UNWANTED}
# Log formats
SYSLOGBASE %{SYSLOGTIMESTAMP:timestamp} (?:%{SYSLOGFACILITY} )?%{SYSLOGHOST:logsource}
%{SYSLOGPROG}:
# Log Levels
LOGLEVEL ([A|a]lert|ALERT|[T|t]race|TRACE|[D|d]ebug|DEBUG|[N|n]otice|NOTICE|[I|i]nfo|
INFO|[W|w]arn?(?:ing)?|WARN?(?:ING)?|[E|e]rr?(?:or)?|ERR?(?:OR)?|[C|c]rit?(?:ical)?|CRIT?
(?:ICAL)?|[F|f]atal|FATAL|[S|s]evere|SEVERE|EMERG(?:ENCY)?|[Ee]merg(?:ency)?)
Name
134
AWS Glue Developer Guide
Writing Custom Classifiers
Row tag
The XML tag name that defines a table row in the XML document, without angle brackets < >. The
name must comply with XML rules for a tag.
Note
The element containing the row data cannot be a self-closing empty element. For example,
this empty element is not parsed by AWS Glue:
AWS Glue keeps track of the creation time, last update time, and version of your classifier.
For example, suppose that you have the following XML file. To create an AWS Glue table that only
contains columns for author and title, create a classifier in the AWS Glue console with Row tag as
AnyCompany. Then add and run a crawler that uses this custom classifier.
<?xml version="1.0"?>
<catalog>
<book id="bk101">
<AnyCompany>
<author>Rivera, Martha</author>
<title>AnyCompany Developer Guide</title>
</AnyCompany>
</book>
<book id="bk102">
<AnyCompany>
<author>Stiles, John</author>
<title>Style Guide for AnyCompany</title>
</AnyCompany>
</book>
</catalog>
Name
A JSON path that points to an object that is used to define a table schema. The JSON path can be
written in dot notation or bracket notation. The following operators are supported:
135
AWS Glue Developer Guide
Writing Custom Classifiers
Operator
Description
*Wildcard character. Available anywhere a name or numeric are required in the JSON path.
Bracket-notated child. Specifies child field in a JSON object. Only a single child field can be
['<name>']
specified.
AWS Glue keeps track of the creation time, last update time, and version of your classifier.
Suppose that your JSON data is an array of records. For example, the first few lines of your file might
look like the following:
[
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:ak",
"name": "Alaska"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:al\/cd:1",
"name": "Alabama's 1st congressional district"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:al\/cd:2",
"name": "Alabama's 2nd congressional district"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:al\/cd:3",
"name": "Alabama's 3rd congressional district"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:al\/cd:4",
"name": "Alabama's 4th congressional district"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:al\/cd:5",
"name": "Alabama's 5th congressional district"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:al\/cd:6",
"name": "Alabama's 6th congressional district"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:al\/cd:7",
"name": "Alabama's 7th congressional district"
},
136
AWS Glue Developer Guide
Writing Custom Classifiers
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:ar\/cd:1",
"name": "Arkansas's 1st congressional district"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:ar\/cd:2",
"name": "Arkansas's 2nd congressional district"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:ar\/cd:3",
"name": "Arkansas's 3rd congressional district"
},
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:ar\/cd:4",
"name": "Arkansas's 4th congressional district"
}
]
When you run a crawler using the built-in JSON classifier, the entire file is used to define the schema.
Because you don’t specify a JSON path, the crawler treats the data as one object, that is, just an array.
For example, the schema might look like the following:
root
|-- record: array
However, to create a schema that is based on each record in the JSON array, create a custom JSON
classifier and specify the JSON path as $[*]. When you specify this JSON path, the classifier interrogates
all 12 records in the array to determine the schema. The resulting schema contains separate fields for
each object, similar to the following example:
root
|-- type: string
|-- id: string
|-- name: string
{
"type": "constituency",
"id": "ocd-division\/country:us\/state:ak",
"name": "Alaska"
}
{
"type": "constituency",
"identifiers": [
{
"scheme": "dmoz",
"identifier": "Regional\/North_America\/United_States\/Alaska\/"
},
{
"scheme": "freebase",
137
AWS Glue Developer Guide
Writing Custom Classifiers
"identifier": "\/m\/0hjy"
},
{
"scheme": "fips",
"identifier": "US02"
},
{
"scheme": "quora",
"identifier": "Alaska-state"
},
{
"scheme": "britannica",
"identifier": "place\/Alaska"
},
{
"scheme": "wikidata",
"identifier": "Q797"
}
],
"other_names": [
{
"lang": "en",
"note": "multilingual",
"name": "Alaska"
},
{
"lang": "fr",
"note": "multilingual",
"name": "Alaska"
},
{
"lang": "nov",
"note": "multilingual",
"name": "Alaska"
}
],
"id": "ocd-division\/country:us\/state:ak",
"name": "Alaska"
}
When you run a crawler using the built-in JSON classifier, the entire file is used to create the schema. You
might end up with a schema like this:
root
|-- type: string
|-- id: string
|-- name: string
|-- identifiers: array
| |-- element: struct
| | |-- scheme: string
| | |-- identifier: string
|-- other_names: array
| |-- element: struct
| | |-- lang: string
| | |-- note: string
| | |-- name: string
However, to create a schema using just the "id" object, create a custom JSON classifier and specify the
JSON path as $.id. Then the schema is based on only the "id" field:
138
AWS Glue Developer Guide
Writing Custom Classifiers
root
|-- record: string
The first few lines of data extracted with this schema look like this:
{"record": "ocd-division/country:us/state:ak"}
{"record": "ocd-division/country:us/state:al/cd:1"}
{"record": "ocd-division/country:us/state:al/cd:2"}
{"record": "ocd-division/country:us/state:al/cd:3"}
{"record": "ocd-division/country:us/state:al/cd:4"}
{"record": "ocd-division/country:us/state:al/cd:5"}
{"record": "ocd-division/country:us/state:al/cd:6"}
{"record": "ocd-division/country:us/state:al/cd:7"}
{"record": "ocd-division/country:us/state:ar/cd:1"}
{"record": "ocd-division/country:us/state:ar/cd:2"}
{"record": "ocd-division/country:us/state:ar/cd:3"}
{"record": "ocd-division/country:us/state:ar/cd:4"}
{"record": "ocd-division/country:us/state:as"}
{"record": "ocd-division/country:us/state:az/cd:1"}
{"record": "ocd-division/country:us/state:az/cd:2"}
{"record": "ocd-division/country:us/state:az/cd:3"}
{"record": "ocd-division/country:us/state:az/cd:4"}
{"record": "ocd-division/country:us/state:az/cd:5"}
{"record": "ocd-division/country:us/state:az/cd:6"}
{"record": "ocd-division/country:us/state:az/cd:7"}
To create a schema based on a deeply nested object, such as "identifier," in the JSON file, you can
create a custom JSON classifier and specify the JSON path as $.identifiers[*].identifier.
Although the schema is similar to the previous example, it is based on a different object in the JSON file.
root
|-- record: string
Listing the first few lines of data from the table shows that the schema is based on the data in the
"identifier" object:
{"record": "Regional/North_America/United_States/Alaska/"}
{"record": "/m/0hjy"}
{"record": "US02"}
{"record": "5879092"}
{"record": "4001016-8"}
{"record": "destination/alaska"}
{"record": "1116270"}
{"record": "139487266"}
{"record": "n79018447"}
{"record": "01490999-8dec-4129-8254-eef6e80fadc3"}
{"record": "Alaska-state"}
{"record": "place/Alaska"}
{"record": "Q797"}
{"record": "Regional/North_America/United_States/Alabama/"}
{"record": "/m/0gyh"}
{"record": "US01"}
{"record": "4829764"}
{"record": "4084839-5"}
{"record": "161950"}
{"record": "131885589"}
139
AWS Glue Developer Guide
Writing Custom Classifiers
To create a table based on another deeply nested object, such as the "name" field in the "other_names"
array in the JSON file, you can create a custom JSON classifier and specify the JSON path as
$.other_names[*].name. Although the schema is similar to the previous example, it is based on a
different object in the JSON file. The schema looks like the following:
root
|-- record: string
Listing the first few lines of data in the table shows that it is based on the data in the "name" object in
the "other_names" array:
{"record": "Alaska"}
{"record": "Alaska"}
{"record": "######"}
{"record": "Alaska"}
{"record": "Alaska"}
{"record": "Alaska"}
{"record": "Alaska"}
{"record": "Alaska"}
{"record": "Alaska"}
{"record": "######"}
{"record": "######"}
{"record": "######"}
{"record": "Alaska"}
{"record": "Alyaska"}
{"record": "Alaska"}
{"record": "Alaska"}
{"record": "#### ######"}
{"record": "######"}
{"record": "Alaska"}
{"record": "#######"}
Name
A custom symbol to denote what separates each column entry in the row.
Quote symbol
A custom symbol to denote what combines content into a single column value. Must be different
from the column delimiter.
Column headings
Indicates the behavior for how column headings should be detected in the CSV file. If your custom
CSV file has column headings, enter a comma-delimited list of the column headings.
140
AWS Glue Developer Guide
Working with Classifiers on the Console
Specifies whether to trim values before identifying the type of column values.
Classifier
The classifier name. When you create a classifier, you must provide a name for it.
Classification
From the Classifiers list in the AWS Glue console, you can add, edit, and delete classifiers. To see more
details for a classifier, choose the classifier name in the list. Details include the information you defined
when you created the classifier.
To add a classifier in the AWS Glue console, choose Add classifier. When you define a classifier, you
supply values for the following:
Classifier name
For grok classifiers, describe the format or type of data that is classified or provide a custom label.
Grok pattern
For grok classifiers, this is used to parse your data into a structured schema. The grok pattern is
composed of named patterns that describe the format of your data store. You write this grok pattern
using the named built-in patterns provided by AWS Glue and custom patterns you write and include
in the Custom patterns field. Although grok debugger results might not match the results from AWS
Glue exactly, we suggest that you try your pattern using some sample data with a grok debugger.
You can find grok debuggers on the web. The named built-in patterns provided by AWS Glue are
generally compatible with grok patterns that are available on the web.
Build your grok pattern by iteratively adding named patterns and check your results in a debugger.
This activity gives you confidence that when the AWS Glue crawler runs your grok pattern, your data
can be parsed.
Custom patterns
For grok classifiers, these are optional building blocks for the Grok pattern that you write. When
built-in patterns cannot parse your data, you might need to write a custom pattern. These custom
patterns are defined in this field and referenced in the Grok pattern field. Each custom pattern is
defined on a separate line. Just like the built-in patterns, it consists of a named pattern definition
that uses regular expression (regex) syntax.
141
AWS Glue Developer Guide
Working with Data Catalog
Settings on the AWS Glue Console
For example, the following has the name MESSAGEPREFIX followed by a regular expression
definition to apply to your data to determine whether it follows the pattern.
MESSAGEPREFIX .*-.*-.*-.*-.*
Row tag
For XML classifiers, this is the name of the XML tag that defines a table row in the XML document.
Type the name without angle brackets < >. The name must comply with XML rules for a tag.
JSON path
For JSON classifiers, this is the JSON path to the object, array, or value that defines a row of
the table being created. Type the name in either dot or bracket JSON syntax using AWS Glue
supported operators. For more information, see the list of operators in Writing JSON Custom
Classifiers (p. 135).
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. Choose Settings, and then in the Permissions editor, add the policy statement to change fine-
grained access control of the Data Catalog for your account. Only one policy at a time can be
attached to a Data Catalog.
3. Choose Save to update your Data Catalog with any changes you made.
You can also use AWS Glue API operations to put, get, and delete resource policies. For more information,
see Security APIs in AWS Glue (p. 453).
Metadata encryption
Select this check box to encrypt the metadata in your Data Catalog. Metadata is encrypted at rest
using the AWS Key Management Service (AWS KMS) key that you specify.
Encrypt connection passwords
Select this check box to encrypt passwords in the AWS Glue connection object when the connection
is created or updated. Passwords are encrypted using the AWS KMS key that you specify. When
passwords are returned, they are encrypted. This option is a global setting for all AWS Glue
connections in the Data Catalog. If you clear this check box, previously encrypted passwords remain
encrypted using the key that was used when they were created or updated. For more information
about AWS Glue connections, see Adding a Connection to Your Data Store (p. 109).
When you enable this option, choose an AWS KMS key, or choose Enter a key ARN
and provide the Amazon Resource Name (ARN) for the key. Enter the ARN in the form
142
AWS Glue Developer Guide
Populating the Data Catalog Using
AWS CloudFormation Templates
Add a resource policy to define fine-grained access control of the Data Catalog. You can paste a
JSON resource policy into this control. For more information, see Resource Policies (p. 58).
For more information, see What Is AWS CloudFormation? and Working with AWS CloudFormation
Templates in the AWS CloudFormation User Guide.
If you plan to use AWS CloudFormation templates that are compatible with AWS Glue, as an
administrator, you must grant access to AWS CloudFormation and to the AWS services and actions on
which it depends. To grant permissions to create AWS CloudFormation resources, attach the following
policy to the IAM users that work with AWS CloudFormation:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"cloudformation:*"
],
"Resource": "*"
}
]
}
The following table contains the actions that an AWS CloudFormation template can perform on your
behalf. It includes links to information about the AWS resource types and their property types that you
can add to an AWS CloudFormation template.
143
AWS Glue Developer Guide
Sample Database
To get started, use the following sample templates and customize them with your own metadata. Then
use the AWS CloudFormation console to create an AWS CloudFormation stack to add objects to AWS
Glue and any associated services. Many fields in an AWS Glue object are optional. These templates
illustrate the fields that are required or are necessary for a working and functional AWS Glue object.
An AWS CloudFormation template can be in either JSON or YAML format. In these examples, YAML is
used for easier readability. The examples contain comments (#) to describe the values that are defined in
the templates.
AWS CloudFormation templates can include a Parameters section. This section can be changed in
the sample text or when the YAML file is submitted to the AWS CloudFormation console to create a
stack. The Resources section of the template contains the definition of AWS Glue and related objects.
AWS CloudFormation template syntax definitions might contain properties that include more detailed
property syntax. Not all properties might be required to create an AWS Glue object. These samples show
example values for common properties to create an AWS Glue object.
The following shows example values for common properties to create an AWS Glue database. For more
information about the AWS CloudFormation database template for AWS Glue, see AWS::Glue::Database.
---
AWSTemplateFormatVersion: '2010-09-09'
144
AWS Glue Developer Guide
Sample Database, Table, Partitions
The following sample shows how to populate a database, a table, and partitions using an AWS
CloudFormation template. The base data format is csv and delimited by a comma (,). Because a
database must exist before it can contain a table, and a table must exist before partitions can be created,
the template uses the DependsOn statement to define the dependency of these objects when they are
created.
The values in this sample define a table that contains flight data from a publicly available Amazon
S3 bucket. For illustration, only a few columns of the data and one partitioning key are defined. Four
partitions are also defined in the Data Catalog. Some fields to describe the storage of the base data are
also shown in the StorageDescriptor fields.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CloudFormation template in YAML to demonstrate creating a database, a table, and
partitions
# The metadata created in the Data Catalog points to the flights public S3 bucket
#
# Parameters substituted in the Resources section
# These parameters are names of the resources created in the Data Catalog
Parameters:
CFNDatabaseName:
Type: String
Default: cfn-database-flights-1
CFNTableName1:
Type: String
145
AWS Glue Developer Guide
Sample Database, Table, Partitions
Default: cfn-manual-table-flights-1
# Resources to create metadata in the Data Catalog
Resources:
###
# Create an AWS Glue database
CFNDatabaseFlights:
Type: AWS::Glue::Database
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseInput:
Name: !Ref CFNDatabaseName
Description: Database to hold tables for flights data
###
# Create an AWS Glue table
CFNTableFlights:
# Creating the table waits for the database to be created
DependsOn: CFNDatabaseFlights
Type: AWS::Glue::Table
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseName: !Ref CFNDatabaseName
TableInput:
Name: !Ref CFNTableName1
Description: Define the first few columns of the flights table
TableType: EXTERNAL_TABLE
Parameters: {
"classification": "csv"
}
# ViewExpandedText: String
PartitionKeys:
# Data is partitioned by month
- Name: mon
Type: bigint
StorageDescriptor:
OutputFormat: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
Columns:
- Name: year
Type: bigint
- Name: quarter
Type: bigint
- Name: month
Type: bigint
- Name: day_of_month
Type: bigint
InputFormat: org.apache.hadoop.mapred.TextInputFormat
Location: s3://crawler-public-us-east-1/flight/2016/csv/
SerdeInfo:
Parameters:
field.delim: ","
SerializationLibrary: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
# Partition 1
# Create an AWS Glue partition
CFNPartitionMon1:
DependsOn: CFNTableFlights
Type: AWS::Glue::Partition
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseName: !Ref CFNDatabaseName
TableName: !Ref CFNTableName1
PartitionInput:
Values:
- 1
StorageDescriptor:
OutputFormat: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
Columns:
- Name: mon
146
AWS Glue Developer Guide
Sample Database, Table, Partitions
Type: bigint
InputFormat: org.apache.hadoop.mapred.TextInputFormat
Location: s3://crawler-public-us-east-1/flight/2016/csv/mon=1/
SerdeInfo:
Parameters:
field.delim: ","
SerializationLibrary: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
# Partition 2
# Create an AWS Glue partition
CFNPartitionMon2:
DependsOn: CFNTableFlights
Type: AWS::Glue::Partition
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseName: !Ref CFNDatabaseName
TableName: !Ref CFNTableName1
PartitionInput:
Values:
- 2
StorageDescriptor:
OutputFormat: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
Columns:
- Name: mon
Type: bigint
InputFormat: org.apache.hadoop.mapred.TextInputFormat
Location: s3://crawler-public-us-east-1/flight/2016/csv/mon=2/
SerdeInfo:
Parameters:
field.delim: ","
SerializationLibrary: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
# Partition 3
# Create an AWS Glue partition
CFNPartitionMon3:
DependsOn: CFNTableFlights
Type: AWS::Glue::Partition
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseName: !Ref CFNDatabaseName
TableName: !Ref CFNTableName1
PartitionInput:
Values:
- 3
StorageDescriptor:
OutputFormat: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
Columns:
- Name: mon
Type: bigint
InputFormat: org.apache.hadoop.mapred.TextInputFormat
Location: s3://crawler-public-us-east-1/flight/2016/csv/mon=3/
SerdeInfo:
Parameters:
field.delim: ","
SerializationLibrary: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
# Partition 4
# Create an AWS Glue partition
CFNPartitionMon4:
DependsOn: CFNTableFlights
Type: AWS::Glue::Partition
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseName: !Ref CFNDatabaseName
TableName: !Ref CFNTableName1
PartitionInput:
Values:
- 4
StorageDescriptor:
147
AWS Glue Developer Guide
Sample Grok Classifier
OutputFormat: org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat
Columns:
- Name: mon
Type: bigint
InputFormat: org.apache.hadoop.mapred.TextInputFormat
Location: s3://crawler-public-us-east-1/flight/2016/csv/mon=4/
SerdeInfo:
Parameters:
field.delim: ","
SerializationLibrary: org.apache.hadoop.hive.serde2.lazy.LazySimpleSerDe
This sample creates a classifier that creates a schema with one column named message and sets the
classification to greedy.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a classifier
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
#
#
# Resources section defines metadata for the Data Catalog
Resources:
# Create classifier that uses grok pattern to put all data in one column and classifies it
as "greedy".
CFNClassifierFlights:
Type: AWS::Glue::Classifier
Properties:
GrokClassifier:
#Grok classifier that puts all data in one column
Name: !Ref CFNClassifierName
Classification: greedy
GrokPattern: "%{GREEDYDATA:message}"
#CustomPatterns: none
If the pattern matches, then the custom classifier is used to create your table's schema.
148
AWS Glue Developer Guide
Sample XML Classifier
This sample creates a classifier that creates a schema with each record in the Records3 array in an
object.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a JSON classifier
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
#
#
# Resources section defines metadata for the Data Catalog
Resources:
# Create classifier that uses a JSON pattern.
CFNClassifierFlights:
Type: AWS::Glue::Classifier
Properties:
JSONClassifier:
#JSON classifier
Name: !Ref CFNClassifierName
JsonPath: $.Records3[*]
This sample creates a classifier that creates a schema with each record in the Record tag and sets the
classification to XML.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating an XML classifier
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
#
#
# Resources section defines metadata for the Data Catalog
Resources:
# Create classifier that uses the XML pattern and classifies it as "XML".
CFNClassifierFlights:
149
AWS Glue Developer Guide
Sample Amazon S3 Crawler
Type: AWS::Glue::Classifier
Properties:
XMLClassifier:
#XML classifier
Name: !Ref CFNClassifierName
Classification: XML
RowTag: <Records>
This sample creates a crawler, the required IAM role, and an AWS Glue database in the Data Catalog.
When this crawler is run, it assumes the IAM role and creates a table in the database for the public flights
data. The table is created with the prefix "cfn_sample_1_". The IAM role created by this template
allows global permissions; you might want to create a custom role. No custom classifiers are defined by
this classifier. AWS Glue built-in classifiers are used by default.
When you submit this sample to the AWS CloudFormation console, you must confirm that you want to
create the IAM role.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a crawler
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
150
AWS Glue Developer Guide
Sample Connection
Path: "/"
Policies:
-
PolicyName: "root"
PolicyDocument:
Version: "2012-10-17"
Statement:
-
Effect: "Allow"
Action: "*"
Resource: "*"
# Create a database to contain tables created by the crawler
CFNDatabaseFlights:
Type: AWS::Glue::Database
Properties:
CatalogId: !Ref AWS::AccountId
DatabaseInput:
Name: !Ref CFNDatabaseName
Description: "AWS Glue container to hold metadata tables for the flights crawler"
#Create a crawler to crawl the flights data on a public S3 bucket
CFNCrawlerFlights:
Type: AWS::Glue::Crawler
Properties:
Name: !Ref CFNCrawlerName
Role: !GetAtt CFNRoleFlights.Arn
#Classifiers: none, use the default classifier
Description: AWS Glue crawler to crawl flights data
#Schedule: none, use default run-on-demand
DatabaseName: !Ref CFNDatabaseName
Targets:
S3Targets:
# Public S3 bucket with the flights data
- Path: "s3://crawler-public-us-east-1/flight/2016/csv"
TablePrefix: !Ref CFNTablePrefixName
SchemaChangePolicy:
UpdateBehavior: "UPDATE_IN_DATABASE"
DeleteBehavior: "LOG"
Configuration: "{\"Version\":1.0,\"CrawlerOutput\":{\"Partitions\":
{\"AddOrUpdateBehavior\":\"InheritFromTable\"},\"Tables\":{\"AddOrUpdateBehavior\":
\"MergeNewColumns\"}}}"
This sample creates a connection to an Amazon RDS MySQL database named devdb. When this
connection is used, an IAM role, database credentials, and network connection values must also be
supplied. See the details of necessary fields in the template.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a connection
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
151
AWS Glue Developer Guide
Sample JDBC Crawler
CFNConnectionName:
Type: String
Default: cfn-connection-mysql-flights-1
CFNJDBCString:
Type: String
Default: "jdbc:mysql://xxx-mysql.yyyyyyyyyyyyyy.us-east-1.rds.amazonaws.com:3306/devdb"
CFNJDBCUser:
Type: String
Default: "master"
CFNJDBCPassword:
Type: String
Default: "12345678"
NoEcho: true
#
#
# Resources section defines metadata for the Data Catalog
Resources:
CFNConnectionMySQL:
Type: AWS::Glue::Connection
Properties:
CatalogId: !Ref AWS::AccountId
ConnectionInput:
Description: "Connect to MySQL database."
ConnectionType: "JDBC"
#MatchCriteria: none
PhysicalConnectionRequirements:
AvailabilityZone: "us-east-1d"
SecurityGroupIdList:
- "sg-7d52b812"
SubnetId: "subnet-84f326ee"
ConnectionProperties: {
"JDBC_CONNECTION_URL": !Ref CFNJDBCString,
"USERNAME": !Ref CFNJDBCUser,
"PASSWORD": !Ref CFNJDBCPassword
}
Name: !Ref CFNConnectionName
This sample creates a crawler, required IAM role, and an AWS Glue database in the Data Catalog. When
this crawler is run, it assumes the IAM role and creates a table in the database for the public flights data
that has been stored in a MySQL database. The table is created with the prefix "cfn_jdbc_1_". The
IAM role created by this template allows global permissions; you might want to create a custom role. No
custom classifiers can be defined for JDBC data. AWS Glue built-in classifiers are used by default.
When you submit this sample to the AWS CloudFormation console, you must confirm that you want to
create the IAM role.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a crawler
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
152
AWS Glue Developer Guide
Sample JDBC Crawler
153
AWS Glue Developer Guide
Sample Job for Amazon S3 to Amazon S3
This sample creates a job that reads flight data from an Amazon S3 bucket in csv format and writes it to
an Amazon S3 Parquet file. The script that is run by this job must already exist. You can generate an ETL
script for your environment with the AWS Glue console. When this job is run, an IAM role with the correct
permissions must also be supplied.
Common parameter values are shown in the template. For example, AllocatedCapacity (DPUs)
defaults to 5.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a job using the public flights S3 table in a
public bucket
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
154
AWS Glue Developer Guide
Sample Job for JDBC to Amazon S3
Properties:
Role: !Ref CFNIAMRoleName
#DefaultArguments: JSON object
# If script written in Scala, then set DefaultArguments={'--job-language'; 'scala',
'--class': 'your scala class'}
#Connections: No connection needed for S3 to S3 job
# ConnectionsList
#MaxRetries: Double
Description: Job created with CloudFormation
#LogUri: String
Command:
Name: glueetl
ScriptLocation: !Ref CFNScriptLocation
# for access to directories use proper IAM role with permission to buckets and
folders that begin with "aws-glue-"
# script uses temp directory from job definition if required (temp directory
not used S3 to S3)
# script defines target for output as s3://aws-glue-target/sal
AllocatedCapacity: 5
ExecutionProperty:
MaxConcurrentRuns: 1
Name: !Ref CFNJobName
This sample creates a job that reads flight data from a MySQL JDBC database as defined by the
connection named cfn-connection-mysql-flights-1 and writes it to an Amazon S3 Parquet file.
The script that is run by this job must already exist. You can generate an ETL script for your environment
with the AWS Glue console. When this job is run, an IAM role with the correct permissions must also be
supplied.
Common parameter values are shown in the template. For example, AllocatedCapacity (DPUs)
defaults to 5.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a job using a MySQL JDBC DB with the flights data
to an S3 file
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
155
AWS Glue Developer Guide
Sample On-Demand Trigger
This sample creates an on-demand trigger that starts one job named cfn-job-S3-to-S3-1.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating an on-demand trigger
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
# The existing job to be started by this trigger
CFNJobName:
Type: String
Default: cfn-job-S3-to-S3-1
# The name of the trigger to be created
CFNTriggerName:
Type: String
Default: cfn-trigger-ondemand-flights-1
#
156
AWS Glue Developer Guide
Sample Scheduled Trigger
This sample creates a scheduled trigger that starts one job named cfn-job-S3-to-S3-1. The timer is a
cron expression to run the job every 10 minutes on weekdays.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a scheduled trigger
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
# The existing job to be started by this trigger
CFNJobName:
Type: String
Default: cfn-job-S3-to-S3-1
# The name of the trigger to be created
CFNTriggerName:
Type: String
Default: cfn-trigger-scheduled-flights-1
#
# Resources section defines metadata for the Data Catalog
# Sample CFN YAML to demonstrate creating a scheduled trigger for a job
#
Resources:
# Create trigger to run an existing job (CFNJobName) on a cron schedule.
TriggerSample1CFN:
Type: AWS::Glue::Trigger
Properties:
Name:
Ref: CFNTriggerName
Description: Trigger created with CloudFormation
Type: SCHEDULED
Actions:
- JobName: !Ref CFNJobName
# Arguments: JSON object
# # Run the trigger every 10 minutes on Monday to Friday
Schedule: cron(0/10 * ? * MON-FRI *)
#Predicate:
157
AWS Glue Developer Guide
Sample Conditional Trigger
This sample creates a conditional trigger that starts one job named cfn-job-S3-to-S3-1. This job
starts when the job named cfn-job-S3-to-S3-2 completes successfully.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a conditional trigger for a job, which starts
when another job completes
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
# The existing job to be started by this trigger
CFNJobName:
Type: String
Default: cfn-job-S3-to-S3-1
# The existing job that when it finishes causes trigger to fire
CFNJobName2:
Type: String
Default: cfn-job-S3-to-S3-2
# The name of the trigger to be created
CFNTriggerName:
Type: String
Default: cfn-trigger-conditional-1
#
Resources:
# Create trigger to run an existing job (CFNJobName) when another job completes
(CFNJobName2).
CFNTriggerSample:
Type: AWS::Glue::Trigger
Properties:
Name:
Ref: CFNTriggerName
Description: Trigger created with CloudFormation
Type: CONDITIONAL
Actions:
- JobName: !Ref CFNJobName
# Arguments: JSON object
#Schedule: none
Predicate:
#Value for Logical is required if more than 1 job listed in Conditions
Logical: AND
Conditions:
- LogicalOperator: EQUALS
JobName: !Ref CFNJobName2
State: SUCCEEDED
158
AWS Glue Developer Guide
Sample Development Endpoint
This sample creates a development endpoint with the minimal network parameter values required to
successfully create it. For more information about the parameters that you need to set up a development
endpoint, see Setting Up Your Environment for Development Endpoints (p. 34).
You provide an existing IAM role ARN (Amazon Resource Name) to create the development endpoint.
Supply a valid RSA public key and keep the corresponding private key available if you plan to create a
notebook server on the development endpoint.
Note
For any notebook server that you create that is associated with a development endpoint, you
manage it. Therefore, if you delete the development endpoint, to delete the notebook server,
you must delete the AWS CloudFormation stack on the AWS CloudFormation console.
---
AWSTemplateFormatVersion: '2010-09-09'
# Sample CFN YAML to demonstrate creating a development endpoint
#
# Parameters section contains names that are substituted in the Resources section
# These parameters are the names the resources created in the Data Catalog
Parameters:
159
AWS Glue Developer Guide
The following diagram summarizes the basic workflow and steps involved in authoring a job in AWS
Glue:
Topics
• Workflow Overview (p. 161)
• Adding Jobs in AWS Glue (p. 161)
• Editing Scripts in AWS Glue (p. 176)
• Triggering Jobs in AWS Glue (p. 179)
• Developing Scripts Using Development Endpoints (p. 181)
• Managing Notebooks (p. 205)
160
AWS Glue Developer Guide
Workflow Overview
Workflow Overview
When you author a job, you supply details about data sources, targets, and other information. The result
is a generated Apache Spark API (PySpark) script. You can then store your job definition in the AWS Glue
Data Catalog.
The following describes an overall process of authoring jobs in the AWS Glue console:
1. You choose a data source for your job. The tables that represent your data source must already be
defined in your Data Catalog. If the source requires a connection, the connection is also referenced in
your job. If your job requires multiple data sources, you can add them later by editing the script.
2. You choose a data target of your job. The tables that represent the data target can be defined in your
Data Catalog, or your job can create the target tables when it runs. You choose a target location when
you author the job. If the target requires a connection, the connection is also referenced in your job. If
your job requires multiple data targets, you can add them later by editing the script.
3. You customize the job-processing environment by providing arguments for your job and generated
script. For more information, see Adding Jobs in AWS Glue (p. 161).
4. Initially, AWS Glue generates a script, but you can also edit this script to add sources, targets, and
transforms. For more information about transforms, see Built-In Transforms (p. 169).
5. You specify how your job is invoked, either on demand, by a time-based schedule, or by an event. For
more information, see Triggering Jobs in AWS Glue (p. 179).
6. Based on your input, AWS Glue generates a PySpark or Scala script. You can tailor the script based on
your business needs. For more information, see Editing Scripts in AWS Glue (p. 176).
Job runs can be initiated by triggers that start a job when they fire. A job contains a script that connects
to your source data, processes your data using the script's logic, and then writes it out to your data
target. Your job can have multiple data sources and multiple data targets. You can use scripts that are
generated by AWS Glue to transform data, or you can provide your own. The AWS Glue code generator
can automatically create an Apache Spark API (PySpark) script given a source schema and target location
or schema. You can use this script as a starting point and edit it to meet your goals.
AWS Glue can write output files in several data formats, including JSON, CSV, ORC (Optimized Row
Columnar), Apache Parquet, and Apache Avro. For some data formats, common compression formats can
be written.
There are two types of jobs in AWS Glue: Spark and Python shell.
• An Apache Spark ETL job consists of the business logic that performs ETL work in AWS Glue. You can
monitor job runs to understand runtime metrics such as success, duration, and start time. The output
of a job is your transformed data, written to a location that you specify.
• A Python shell job runs Python scripts as a shell. With a Python shell job, you can run scripts that are
compatible with Python 2.7 or Python 3.6. You can use these jobs to schedule and run tasks that don't
require Spark ETL jobs.
161
AWS Glue Developer Guide
Defining Job Properties
Name
Specify the IAM role that is used for authorization to resources used to run the job and access data
stores. For more information about permissions for running jobs in AWS Glue, see Managing Access
Permissions for AWS Glue Resources (p. 51).
Type
Glue version determines the versions of Apache Spark and Python that AWS Glue supports. The
Python version indicates the version supported for jobs of type Spark. The following table lists the
available AWS Glue versions and corresponding Spark and Python versions.
Jobs that were created without specifying a Glue version default to Glue 0.9.
Generated or custom script
The code in the ETL script defines your job's procedural logic. The script can be coded in Python or
Scala. You can choose whether the script that the job runs is generated by AWS Glue or provided
by you. You provide the script name and location in Amazon Simple Storage Service (Amazon S3).
Confirm that there isn't a file with the same name as the script directory in the path. To learn more
about using scripts, see Editing Scripts in AWS Glue (p. 176).
Scala class name
If the script is coded in Scala, you must provide a class name. The default class name for AWS Glue
generated scripts is GlueApp.
Temporary directory
Provide the location of a working directory in Amazon S3 where temporary intermediate results are
written when AWS Glue runs the script. Confirm that there isn't a file with the same name as the
temporary directory in the path. This directory is used when AWS Glue reads and writes to Amazon
Redshift and by certain AWS Glue transforms.
162
AWS Glue Developer Guide
Defining Job Properties
Job bookmark
Specify how AWS Glue processes state information when the job runs. You can have it remember
previously processed data, update state information, or ignore state information.
Job metrics
Enable or disable the creation of Amazon CloudWatch metrics when this job runs. To see profiling
data, you must enable this option. For more information about how to enable and visualize metrics,
see Job Monitoring and Debugging (p. 254).
Tags
Tag your job with a Tag key and an optional Tag value. After tag keys are created, they are read-
only. Use tags on some resources to help you organize and identify them. For more information, see
AWS Tags in AWS Glue (p. 224).
Server-side encryption
If you select this option, when the ETL job writes to Amazon S3, the data is encrypted at rest using
SSE-S3 encryption. Both your Amazon S3 data target and any data that is written to an Amazon
S3 temporary directory is encrypted. For more information, see Protecting Data Using Server-Side
Encryption with Amazon S3-Managed Encryption Keys (SSE-S3).
Important
Currently, a security configuration overrides any server-side encryption (SSE-S3) setting
passed as an ETL job parameter. Thus, if both a security configuration and an SSE-S3
parameter are associated with a job, the SSE-S3 parameter is ignored.
Script libraries
If your script requires it, you can specify locations for the following:
• Python library path
• Dependent jars path
• Referenced files path
You can define the comma-separated Amazon S3 paths for these libraries when you define a job.
You can override these paths when you run the job. For more information, see Providing Your Own
Custom Scripts (p. 178).
Worker type
You are charged an hourly rate based on the number of DPUs used to run your ETL jobs. For more
information, see the AWS Glue pricing page.
When you configure a job using the console and specify a Worker type of Standard, the Maximum
capacity is set and the Number of workers becomes the value of Maximum capacity - 1. If you
163
AWS Glue Developer Guide
Defining Job Properties
use the AWS Command Line Interface (AWS CLI) or AWS SDK, you can specify the Max capacity
parameter, or you can specify both Worker type and the Number of workers. For more information,
see Jobs.
Number of workers
The number of workers of a defined workerType that are allocated when a job runs.
With G.1X and G.2X Worker types, you must specify the number of workers of that type.
The maximum number of workers you can define are 299 for G.1X, and 149 for G.2X.
Maximum capacity
The maximum number of AWS Glue data processing units (DPUs) that can be allocated when this job
runs. A DPU is a relative measure of processing power that consists of 4 vCPUs of compute capacity
and 16 GB of memory. You are charged an hourly rate based on the number of DPUs used to run
your ETL jobs. For more information, see the AWS Glue pricing page.
With the Standard Worker type, you must specify the maximum capacity of the job.
Choose an integer from 2 to 100. The default is 10. This job type cannot have a fractional DPU
allocation.
Max concurrency
Sets the maximum number of concurrent runs that are allowed for this job. The default is 1. An
error is returned when this threshold is reached. The maximum value you can specify is controlled
by a service limit. For example, if a previous run of a job is still running when a new instance is
started, you might want to return an error to prevent two instances of the same job from running
concurrently.
Job timeout
Sets the maximum execution time in minutes. The default is 2880 minutes. If this limit is greater
than the execution time, the job run state changes to “TIMEOUT”.
Delay notification threshold
Sets the threshold (in minutes) before a delay notification is sent. You can set this threshold to
send notifications when a RUNNING, STARTING, or STOPPING job run takes more than an expected
number of minutes.
Number of retries
Specify the number of times, from 0 to 10, that AWS Glue should automatically restart the job if it
fails.
Job parameters
A set of key-value pairs that are passed as named parameters to the script invoked by the job. These
are default values that are used when the script is run, but you can override them at run time. The
key name is prefixed with --, for example --myKey and the value is value-for-myKey.
'--myKey' : 'value-for-myKey'
For more examples, see Python parameters in Passing and Accessing Python Parameters in AWS
Glue (p. 316).
Source
164
AWS Glue Developer Guide
Adding Python Shell Jobs
Target
For Amazon S3 target locations, provide the location of a directory where your output is written.
Confirm that there isn't a file with the same name as the target path directory in the path. For JDBC
targets, AWS Glue creates schema objects as needed if the specified objects do not exist.
Note
Source and target are not listed under the console Details tab for a job. Review the script to see
source and target details.
Enables you to use the AWS Glue Data Catalog as a Spark Hive metastore.
Spark UI
Enable the use of Spark UI for monitoring this job. For more information, see Enabling the Apache
Spark Web UI for AWS Glue Jobs (p. 232).
For more information about adding a job using the AWS Glue console, see Working with Jobs on the AWS
Glue Console (p. 171).
You can't use job bookmarks with Python shell jobs. Most of the other features that are available for
Apache Spark jobs are also available for Python shell jobs.
The Amazon CloudWatch Logs group for Python shell jobs output is /aws-glue/python-jobs/
output. For errors, see the log group /aws-glue/python-jobs/errors.
Topics
• Defining Job Properties for Python Shell Jobs (p. 165)
• Supported Libraries for Python Shell Jobs (p. 166)
• Limitations (p. 167)
• Providing Your Own Python Library (p. 167)
IAM role
Specify the AWS Identity and Access Management (IAM) role that is used for authorization
to resources that are used to run the job and access data stores. For more information about
permissions for running jobs in AWS Glue, see Managing Access Permissions for AWS Glue
Resources (p. 51).
165
AWS Glue Developer Guide
Adding Python Shell Jobs
Type
Choose Python shell to run a Python script with the job command named pythonshell.
Python version
The code in the script defines your job's procedural logic. You provide the script name and location
in Amazon Simple Storage Service (Amazon S3). Confirm that there isn't a file with the same name
as the script directory in the path. To learn more about using scripts, see Editing Scripts in AWS
Glue (p. 176).
An existing or new script
The code in the script defines your job's procedural logic. You can code the script in Python 2.7 or
Python 3.6. You can edit a script on the AWS Glue console, but it is not generated by AWS Glue.
Maximum capacity
The maximum number of AWS Glue data processing units (DPUs) that can be allocated when this job
runs. A DPU is a relative measure of processing power that consists of 4 vCPUs of compute capacity
and 16 GB of memory. For more information, see AWS Glue pricing.
For descriptions of additional properties, see Defining Job Properties (p. 162). For more
information about adding a job using the AWS Glue console, see Working with Jobs on the AWS Glue
Console (p. 171).
You can also create a Python shell job using the AWS CLI, as in the following example.
Jobs that you create with the AWS CLI default to Python 2. To specify Python 3, add this tuple to the --
command parameter:
"PythonVersion":"3"
To set the maximum capacity used by a Python shell job, provide the --max-capacity parameter. For
Python shell jobs, the --allocated-capacity parameter can't be used.
• Boto3
• collections
• CSV
• gzip
• multiprocessing
• NumPy
166
AWS Glue Developer Guide
Adding Python Shell Jobs
You can use the NumPy library in a Python shell job for scientific computing. For more information, see
NumPy. The following example shows a NumPy script that can be used in a Python shell job. The script
prints "Hello world" and the results of several mathematical calculations.
import numpy as np
print("Hello world")
a = np.array([20,30,40,50])
print(a)
b = np.arange( 4 )
print(b)
c = a-b
print(c)
d = b**2
print(d)
Limitations
Note the following limitations on packaging your Python libraries:
• Creating an .egg file on Windows 10 Pro using Python 3.7 is not supported.
• Creating an .egg file on WSL (Windows Linux Subsystem, hosted by Windows 10 Pro) using Python
3.6 is supported.
167
AWS Glue Developer Guide
Adding Python Shell Jobs
If you aren't sure how to create an .egg or a .whl file from a Python library, use the following steps.
This example is applicable on macOS, Linux, and Windows Subsystem for Linux (WSL).
1. Create an Amazon Redshift cluster in a virtual private cloud (VPC), and add some data to a table.
2. Create an AWS Glue connection for the VPC-SecurityGroup-Subnet combination that you used to
create the cluster. Test that the connection is successful.
3. Create a directory named redshift_example, and create a file named setup.py. Paste the
following code into setup.py.
setup(
name="redshift_module",
version="0.1",
packages=['redshift_module']
)
import pg
def get_connection(host):
rs_conn_string = "host=%s port=%s dbname=%s user=%s password=%s" % (
host, port, db_name, user, password_for_user)
rs_conn = pg.connect(dbname=rs_conn_string)
rs_conn.query("set statement_timeout = 1200000")
return rs_conn
def query(con):
statement = "Select * from table_name;"
res = con.query(statement)
return res
8. Install the dependencies that are required for the preceding command.
9. The command creates a file in the dist directory:
168
AWS Glue Developer Guide
Built-In Transforms
con1 = rs_common.get_connection(redshift_endpoint)
res = rs_common.query(con1)
print res
11. Upload the preceding file to Amazon S3. In this example, the uploaded file path is s3://
MyBucket/python/library/redshift_test.py.
12. Create a Python shell job using this script. On the AWS Glue console, on the Job properties page,
specify the path to the .egg/.whl file in the Python library path box. If you have multiple
.egg/.whl files and Python files, provide a comma-separated list in this box.
Using the AWS CLI, create a job with a command, as in the following example.
When the job runs, the script prints the rows created in the table_name table in the Amazon
Redshift cluster.
Built-In Transforms
AWS Glue provides a set of built-in transforms that you can use to process your data. You can call these
transforms from your ETL script. Your data passes from transform to transform in a data structure
called a DynamicFrame, which is an extension to an Apache Spark SQL DataFrame. The DynamicFrame
contains your data, and you reference its schema to process your data. For more information about these
transforms, see AWS Glue PySpark Transforms Reference (p. 357).
ApplyMapping
Maps source columns and data types from a DynamicFrame to target columns and data types in a
returned DynamicFrame. You specify the mapping argument, which is a list of tuples that contain
source column, source type, target column, and target type.
DropFields
Removes a field from a DynamicFrame. The output DynamicFrame contains fewer fields than the
input. You specify which fields to remove using the paths argument. The paths argument points
169
AWS Glue Developer Guide
Built-In Transforms
to a field in the schema tree structure using dot notation. For example, to remove field B, which is a
child of field A in the tree, type A.B for the path.
DropNullFields
Removes null fields from a DynamicFrame. The output DynamicFrame does not contain fields of
the null type in the schema.
Filter
Selects records from a DynamicFrame and returns a filtered DynamicFrame. You specify a function,
such as a Lambda function, which determines whether a record is output (function returns true) or
not (function returns false).
Join
Equijoin of two DynamicFrames. You specify the key fields in the schema of each frame to compare
for equality. The output DynamicFrame contains rows where keys match.
Map
Converts a DynamicFrame to a relational (rows and columns) form. Based on the data's schema,
this transform flattens nested structures and creates DynamicFrames from arrays structures. The
output is a collection of DynamicFrames that can result in data written to multiple tables.
RenameField
Renames a field in a DynamicFrame. The output is a DynamicFrame with the specified field
renamed. You provide the new name and the path in the schema to the field to be renamed.
ResolveChoice
Use ResolveChoice to specify how a column should be handled when it contains values of
multiple types. You can choose to either cast the column to a single data type, discard one or more
of the types, or retain all types in either separate columns or a structure. You can select a different
resolution policy for each column or specify a global policy that is applied to all columns.
SelectFields
Selects fields from a DynamicFrame to keep. The output is a DynamicFrame with only the selected
fields. You provide the paths in the schema to the fields to keep.
SelectFromCollection
Selects one DynamicFrame from a collection of DynamicFrames. The output is the selected
DynamicFrame. You provide an index to the DynamicFrame to select.
Spigot
Writes sample data from a DynamicFrame. Output is a JSON file in Amazon S3. You specify the
Amazon S3 location and how to sample the DynamicFrame. Sampling can be a specified number of
records from the beginning of the file or a probability factor used to pick records to write.
SplitFields
Splits fields into two DynamicFrames. Output is a collection of DynamicFrames: one with selected
fields, and one with the remaining fields. You provide the paths in the schema to the selected fields.
170
AWS Glue Developer Guide
Jobs on the Console
SplitRows
Unboxes a string field from a DynamicFrame. The output is a DynamicFrame with the selected
string field reformatted. The string field can be parsed and replaced with several fields. You provide
a path in the schema for the string field to reformat and its current format type. For example, you
might have a CSV file that has one field that is in JSON format {"a": 3, "b": "foo", "c":
1.2}. This transform can reformat the JSON into three fields: an int, a string, and a double.
To view existing jobs, sign in to the AWS Management Console and open the AWS Glue console at
https://console.aws.amazon.com/glue/. Then choose the Jobs tab in AWS Glue. The Jobs list displays
the location of the script that is associated with each job, when the job was last modified, and the
current job bookmark option.
• To start an existing job, choose Action, and then choose Run job.
• To stop a Running or Starting job, choose Action, and then choose Stop job run.
• To add triggers that start a job, choose Action, Choose job triggers.
• To modify an existing job, choose Action, and then choose Edit job or Delete.
• To change a script that is associated with a job, choose Action, Edit script.
• To reset the state information that AWS Glue stores about your job, choose Action, Reset job
bookmark.
• To create a development endpoint with the properties of this job, choose Action, Create development
endpoint.
1. Open the AWS Glue console, and choose the Jobs tab.
2. Choose Add job, and follow the instructions in the Add job wizard.
If you decide to have AWS Glue generate a script for your job, you must specify the job properties,
data sources, and data targets, and verify the schema mapping of source columns to target columns.
The generated script is a starting point for you to add code to perform your ETL work. Verify the
code in the script and modify it to meet your business needs.
Note
To get step-by-step guidance for adding a job with a generated script, see the Add job
tutorial in the console.
Optionally, you can add a security configuration to a job to specify at-rest encryption options.
If you provide or author the script, your job defines the sources, targets, and transforms. But you
must specify any connections that are required by the script in the job. For information about
creating your own script, see Providing Your Own Custom Scripts (p. 178).
171
AWS Glue Developer Guide
Jobs on the Console
Note
The job assumes the permissions of the IAM role that you specify when you create it. This
IAM role must have permission to extract data from your data store and write to your target.
The AWS Glue console only lists IAM roles that have attached a trust policy for the AWS Glue
principal service. For more information about providing roles for AWS Glue, see Identity-Based
Policies (p. 54).
If the job reads AWS KMS encrypted Amazon Simple Storage Service (Amazon S3) data, then
the IAM role must have decrypt permission on the KMS key. For more information, see Step 2:
Create an IAM Role for AWS Glue (p. 14).
Important
Check Troubleshooting Errors in AWS Glue (p. 288) for known problems when a job runs.
To learn about the properties that are required for each job, see Defining Job Properties (p. 162).
To get step-by-step guidance for adding a job with a generated script, see the Add job tutorial in the
AWS Glue console.
• History
• Details
• Script
• Metrics
History
The History tab shows your job run history and how successful a job has been in the past. For each job,
the run metrics include the following:
• Run ID is an identifier created by AWS Glue for each run of this job.
• Retry attempt shows the number of attempts for jobs that required AWS Glue to automatically retry.
• Run status shows the success of each run listed with the most recent run at the top. If a job is
Running or Starting, you can choose the action icon in this column to stop it.
• Error shows the details of an error message if the run was not successful.
• Logs links to the logs written to stdout for this job run.
The Logs link takes you to Amazon CloudWatch Logs, where you can see all the details about the
tables that were created in the AWS Glue Data Catalog and any errors that were encountered. You
can manage your log retention period in the CloudWatch console. The default log retention is Never
Expire. For more information about how to change the retention period, see Change Log Data
Retention in CloudWatch Logs in the Amazon CloudWatch Logs User Guide.
• Error logs links to the logs written to stderr for this job run.
This link takes you to CloudWatch Logs, where you can see details about any errors that were
encountered. You can manage your log retention period on the CloudWatch console. The default log
retention is Never Expire. For more information about how to change the retention period, see
Change Log Data Retention in CloudWatch Logs in the Amazon CloudWatch Logs User Guide.
• Execution time shows the length of time during which the job run consumed resources. The amount is
calculated from when the job run starts consuming resources until it finishes.
• Timeout shows the maximum execution time during which this job run can consume resources before
it stops and goes into timeout status.
172
AWS Glue Developer Guide
Jobs on the Console
• Delay shows the threshold before sending a job delay notification. When a job run execution time
reaches this threshold, AWS Glue sends a notification ("Glue Job Run Status") to CloudWatch Events.
• Triggered by shows the trigger that fired to start this job run.
• Start time shows the date and time (local time) that the job started.
• End time shows the date and time (local time) that the job ended.
For a specific job run, you can View run metrics, which displays graphs of metrics for the selected job
run. For more information about how to enable metrics and interpret the graphs, see Job Monitoring and
Debugging (p. 254).
Details
The Details tab includes attributes of your job. It shows you the details about the job definition and also
lists the triggers that can start this job. Each time one of the triggers in the list fires, the job is started.
For the list of triggers, the details include the following:
• Trigger name shows the names of triggers that start this job when fired.
• Trigger type lists the type of trigger that starts this job.
• Trigger status displays whether the trigger is created, activated, or deactivated.
• Trigger parameters shows parameters that define when the trigger fires.
• Jobs to trigger shows the list of jobs that start when this trigger fires.
Note
The Details tab does not include source and target information. Review the script to see the
source and target details.
Script
The Script tab shows the script that runs when your job is started. You can invoke an Edit script view
from this tab. For more information about the script editor in the AWS Glue console, see Working with
Scripts on the AWS Glue Console (p. 178). For information about the functions that are called in your
script, see Program AWS Glue ETL Scripts in Python (p. 315).
Metrics
The Metrics tab shows metrics collected when a job runs and profiling is enabled. The following graphs
are shown:
Data for these graphs is pushed to CloudWatch metrics if the job is enabled to collect metrics. For
more information about how to enable metrics and interpret the graphs, see Job Monitoring and
Debugging (p. 254).
173
AWS Glue Developer Guide
Jobs on the Console
• The fraction of memory used by the JVM heap for this driver (scale: 0–1) by the driver, an executor
identified by executorId, or all executors—
• glue.driver.jvm.heap.usage (p. 246)
• glue.executorId.jvm.heap.usage (p. 246)
• glue.ALL.jvm.heap.usage (p. 246)
The Data Shuffle Across Executors graph shows the following metrics:
• The number of bytes read by all executors to shuffle data between them
—glue.driver.aggregate.shuffleLocalBytesRead (p. 243)
• The number of bytes written by all executors to shuffle data between them
—glue.driver.aggregate.shuffleBytesWritten (p. 242)
174
AWS Glue Developer Guide
Jobs on the Console
• The fraction of CPU system load used (scale: 0–1) by the driver, an executor identified by executorId, or
all executors—
• glue.driver.system.cpuSystemLoad (p. 250)
• glue.executorId.system.cpuSystemLoad (p. 250)
• glue.ALL.system.cpuSystemLoad (p. 250)
175
AWS Glue Developer Guide
Editing Scripts
AWS Glue ETL scripts can be coded in Python or Scala. Python scripts use a language that is an extension
of the PySpark Python dialect for extract, transform, and load (ETL) jobs. The script contains extended
constructs to deal with ETL transformations. When you automatically generate the source code logic for
your job, a script is created. You can edit this script, or you can provide your own script to process your
ETL work.
For information about defining and editing scripts using the AWS Glue console, see Working with Scripts
on the AWS Glue Console (p. 178).
Defining a Script
Given a source and target, AWS Glue can generate a script to transform the data. This proposed script
is an initial version that fills in your sources and targets, and suggests transformations in PySpark. You
can verify and modify the script to fit your business needs. Use the script editor in AWS Glue to add
arguments that specify the source and target, and any other arguments that are required to run. Scripts
are run by jobs, and jobs are started by triggers, which can be based on a schedule or an event. For more
information about triggers, see Triggering Jobs in AWS Glue (p. 179).
In the AWS Glue console, the script is represented as code. You can also view the script as a diagram that
uses annotations (##) embedded in the script. These annotations describe the parameters, transform
types, arguments, inputs, and other characteristics of the script that are used to generate a diagram in
the AWS Glue console.
Annotation Usage
To learn about the code constructs within a script, see Program AWS Glue ETL Scripts in
Python (p. 315).
176
AWS Glue Developer Guide
Defining a Script
Example
The following is an example of a script generated by AWS Glue. The script is for a job that copies a
simple dataset from one Amazon Simple Storage Service (Amazon S3) location to another, changing the
format from CSV to JSON. After some initialization code, the script includes commands that specify the
data source, the mappings, and the target (data sink). Note also the annotations.
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)
## @type: DataSource
## @args: [database = "sample-data", table_name = "taxi_trips", transformation_ctx =
"datasource0"]
## @return: datasource0
## @inputs: []
datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "sample-data",
table_name = "taxi_trips", transformation_ctx = "datasource0")
## @type: ApplyMapping
## @args: [mapping = [("vendorid", "long", "vendorid", "long"), ("tpep_pickup_datetime",
"string", "tpep_pickup_datetime", "string"), ("tpep_dropoff_datetime", "string",
"tpep_dropoff_datetime", "string"), ("passenger_count", "long", "passenger_count",
"long"), ("trip_distance", "double", "trip_distance", "double"), ("ratecodeid",
"long", "ratecodeid", "long"), ("store_and_fwd_flag", "string", "store_and_fwd_flag",
"string"), ("pulocationid", "long", "pulocationid", "long"), ("dolocationid", "long",
"dolocationid", "long"), ("payment_type", "long", "payment_type", "long"), ("fare_amount",
"double", "fare_amount", "double"), ("extra", "double", "extra", "double"), ("mta_tax",
"double", "mta_tax", "double"), ("tip_amount", "double", "tip_amount", "double"),
("tolls_amount", "double", "tolls_amount", "double"), ("improvement_surcharge", "double",
"improvement_surcharge", "double"), ("total_amount", "double", "total_amount", "double")],
transformation_ctx = "applymapping1"]
## @return: applymapping1
## @inputs: [frame = datasource0]
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("vendorid",
"long", "vendorid", "long"), ("tpep_pickup_datetime", "string", "tpep_pickup_datetime",
"string"), ("tpep_dropoff_datetime", "string", "tpep_dropoff_datetime", "string"),
("passenger_count", "long", "passenger_count", "long"), ("trip_distance",
"double", "trip_distance", "double"), ("ratecodeid", "long", "ratecodeid", "long"),
("store_and_fwd_flag", "string", "store_and_fwd_flag", "string"), ("pulocationid",
"long", "pulocationid", "long"), ("dolocationid", "long", "dolocationid", "long"),
("payment_type", "long", "payment_type", "long"), ("fare_amount", "double", "fare_amount",
"double"), ("extra", "double", "extra", "double"), ("mta_tax", "double", "mta_tax",
"double"), ("tip_amount", "double", "tip_amount", "double"), ("tolls_amount", "double",
"tolls_amount", "double"), ("improvement_surcharge", "double", "improvement_surcharge",
"double"), ("total_amount", "double", "total_amount", "double")], transformation_ctx =
"applymapping1")
## @type: DataSink
## @args: [connection_type = "s3", connection_options = {"path": "s3://example-data-
destination/taxi-data"}, format = "json", transformation_ctx = "datasink2"]
## @return: datasink2
## @inputs: [frame = applymapping1]
datasink2 = glueContext.write_dynamic_frame.from_options(frame = applymapping1,
connection_type = "s3", connection_options = {"path": "s3://example-data-destination/taxi-
data"}, format = "json", transformation_ctx = "datasink2")
177
AWS Glue Developer Guide
Scripts on the Console
job.commit()
You can edit a script in the AWS Glue console. When you edit a script, you can add sources, targets, and
transforms.
To edit a script
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/. Then choose the Jobs tab.
2. Choose a job in the list, and then choose Action, Edit script to open the script editor.
You can also access the script editor from the job details page. Choose the Script tab, and then
choose Edit script.
Script Editor
The AWS Glue script editor lets you insert, modify, and delete sources, targets, and transforms in your
script. The script editor displays both the script and a diagram to help you visualize the flow of data.
To create a diagram for the script, choose Generate diagram. AWS Glue uses annotation lines in the
script beginning with ## to render the diagram. To correctly represent your script in the diagram, you
must keep the parameters in the annotations and the parameters in the Apache Spark code in sync.
The script editor lets you add code templates wherever your cursor is positioned in the script. At the top
of the editor, choose from the following options:
In the inserted code, modify the parameters in both the annotations and Apache Spark code. For
example, if you add a Spigot transform, verify that the path is replaced in both the @args annotation
line and the output code line.
The Logs tab shows the logs that are associated with your job as it runs. The most recent 1,000 lines are
displayed.
The Schema tab shows the schema of the selected sources and targets, when available in the Data
Catalog.
178
AWS Glue Developer Guide
Triggering Jobs
Important
Different versions of AWS Glue support different versions of Apache Spark. Your custom script
must be compatible with the supported Apache Spark version. For information about AWS Glue
versions, see the Glue version job property (p. 162).
To provide your own custom script in AWS Glue, follow these general steps:
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. Choose the Jobs tab, and then choose Add job to start the Add job wizard.
3. In the Job properties screen, choose the IAM role that is required for your custom script to run. For
more information, see Identity and Access Management in AWS Glue (p. 49).
4. Under This job runs, choose one of the following:
An elastic network interface is a virtual network interface that you can attach to an instance in a
virtual private cloud (VPC). Choose the elastic network interface that is required to connect to the
data store that's used in the script.
6. If your script requires additional libraries or files, you can specify them as follows:
Comma-separated Amazon Simple Storage Service (Amazon S3) paths to Python libraries that
are required by the script.
Note
Only pure Python libraries can be used. Libraries that rely on C extensions, such as the
pandas Python Data Analysis Library, are not yet supported.
Dependent jars path
Comma-separated Amazon S3 paths to JAR files that are required by the script.
Note
Currently, only pure Java or Scala (2.11) libraries can be used.
Referenced files path
Comma-separated Amazon S3 paths to additional files (for example, configuration files) that are
required by the script.
7. If you want, you can add a schedule to your job. To change a schedule, you must delete the existing
schedule and add a new one.
For more information about adding jobs in AWS Glue, see Adding Jobs in AWS Glue (p. 161).
For step-by-step guidance, see the Add job tutorial in the AWS Glue console.
179
AWS Glue Developer Guide
Triggering Jobs Based on Schedules or Events
When you create a trigger based on an event, you specify events to watch that cause the trigger to fire,
such as when another job succeeded. For a conditional trigger based on a job events trigger, you specify
a list of jobs that cause a trigger to fire when any or all jobs satisfy the watched job events. In turn, when
the trigger fires, it starts a run of any dependent jobs.
Schedule
An event-based trigger that fires when a previous job or multiple jobs satisfy a list of conditions.
You provide a list of job events to watch for when their run state changes to succeeded, failed,
stopped, or timeout. This trigger waits to fire until any or all the conditions are satisfied.
Important
Dependent jobs are only started if the job which completes was started by a trigger (not run
ad-hoc). All jobs in a dependency chain must be descendants of a single schedule or on-
demand trigger.
On-demand
The trigger fires when you start it. As jobs complete, any triggers watching for completion are also
fired and dependent jobs are started.
So that they are ready to fire as soon as they exist, you can set a flag to enable (activate) schedule and
job events (conditional) triggers when they are created.
For more information about defining triggers using the AWS Glue console, see Working with Triggers on
the AWS Glue Console (p. 180).
Trigger name
The unique name you gave the trigger when you created it.
Tags
Tag your trigger with a Tag key and optional Tag value. Once created, tag keys are read-only. Use
tags on some resources to help you organize and identify them. For more information, see AWS Tags
in AWS Glue (p. 224).
180
AWS Glue Developer Guide
Developing Scripts Using Development Endpoints
Trigger type
Indicates whether the trigger is time-based (Schedule), event-based (Job events), or started by you
(On-demand).
Trigger status
Indicates whether the trigger is Enabled or ACTIVATED and ready to invoke associated jobs when
it fires. The trigger can also be Disabled or DEACTIVATED and paused so that it doesn't determine
whether a job is invoked. A CREATED trigger exists, but does not factor into whether a job runs.
Trigger parameters
For Schedule triggers, this includes the details about the frequency and time to fire the trigger. For
Job events triggers, it includes the list of jobs to watch that, depending on their run state, might fire
the trigger. See the details of the trigger for the watch list of jobs with events.
Jobs to trigger
Lists the jobs associated with the trigger that are invoked when this trigger fires.
Choose a trigger in the list to view details for the trigger. Trigger details include the information you
defined when you created the trigger.
To add a new trigger, choose Add trigger, and follow the instructions in the Add trigger wizard.
Name
For Schedule and Job events trigger types, you can enable them when they are created.
Jobs to trigger
For more information, see Triggering Jobs in AWS Glue (p. 179).
181
AWS Glue Developer Guide
Development Endpoint Workflow
When you create a development endpoint, you provide configuration values to provision the
development environment. These values tell AWS Glue how to set up the network so that you can access
the endpoint securely and the endpoint can access your data stores.
You can then create a notebook that connects to the endpoint, and use your notebook to author and
test your ETL script. When you're satisfied with the results of your development process, you can create
an ETL job that runs your script. With this process, you can add functions and debug your scripts in an
interactive manner.
Follow the tutorials in this section to learn how to use your development endpoint with notebooks.
Topics
• Development Endpoint Workflow (p. 182)
• Adding a Development Endpoint (p. 183)
• Viewing Development Endpoint Properties (p. 184)
• Accessing Your Development Endpoint (p. 186)
• Creating a Notebook Server Hosted on Amazon EC2 (p. 187)
• Tutorial Setup: Prerequisites for the Development Endpoint Tutorials (p. 189)
• Tutorial: Set Up a Local Apache Zeppelin Notebook to Test and Debug ETL Scripts (p. 192)
• Tutorial: Set Up an Apache Zeppelin Notebook Server on Amazon EC2 (p. 195)
• Tutorial: Use a REPL Shell with Your Development Endpoint (p. 197)
• Tutorial: Set Up PyCharm Professional with a Development Endpoint (p. 199)
1. Create a development endpoint using the console or API. The endpoint is launched in a virtual
private cloud (VPC) with your defined security groups.
2. The console or API polls the development endpoint until it is provisioned and ready for work. When
it's ready, connect to the development endpoint using one of the following methods to create and
test AWS Glue scripts.
182
AWS Glue Developer Guide
Adding a Development Endpoint
1. Open the AWS Glue console at https://console.aws.amazon.com/glue/. Sign in as a user who has the
IAM permission glue:CreateDevEndpoint.
2. In the navigation pane, choose Dev endpoints, and then choose Add endpoint.
3. Follow the steps in the AWS Glue Add endpoint wizard to provide the properties that are required to
create an endpoint. Specify an IAM role that permits access to your data.
If you choose to provide an SSH public key when you create your development endpoint, save the
SSH private key to access the development endpoint later.
4. Choose Finish to complete the wizard. Then check the console for development endpoint status.
When the status changes to READY, the development endpoint is ready to use.
When creating the endpoint, you can provide the following optional information:
Security configuration
To specify at-rest encryption options, add a security configuration to the development endpoint.
Worker type
The type of predefined worker that is allocated to the development endpoint. Accepts a value of
Standard, G.1X, or G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory, a 50 GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker maps to 1 DPU (4 vCPU, 16 GB of memory, and a 64
GB disk), and provides 1 executor per worker. We recommend this worker type for memory-
intensive jobs.
• For the G.2X worker type, each worker maps to 2 DPU (8 vCPU, 32 GB of memory, and a 128
GB disk), and provides 1 executor per worker. We recommend this worker type for memory-
intensive jobs.
Known issue: When you create a development endpoint with the G.2X WorkerType
configuration, the Spark drivers for the development endpoint run on 4 vCPU, 16 GB of
memory, and a 64 GB disk.
Number of workers
The number of workers of a defined workerType that are allocated to the development
endpoint. This field is available only when you choose worker type G.1X or G.2X.
The maximum number of workers you can define is 299 for G.1X, and 149 for G.2X.
Data processing units (DPUs)
The number of DPUs that AWS Glue uses for your development endpoint. The number must be
greater than 1.
Python library path
Comma-separated Amazon Simple Storage Service (Amazon S3) paths to Python libraries that
are required by your script. Multiple values must be complete paths separated by a comma (,).
Only individual files are supported, not a directory path.
183
AWS Glue Developer Guide
Viewing Development Endpoint Properties
Note
You can use only pure Python libraries. Libraries that rely on C extensions, such as the
Pandas Python data analysis library, are not yet supported.
Dependent jars path
Comma-separated Amazon S3 paths to JAR files that are required by the script.
Note
Currently, you can use only pure Java or Scala (2.11) libraries.
Glue Version
Specifies the versions of Python and Apache Spark to use. Defaults to AWS Glue version 1.0
(Python version 3 and Spark version 2.4). For more information, see the Glue version job
property (p. 162).
Tags
Tag your development endpoint with a Tag key and optional Tag value. After tag keys are
created, they are read-only. Use tags on some resources to help you organize and identify them.
For more information, see AWS Tags in AWS Glue (p. 224).
Spark UI
Enable the use of Spark UI for monitoring Spark applications runnning on this development
endpoint. For more information, see Enabling the Apache Spark Web UI for Development
Endpoints (p. 233).
Use Glue Data Catalog as the Hive metastore (under Catalog Options)
Enables you to use the AWS Glue Data Catalog as a Spark Hive metastore.
This command specifies AWS Glue version 1.0. Because this version supports both Python 2 and
Python 3, you can use the arguments parameter to indicate the desired Python version. If the
glue-version parameter is omitted, AWS Glue version 0.9 is assumed. For more information about
AWS Glue versions, see the Glue version job property (p. 162).
For information about additional command line parameters, see create-dev-endpoint in the AWS CLI
Command Reference.
2. (Optional) Enter the following command to check the development endpoint status. When the
status changes to READY, the development endpoint is ready to use.
184
AWS Glue Developer Guide
Viewing Development Endpoint Properties
information that you need to connect to the endpoint and information about any notebooks that use the
endpoint.
1. Open the AWS Glue console at https://console.aws.amazon.com/glue/. Sign in as a user who has the
IAM permissions glue:GetDevEndpoints and glue:GetDevEndpoint.
2. In the navigation pane, under ETL, choose Dev endpoints.
3. On the Dev endpoints page, choose the name of the development endpoint.
Endpoint name
The unique name that you give the endpoint when you create it.
Provisioning status
Describes whether the endpoint is being created (PROVISIONING), ready to be used (READY), in the
process of terminating (TERMINATING), terminated (TERMINATED), or failed (FAILED).
Failure reason
The address to connect to the development endpoint. On the Amazon EC2 console, you can view
the elastic network interface that is attached to this IP address. This internal address is created if the
development endpoint is associated with a virtual private cloud (VPC).
For more information about accessing a development endpoint from a private address, see the
section called “Accessing Your Development Endpoint” (p. 186).
Public address
The current public SSH keys that are associated with the development endpoint (optional). If you
provided a public key when you created the development endpoint, you should have saved the
corresponding SSH private key.
IAM role
Specify the IAM role that is used for authorization to resources. If the development endpoint reads
AWS KMS encrypted Amazon S3 data, the IAM role must have decrypt permission on the KMS key.
For more information about creating an IAM role, see Step 2: Create an IAM Role for AWS
Glue (p. 14).
SSH to Python REPL
You can open a terminal window on your computer and enter this command to interact with
the development endpoint as a read-eval-print loop (REPL) shell. This field is shown only if the
development endpoint contains a public SSH key.
SSH to Scala REPL
You can open a terminal window and enter this command to interact with the development
endpoint as a REPL shell. This field is shown only if the development endpoint contains a public SSH
key.
185
AWS Glue Developer Guide
Accessing Your Development Endpoint
You can open a terminal window and enter this command to open a tunnel to the development
endpoint. Then open your local Apache Zeppelin notebook and point to the development endpoint
as a remote interpreter. When the interpreter is set up, all notes within the notebook can use it. This
field is shown only if the development endpoint contains a public SSH key.
Public key update status
The status of completing an update of the public key on the development endpoint. When you
update a public key, the new key must be propagated to the development endpoint. Status values
include COMPLETED and PENDING.
Last modified time
The amount of time the development endpoint has been provisioned and READY.
If your development endpoint has a Public address, confirm that it is reachable with the SSH private key
for the development endpoint, as in the following example.
Suppose that your development endpoint has a Private address, your VPC subnet is routable from the
public internet, and its security groups allow inbound access from your client. In this case, follow these
steps to attach an Elastic IP address to a development endpoint to allow access from the internet.
Note
If you want to use Elastic IP addresses, the subnet that is being used requires an internet
gateway associated through the route table.
You might need to modify which columns are displayed on your Amazon EC2 console. Note the
Network interface ID (ENI) for this address (for example, eni-12345678).
6. On the Amazon EC2 console, under Network & Security, choose Elastic IPs.
7. Choose Allocate new address, and then choose Allocate to allocate a new Elastic IP address.
8. On the Elastic IPs page, choose the newly allocated Elastic IP. Then choose Actions, Associate
address.
186
AWS Glue Developer Guide
Creating a Notebook Server Hosted on Amazon EC2
For information about using a bastion host to get SSH access to the development endpoint’s private
address, see the AWS Security Blog post Securely Connect to Linux Instances Running in a Private
Amazon VPC.
In the AWS Glue Create notebook server window, you add the properties that are required to create a
notebook server to use an Apache Zeppelin notebook.
Note
For any notebook server that you create that is associated with a development endpoint, you
manage it. Therefore, if you delete the development endpoint, to delete the notebook server,
you must delete the AWS CloudFormation stack on the AWS CloudFormation console.
Important
Before you can use the notebook server hosted on Amazon EC2, you must run a script on the
Amazon EC2 instance that does the following actions:
For more information, see the section called “Notebook Server Considerations” (p. 207).
The name of your notebook that is created in the AWS CloudFormation stack on the development
endpoint. The name is prefixed with aws-glue-. This notebook runs on an Amazon EC2 instance.
The Zeppelin HTTP server is started either on public port 443 or localhost port 8080 that can be
accessed with an SSH tunnel command.
IAM role
A role with a trust relationship to Amazon EC2 that matches the Amazon EC2 instance profile
exactly. Create the role in the IAM console. Choose Amazon EC2, and attach a policy for the
notebook, such as AWSGlueServiceNotebookRoleDefault. For more information, see Step 5: Create
an IAM Role for Notebook Servers (p. 25).
For more information about instance profiles, see Using Instance Profiles.
187
AWS Glue Developer Guide
Creating a Notebook Server Hosted on Amazon EC2
The Amazon EC2 key that is used to access the Amazon EC2 instance hosting the notebook server.
You can create a key pair on the Amazon EC2 console (https://console.aws.amazon.com/ec2/). Save
the key files for later use. For more information, see Amazon EC2 Key Pairs.
Attach a public IP to the notebook server EC2 instance
Select this option to attach a public IP which can be used to access the notebook server from the
internet. Whether you choose a public or private Subnet is a factor when deciding to select this
option. In a public subnet, a notebook server requires a public IP to access the internet. If your
notebook server is in a private subnet and you do not want a public IP, don't select this option.
However, your notebook server still requires a route to the internet such as through a NAT gateway.
Notebook username
The user name that you use to access the Zeppelin notebook. The default is admin.
Notebook S3 path
The location where the state of the notebook is stored. The Amazon S3 path to the Zeppelin
notebook must follow the format: s3://bucket-name/username. Subfolders cannot be included
in the path. The default is s3://aws-glue-notebooks-account-id-region/notebook-
username.
Subnet
The available subnets that you can use with your notebook server. An asterisk (*) indicates that the
subnet can be accessed from the internet. The subnet must have a route to the internet through
an internet gateway (IGW), NAT gateway, or VPN. For more information, see Setting Up Your
Environment for Development Endpoints (p. 34).
Security groups
The available security groups that you can use with your notebook server. The security group must
have inbound rules for HTTPS (port 443) and SSH (port 22). Ensure that the rule's source is either
0.0.0.0/0 or the IP address of the machine connecting to the notebook.
S3 AWS KMS key
A key used for client-side KMS encryption of the Zeppelin notebook storage on Amazon S3. This
field is optional. Enable access to Amazon S3 by either choosing an AWS KMS key or choose Enter
a key ARN and provide the Amazon Resource Name (ARN) for the key. Type the ARN in the form
arn:aws:kms:region:account-id:key/key-id. You can also provide the ARN in the form of a
key alias, such as arn:aws:kms:region:account-id:alias/alias-name.
Custom AMI ID
A custom Amazon Machine Image (AMI) ID of an encrypted Amazon Elastic Block Storage (EBS) EC2
instance. This field is optional. Provide the AMI ID by either choosing an AMI ID or choose Enter AMI
ID and type the custom AMI ID. For more information about how to encrypt your notebook server
storage, see Encryption and AMI Copy.
Notebook server tags
The AWS CloudFormation stack is always tagged with a key aws-glue-dev-endpoint and the value
of the name of the development endpoint. You can add more tags to the AWS CloudFormation
stack.
EC2 instance
The name of Amazon EC2 instance that is created to host your notebook. This links to the Amazon
EC2 console (https://console.aws.amazon.com/ec2/) where the instance is tagged with the key aws-
glue-dev-endpoint and value of the name of the development endpoint.
188
AWS Glue Developer Guide
Tutorial Prerequisites
CloudFormation stack
The name of the AWS CloudFormation stack used to create the notebook server.
SSH to EC2 server command
Type this command in a terminal window to connect to the Amazon EC2 instance that is running
your notebook server. The Amazon EC2 address shown in this command is either public or private
depending on whether you chose to Attach a public IP to the notebook server EC2 instance.
Copy certificate
Example scp command to copy the keystore required to set up the Zeppelin notebook server to the
Amazon EC2 instance that hosts the notebook server. Run the command from a terminal window
in the directory where the Amazon EC2 private key is located. The key to access the Amazon EC2
instance is the parameter to the -i option. You provide the path-to-keystore-file. The
location where the development endpoint private SSH key on the Amazon EC2 server is located is
the remaining part of the command.
HTTPS URL
After completing the setup of a notebook server, type this URL in a browser to connect to your
notebook using HTTPS.
Because you're using only Amazon Simple Storage Service (Amazon S3) data in some cases, and a mix
of JDBC and Amazon S3 data in others, you will set up one development endpoint that is not in a virtual
private cloud (VPC) and one that is.
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
In the AWS Glue console, choose Databases in the navigation pane, and then choose Add database.
Name the database legislators.
2. Choose Crawlers, and then choose Add crawler. Name the crawler legislator_crawler, and then
choose Next.
3. Accept the default crawler source type (Data stores) and click Next.
4. Leave S3 as the data store. Under Crawl data in, choose Specified path in another account. Then
in the Include path box, enter s3://awsglue-datasets/examples/us-legislators/all.
Choose Next, and then choose Next again to confirm that you don't want to add another data store.
5. Provide an IAM role for the crawler to assume when it runs.
189
AWS Glue Developer Guide
Tutorial Prerequisites
1. In the AWS Glue console, choose Dev endpoints. Choose Add endpoint.
2. Specify an endpoint name, such as demo-endpoint.
3. Choose an IAM role with permissions similar to the IAM role that you use to run AWS Glue ETL jobs.
For more information, see Step 2: Create an IAM Role for AWS Glue (p. 14). Choose Next.
4. In Networking, leave Skip networking information selected, and choose Next.
5. In SSH Public Key, enter a public key generated by an SSH key generator program, such as ssh-
keygen (do not use an Amazon EC2 key pair). The generated public key will be imported into your
development endpoint. Save the corresponding private key to later connect to the development
endpoint using SSH. Choose Next. For more information, see ssh-keygen in Wikipedia.
Note
When generating the key on Microsoft Windows, use a current version of PuTTYgen and
paste the public key into the AWS Glue console from the PuTTYgen window. Generate an
RSA key. Do not upload a file with the public key, instead use the key generated in the field
Public key for pasting into OpenSSH authorized_keys file. The corresponding private key
(.ppk) can be used in PuTTY to connect to the development endpoint. To connect to the
development endpoint with SSH on Windows, convert the private key from .ppk format to
OpenSSH .pem format using the PuTTYgen Conversion menu. For more information, see
Connecting to Your Linux Instance from Windows Using PuTTY.
6. In Review, choose Finish. After the development endpoint is created, wait for its provisioning status
to move to READY.
1. In the AWS Glue console, choose Dev endpoints in the navigation pane. Then choose Add endpoint.
190
AWS Glue Developer Guide
Tutorial Prerequisites
• If you already set up a connection to your data stores, you can use the same connection to
determine the Amazon VPC, subnet, and security groups for your endpoint. Otherwise, specify
these parameters individually.
• Ensure that your Amazon VPC has Edit DNS hostnames set to yes. This parameter can be set
in the Amazon VPC console (https://console.aws.amazon.com/vpc/). For more information, see
Setting Up DNS in Your VPC (p. 29).
• For this tutorial, ensure that the Amazon VPC you select has an Amazon S3 VPC endpoint. For
information about how to create an Amazon S3 VPC endpoint, see Amazon VPC Endpoints for
Amazon S3 (p. 30).
• Choose a public subnet for your development endpoint. You can make a subnet a public subnet
by adding a route to an internet gateway. For IPv4 traffic, create a route with Destination
0.0.0.0/0 and Target the internet gateway ID. Your subnet’s route table should be associated
with an internet gateway, not a NAT gateway. This information can be set in the Amazon VPC
console (https://console.aws.amazon.com/vpc/). For example:
For more information, see Route tables for Internet Gateways. For information about how to
create an internet gateway, see Internet Gateways.
• Ensure that you choose a security group that has an inbound self-reference rule. This information
can be set in the Amazon VPC console (https://console.aws.amazon.com/vpc/). For example:
For more information about how to set up your subnet, see Setting Up Your Environment for
Development Endpoints (p. 34).
191
AWS Glue Developer Guide
Tutorial: Local Zeppelin Notebook
Choose Next.
5. In SSH Public Key, enter a public key generated by an SSH key generator program (do not use an
Amazon EC2 key pair). Save the corresponding private key to later connect to the development
endpoint using SSH. Choose Next.
Note
When generating the key on Microsoft Windows, use a current version of PuTTYgen and
paste the public key into the AWS Glue console from the PuTTYgen window. Generate an
RSA key. Do not upload a file with the public key, instead use the key generated in the field
Public key for pasting into OpenSSH authorized_keys file. The corresponding private key
(.ppk) can be used in PuTTY to connect to the development endpoint. To connect to the
development endpoint with SSH on Windows, convert the private key from .ppk format to
OpenSSH .pem format using the PuTTYgen Conversion menu. For more information, see
Connecting to Your Linux Instance from Windows Using PuTTY.
6. In Review, choose Finish. After the development endpoint is created, wait for its provisioning status
to move to READY.
You are now ready to try out the tutorials in this section:
• Tutorial: Set Up a Local Apache Zeppelin Notebook to Test and Debug ETL Scripts (p. 192)
• Tutorial: Set Up an Apache Zeppelin Notebook Server on Amazon EC2 (p. 195)
• Tutorial: Use a REPL Shell with Your Development Endpoint (p. 197)
The tutorial assumes that you have already taken the steps outlined in Tutorial Prerequisites (p. 189).
If you are running on Microsoft Windows, make sure that the JAVA_HOME environment variable
points to the right Java directory. It's possible to update Java without updating this variable, and if it
points to a folder that no longer exists, Zeppelin fails to start.
2. Download the version of Apache Zeppelin with all interpreters from the Zeppelin download page
onto your local machine. Choose the file to download according to the following compatibility table,
and follow the download instructions.
192
AWS Glue Developer Guide
Tutorial: Local Zeppelin Notebook
Start Zeppelin in the way that's appropriate for your operating system. Leave the terminal window
that starts the notebook server open while you are using Zeppelin. When the server has started
successfully, you can see a line in the console that ends with "Done, zeppelin server started."
3. Open Zeppelin in your browser by navigating to http://localhost:8080.
4. In Zeppelin in the browser, open the drop-down menu at anonymous in the upper-right corner of
the page, and choose Interpreter. On the interpreters page, search for spark, and choose edit on
the right. Make the following changes:
• Select the Connect to existing process check box, and then set Host to localhost and Port to
9007 (or whatever other port you are using for port forwarding).
• In Properties, set master to yarn-client.
• If there is a spark.executor.memory property, delete it by choosing the x in the action column.
• If there is a spark.driver.memory property, delete it by choosing the x in the action column.
Choose Save at the bottom of the page, and then choose OK to confirm that you want to update the
interpreter and restart it. Use the browser back button to return to the Zeppelin start page.
Open a terminal window that gives you access to the SSH secure-shell protocol. On Microsoft Windows,
you can use the BASH shell provided by Git for Windows, or install Cygwin.
• Replace private-key-file-path with a path to the .pem file that contains the private key
corresponding to the public key that you used to create your development endpoint.
• If you are forwarding a different port than 9007, replace 9007 with the port number that you are
actually using locally. The address, 169.254.76.1:9007, is the remote port and not changed by you.
• Replace dev-endpoint-public-dns with the public DNS address of your development endpoint. To
find this address, navigate to your development endpoint in the AWS Glue console, choose the name,
and copy the Public address that's listed in the Endpoint details page.
Type yes and leave the terminal window open while you use your Zeppelin notebook.
193
AWS Glue Developer Guide
Tutorial: Local Zeppelin Notebook
Type the following script fragment into your notebook and run it. It uses the person's metadata in the
AWS Glue Data Catalog to create a DynamicFrame from your sample data. It then prints out the item
count and the schema of this data.
%pyspark
import sys
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.transforms import *
Count: 1961
root
|-- family_name: string
|-- name: string
|-- links: array
| |-- element: struct
| | |-- note: string
| | |-- url: string
|-- gender: string
|-- image: string
|-- identifiers: array
| |-- element: struct
| | |-- scheme: string
| | |-- identifier: string
|-- other_names: array
| |-- element: struct
| | |-- note: string
| | |-- name: string
| | |-- lang: string
|-- sort_name: string
|-- images: array
| |-- element: struct
| | |-- url: string
|-- given_name: string
|-- birth_date: string
|-- id: string
|-- contact_details: array
| |-- element: struct
| | |-- type: string
| | |-- value: string
|-- death_date: string
194
AWS Glue Developer Guide
Tutorial: Amazon EC2 Zeppelin Notebook Server
1. In Zeppelin, in the drop-down menu in the upper-right corner of the page, choose Interpreters. On
the interpreters page, search for spark. Choose edit, and clear the Connect to existing process
check box. Choose Save at the bottom of the page.
2. Initiate SSH port forwarding as described earlier.
3. In Zeppelin, re-enable the spark interpreter's Connect to existing process settings, and then save
again.
Resetting the interpreter like this should restore the connection. Another way to accomplish this is to
choose restart for the Spark interpreter on the Interpreters page. Then wait for up to 30 seconds to
ensure that the remote interpreter has restarted.
• Ensure your development endpoint has permission to access the remote Zeppelin interpreter. Without
the proper networking permissions you might encounter errors such as open failed: connect failed:
Connection refused.
The tutorial assumes that you have already taken the steps outlined in Tutorial Prerequisites (p. 189).
1. On the AWS Glue console, choose Dev endpoints to go to the development endpoints list.
2. Choose an endpoint by selecting the box next to it. Choose and endpoint with an empty SSH public
key because the key is generated with a later action on the Amazon EC2 instance. Then choose
Actions, and choose Create notebook server.
To host the notebook server, an Amazon EC2 instance is spun up using an AWS CloudFormation
stack on your development endpoint. If you create the Zeppelin server with an SSL certificate, the
Zeppelin HTTPS server is started on port 443.
3. Enter an AWS CloudFormation stack server name such as demo-cf, using only alphanumeric
characters and hyphens.
4. Choose an IAM role that you have set up with a trust relationship to Amazon EC2, as documented in
Step 5: Create an IAM Role for Notebook Servers (p. 25).
5. Choose an Amazon EC2 key pair that you have generated on the Amazon EC2 console (https://
console.aws.amazon.com/ec2/), or choose Create EC2 key pair to generate a new one. Remember
where you have downloaded and saved the private key portion of the pair. This key pair is different
from the SSH key you used when creating your development endpoint (the keys that Amazon EC2
uses are 2048-bit SSH-2 RSA keys). For more information about Amazon EC2 keys, see Amazon EC2
Key Pairs.
It is to generally a good practice to ensure that the private-key file is write-protected so that it is
not accidentally modified. On macOS and Linux systems, do this by opening a terminal and entering
chmod 400 private-key-file path. On Windows, open the console and enter attrib -r
private-key-file path.
195
AWS Glue Developer Guide
Tutorial: Amazon EC2 Zeppelin Notebook Server
You can view the status of the AWS CloudFormation stack in the AWS CloudFormation console Events
tab (https://console.aws.amazon.com/cloudformation). You can view the Amazon EC2 instances created
by AWS CloudFormation in the Amazon EC2 console (https://console.aws.amazon.com/ec2/). Search
for instances that are tagged with the key name aws-glue-dev-endpoint and value of the name of your
development endpoint.
After the notebook server is created, its status changes to CREATE_COMPLETE in the Amazon EC2
console. Details about your server also appear in the development endpoint details page. When the
creation is complete, you can connect to a notebook on the new server.
To complete the setup of the Zeppelin notebook server, you must run a script on the Amazon EC2
instance. This tutorial requires that you upload an SSL certificate when you create the Zeppelin server
on the Amazon EC2 instance. But there is also an SSH local port forwarding method to connect.
For additional setup instructions, see Creating a Notebook Server Associated with a Development
Endpoint (p. 207). When the creation is complete, you can connect to a notebook on the new server
using HTTPS.
Note
For any notebook server that you create that is associated with a development endpoint, you
manage it. Therefore, if you delete the development endpoint, to delete the notebook server,
you must delete the AWS CloudFormation stack on the AWS CloudFormation console.
%pyspark
import sys
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
196
AWS Glue Developer Guide
Tutorial: Use a REPL Shell
glueContext = GlueContext(SparkContext.getOrCreate())
Count: 1961
root
|-- family_name: string
|-- name: string
|-- links: array
| |-- element: struct
| | |-- note: string
| | |-- url: string
|-- gender: string
|-- image: string
|-- identifiers: array
| |-- element: struct
| | |-- scheme: string
| | |-- identifier: string
|-- other_names: array
| |-- element: struct
| | |-- note: string
| | |-- name: string
| | |-- lang: string
|-- sort_name: string
|-- images: array
| |-- element: struct
| | |-- url: string
|-- given_name: string
|-- birth_date: string
|-- id: string
|-- contact_details: array
| |-- element: struct
| | |-- type: string
| | |-- value: string
|-- death_date: string
The tutorial assumes that you have already taken the steps outlined in Tutorial Prerequisites (p. 189).
1. In the AWS Glue console, choose Dev endpoints to navigate to the development endpoints list.
Choose the name of a development endpoint to open its details page.
2. Copy the SSH command labeled SSH to Python REPL, and paste it into a text editor. This field
is only shown if the development endpoint contains a public SSH key. Replace the <private-
key.pem> text with the path to the private-key .pem file that corresponds to the public key that
197
AWS Glue Developer Guide
Tutorial: Use a REPL Shell
you used to create the development endpoint. Use forward slashes rather than backslashes as
delimiters in the path.
3. On your local computer, open a terminal window that can run SSH commands, and paste in the
edited SSH command. Run the command.
Assuming that you accepted the default AWS Glue version 1.0 with Python 3 for the development
endpoint, the output will look like this:
4. Test that the REPL shell is working correctly by typing the statement, print(spark.version). As
long as that displays the Spark version, your REPL is now ready to use.
5. Now you can try executing the following simple script, line by line, in the shell:
import sys
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.transforms import *
glueContext = GlueContext(SparkContext.getOrCreate())
persons_DyF = glueContext.create_dynamic_frame.from_catalog(database="legislators",
table_name="persons_json")
print ("Count: ", persons_DyF.count())
persons_DyF.printSchema()
198
AWS Glue Developer Guide
Tutorial: Use PyCharm Professional
To connect to a development endpoint interactively, you must have PyCharm Professional installed. You
can't do this using the free edition.
The tutorial assumes that you have already taken the steps outlined in Tutorial Prerequisites (p. 189).
Topics
• Connecting PyCharm Professional to a Development Endpoint (p. 199)
• Deploying the Script to Your Development Endpoint (p. 202)
• Starting the Debug Server on localhost and a Local Port (p. 203)
• Initiating Port Forwarding (p. 204)
• Running Your Script on the Development Endpoint (p. 204)
import sys
import pydevd
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.transforms import *
def main():
# Invoke pydevd
pydevd.settrace('169.254.76.0', port=9001, stdoutToServer=True, stderrToServer=True)
if __name__ == "__main__":
main()
• For Glue version 0.9, download the AWS Glue Python library file, PyGlue.zip, from https://
s3.amazonaws.com/aws-glue-jes-prod-us-east-1-assets/etl/python/PyGlue.zip
to a convenient location on your local machine.
• For Glue version 1.0, download the AWS Glue Python library file, PyGlue.zip, from https://
s3.amazonaws.com/aws-glue-jes-prod-us-east-1-assets/etl-1.0/python/
PyGlue.zip to a convenient location on your local machine.
199
AWS Glue Developer Guide
Tutorial: Use PyCharm Professional
• In PyCharm, choose File, Settings to open the Settings dialog box. (You can also use the gear-
and-wrench icon on the toolbar, or press Ctrl+Alt+S.)
• Expand the legislators project and choose Project Structure. Then in the right pane, choose +
Add Content Root.
• Navigate to the location where you saved PyGlue.zip, select it, then choose Apply.
Leave the Settings dialog box open after you choose Apply.
5. Configure deployment options to upload the local script to your development endpoint using SFTP
(this capability is available only in PyCharm Professional):
• In the Settings dialog box, expand the Build, Execution, Deployment section. Choose the
Deployment subsection.
• Choose the + icon at the top of the middle pane to add a new server. Give it a name and set its
Type to SFTP.
• Set the SFTP host to the Public address of your development endpoint, as listed on its details
page (choose the name of your development endpoint in the AWS Glue console to display the
details page).
• Set the User name to glue.
• Set the Auth type to Key pair (OpenSSH or Putty). Set the Private key file by browsing to the
location where your development endpoint's private key file is located. Note that PyCharm only
supports DSA, RSA and ECDSA OpenSSH key types, and does not accept keys in Putty's private
format. You can use an up-to-date version of ssh-keygen to generate a key-pair type that
PyCharm accepts, using syntax like the following:
200
AWS Glue Developer Guide
Tutorial: Use PyCharm Professional
• Choose Test SFTP connection, and allow the connection to be tested. If the connection succeeds,
choose Apply.
The Settings screen should now look something like the following:
Again, leave the Settings dialog box open after you choose Apply.
6. Map the local directory to a remote directory for deployment:
• In the right pane of the Deployment page, choose the middle tab at the top, labeled Mappings.
• In the Deployment Path column, enter a path under /home/glue/scripts/ for deployment of
your project path.
• Choose Apply.
The Settings screen should now look something like the following:
201
AWS Glue Developer Guide
Tutorial: Use PyCharm Professional
After your script has been deployed, the bottom of the screen should look something like the following:
202
AWS Glue Developer Guide
Tutorial: Use PyCharm Professional
4. Note items 2 and 3 in the instructions in this screen. The script file that you created does import
pydevd. But in the call to settrace, it replaces localhost with 169.254.76.0, which is a special
link local IP address that is accessible to your development endpoint.
5. Choose Apply to save this default configuration.
6. Choose the + icon at the top of the screen to create a new configuration based on the default that
you just saved. In the drop-down menu, choose Python Remote Debug. Name this configuration
demoDevEndpoint, and choose OK.
7. On the Run menu, choose Debug 'demoDevEndpoint'. Your screen should now look something like
the following:
203
AWS Glue Developer Guide
Tutorial: Use PyCharm Professional
Replacements
• Replace private-key-file-path with the path to the private-key .pem file that corresponds to
your development endpoint's public key.
• Replace ec2-12-345-678-9.compute-1.amazonaws.com with the public address of your
development endpoint. You can find the public address in the AWS Glue console by choosing Dev
endpoints. Then choose the name of the development endpoint to open its Endpoint details page.
ssh -i private-key-file-path \
[email protected] \
-t gluepython deployed-script-path/script-name
204
AWS Glue Developer Guide
Managing Notebooks
Replacements
• Replace private-key-file-path with the path to the private-key .pem file that corresponds to
your development endpoint's public key.
• Replace ec2-12-345-678-9.compute-1.amazonaws.com with the public address of your
development endpoint. You can find the public address in the AWS Glue console by navigating to Dev
endpoints. Then choose the name of the development endpoint to open its Endpoint details page.
• Replace -t gluepython with -t gluepython3 if you are running with Python 3.
• Replace deployed-script-path with the path that you entered in the Deployment Mappings tab
(for example, /home/glue/scripts/legislators/).
• Replace script-name with the name of the script that you uploaded (for example,
get_person_schema.py).
PyCharm now prompts you to provide a local source file equivalent to the one being debugged remotely:
Choose Autodetect.
You are now set up to debug your script remotely on your development endpoint.
Managing Notebooks
A notebook enables interactive development and testing of your ETL (extract, transform, and load)
scripts on a development endpoint. AWS Glue provides an interface to Amazon SageMaker notebooks
and Apache Zeppelin notebook servers.
• Amazon SageMaker provides an integrated Jupyter authoring notebook instance. With AWS Glue, you
create and manage Amazon SageMaker notebooks. You can also open Amazon SageMaker notebooks
from the AWS Glue console.
205
AWS Glue Developer Guide
Managing Notebooks
In addition, you can use Apache Spark with Amazon SageMaker on AWS Glue development endpoints
which support Amazon SageMaker (but not AWS Glue ETL jobs). SageMaker Spark is an open source
Apache Spark library for Amazon SageMaker. For more information, see see Using Apache Spark with
Amazon SageMaker.
• Apache Zeppelin notebook servers are run on Amazon EC2 instances. You can create these instances
on the AWS Glue console.
For more information about creating and accessing your notebooks using the AWS Glue console, see
Working with Notebooks on the AWS Glue Console (p. 213).
For more information about creating development endpoints, see Viewing Development Endpoint
Properties (p. 184).
Important
Managing Amazon SageMaker notebooks with AWS Glue development endpoints is available
in the following AWS Regions:
Region Code
EU (Frankfurt) eu-central-1
EU (Ireland) eu-west-1
EU (London) eu-west-2
Topics
• Creating a Notebook Server Associated with a Development Endpoint (p. 207)
• Working with Notebooks on the AWS Glue Console (p. 213)
206
AWS Glue Developer Guide
Notebook Server Considerations
The following sections explain some of the choices to make and the actions to take to create a notebook
server securely. These instructions perform the following tasks:
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. Choose Dev endpoints in the navigation pane, and then choose Add endpoint to create a
development endpoint.
3. Follow the steps in the wizard to create a development endpoint that you plan to associate with one
notebook server running on Amazon EC2.
In the Add SSH public key (optional) step, leave the public key empty. In a later step, you generate
and push a public key to the development endpoint and a corresponding private key to the Amazon
EC2 instance that is running the notebook server.
4. When the development endpoint is provisioned, continue with the steps to create a notebook server
on Amazon EC2. On the development endpoints list page, choose the development endpoint that
you just created. Choose Action, Create Zeppelin notebook server, and fill in the information about
your notebook server. (For more information, see the section called “Viewing Development Endpoint
Properties” (p. 184).)
5. Choose Finish. The notebook server is created with an AWS CloudFormation stack. The AWS Glue
console provides you with the information you need to access the Amazon EC2 instance.
After the notebook server is ready, you must run a script on the Amazon EC2 instance to complete
the setup.
207
AWS Glue Developer Guide
Notebook Server Considerations
1. If your local desktop is running Windows, you need a way to run commands SSH and SCP to
interact with the Amazon EC2 instance. You can find instructions for connecting in the Amazon EC2
documentation. For more information, see Connecting to Your Linux Instance from Windows Using
PuTTY.
2. You can connect to your Zeppelin notebook using an HTTPS URL. This requires a Secure Sockets
Layer (SSL) certificate on your Amazon EC2 instance. The notebook server must provide web
browsers with a certificate to validate its authenticity and to allow encrypted traffic for sensitive
data such as passwords.
If you have an SSL certificate from a certificate authority (CA), copy your SSL certificate key store
onto the Amazon EC2 instance into a path that the ec2-user has write access to, such as /home/
ec2-user/. See the AWS Glue console notebook server details for the scp command to Copy
certificate. For example, open a terminal window, and enter the following command:
The truststore, keystore.jks, that is copied to the Amazon EC2 instance must have been created
with a password.
The ec2-private-key is the key needed to access the Amazon EC2 instance. When you created the
notebook server, you provided an Amazon EC2 key pair and saved this EC2 private key to your local
machine. You might need to edit the Copy certificate command to point to the key file on your local
machine. You can also find this key file name on the Amazon EC2 console details for your notebook
server.
The dns-address-of-ec2-instance is the address of the Amazon EC2 instance where the
keystore is copied.
Note
There are many ways to generate an SSL certificate. It is a security best practice to use a
certificate generated with a certificate authority (CA). You might need to enlist the help of
an administrator in your organization to obtain the certificate. Follow the policies of your
organization when you create a keystore for the notebook server. For more information, see
Certificate authority in Wikipedia.
Another method is to generate a self-signed certificate with a script on your notebook server
Amazon EC2 instance. However, with this method, each local machine that connects to the notebook
server must be configured to trust the certificate generated before connecting to the notebook
server. Also, when the generated certificate expires, a new certificate must be generated and trusted
on all local machines. For more information about the setup, see Self-signed certificates (p. 211).
For more information, see Self-signed certificate in Wikipedia.
3. Using SSH, connect to the Amazon EC2 instance that is running your notebook server; for example:
The ec2-private-key is the key that is needed to access the Amazon EC2 instance. When you
created the notebook server, you provided an Amazon EC2 key pair and saved this EC2 private key to
your local machine. You might need to edit the Copy certificate command to point to the key file on
your local machine. You can also find this key file name on the Amazon EC2 console details for your
notebook server.
The dns-address-of-ec2-instance is the address of the Amazon EC2 instance where the
keystore is copied.
208
AWS Glue Developer Guide
Notebook Server Considerations
• Asks for a Zeppelin notebook password: The password is SHA-256 hashed plus salted-and-
iterated with a random 128-bit salt kept in the shiro.ini file with restricted access. This is the
best practice available to Apache Shiro, the authorization package that Apache Zeppelin uses.
• Generates SSH public and private keys: The script overwrites any existing SSH public key on
the development endpoint that is associated with the notebook server. As a result, any other
notebook servers, Read–Eval–Print Loops (REPLs), or IDEs that connect to this development
endpoint can no longer connect.
• Verifies or generates an SSL certificate: Either use an SSL certificate that was generated with
a certificate authority (CA) or generate a certificate with this script. If you copied a certificate,
the script asks for the location of the keystore file. Provide the entire path on the Amazon EC2
instance, for example, /home/ec2-user/keystore.jks. The SSL certificate is verified.
Starting notebook server setup. See AWS Glue documentation for more details.
Press Enter to continue...
Attempting to reach AWS Glue to update DevEndpoint's public key. This might take a
while.
Waiting for DevEndpoint update to complete...
Waiting for DevEndpoint update to complete...
Waiting for DevEndpoint update to complete...
DevEndpoint updated to use the public key generated.
Configuring Zeppelin server...
209
AWS Glue Developer Guide
Notebook Server Considerations
********************
We will configure Zeppelin to be a HTTPS server. You can upload a CA signed certificate
for the server to consume (recommended). Or you can choose to have a self-signed
certificate created.
See AWS Glue documentation for additional information on using SSL/TLS certificates.
********************
Do you have a JKS keystore to encrypt HTTPS requests? If not, a self-signed certificate
will be generated. [y/n] n
Generating self-signed SSL/TLS certificate at /home/ec2-user/
ec2-192-0-2-0.compute-1.amazonaws.com.jks
Self-signed certificates successfully generated.
Exporting the public key certificate to /home/ec2-user/
ec2-192-0-2-0.compute-1.amazonaws.com.der
Certificate stored in file /home/ec2-user/ec2-192-0-2-0.compute-1.amazonaws.com.der
Configuring Zeppelin to use the keystore for SSL connection...
**********
The public key certificate is exported to /home/ec2-user/
ec2-192-0-2-0.compute-1.amazonaws.com.der
The SHA-256 fingerprint for the certificate is
53:39:12:0A:2B:A5:4A:37:07:A0:33:34:15:B7:2B:6F:ED:35:59:01:B9:43:AF:B9:50:55:E4:A2:8B:3B:59:E6.
You may need it when importing the certificate to the client. See AWS Glue
documentation for more details.
**********
5. Check for errors with trying to start the Zeppelin server in the log files located at /home/ec2-
user/zeppelin/logs/.
1. Connect with a trusted CA certificate. If you provided an SSL certificate from a certificate authority
(CA) when the Zeppelin server was set up on the Amazon EC2 instance, choose this method. To
connect with HTTPS on port 443, open a web browser and enter the URL for the notebook server.
You can find this URL on the development notebook details page for your notebook server. Enter
the contents of the HTTPS URL field; for example:
https://public-dns-address-of-ec2-instance:443
210
AWS Glue Developer Guide
Notebook Server Considerations
1. Access the SSL certificate from the local computer. For some scenarios, this requires you to copy
the SSL certificate from the Amazon EC2 instance to the local computer; for example:
2. Import and view (or view and then import) the certificate into the certificate manager that is used
by your operating system and browser. Verify that it matches the certificate generated on the
Amazon EC2 instance.
In Firefox, you might encounter an error like Your connection is not secure. To set up the
connection, the general steps are as follows (the steps might vary by Firefox version):
1. Find the Options or Preferences page, navigate to the page and choose View Certificates. This
option might appear in the Privacy, Security, or Advanced tab.
2. In the Certificate Manager window, choose the Servers tab, and then choose Add Exception.
3. Enter the HTTPS Location of the notebook server on Amazon EC2, and then choose Get
Certificate. Choose View.
4. Verify that the Common Name (CN) matches the DNS of the notebook server Amazon EC2
instance. Also, verify that the SHA-256 Fingerprint matches that of the certificate generated on
the Amazon EC2 instance. You can find the SHA-256 fingerprint of the certificate in the output of
the setup_notebook_server.py script or by running an openssl command on the notebook
instance.
When using Chrome on macOS, you might encounter an error like Your connection is not private.
To set up the connection, the general steps are as follows:
1. Copy the SSL certificate from the Amazon EC2 instance to your local computer.
2. Choose Preferences or Settings to find the Settings page. Navigate to the Advanced section, and
then find the Privacy and security section. Choose Manage certificates.
3. In the Keychain Access window, navigate to the Certificates and choose File, Import items to
import the SSL certificate.
4. Verify that the Common Name (CN) matches the DNS of the notebook server Amazon EC2
instance. Also, verify that the SHA-256 Fingerprint matches that of the certificate generated on
the Amazon EC2 instance. You can find the SHA-256 fingerprint of the certificate in the output of
the setup_notebook_server.py script or by running an openssl command on the notebook
instance.
211
AWS Glue Developer Guide
Notebook Server Considerations
When using Chrome on Windows, you might encounter an error like Your connection is not private.
To set up the connection, the general steps are as follows:
1. Copy the SSL certificate from the Amazon EC2 instance to your local computer.
2. Find the Settings page, navigate to the Advanced section, and then find the Privacy and security
section. Choose Manage certificates.
3. In the Certificates window, navigate to the Trusted Root Certification Authorities tab, and
choose Import to import the SSL certificate.
4. Place the certificate in the Certificate store for Trusted Root Certification Authorities.
5. Trust by installing the certificate.
6. Verify that the SHA-1 Thumbprint that is displayed by the certificate in the browser matches that
of the certificate generated on the Amazon EC2 instance. To find the certificate on the browser,
navigate to the list of Trusted Root Certification Authorities, and choose the certificate Issued
To the Amazon EC2 instance. Choose to View the certificate, choose Details, and then view the
Thumbprint for sha1. You can find the corresponding SHA-1 fingerprint of the certificate by
running an openssl command on the Amazon EC2 instance.
7. When the certificate expires, generate a new certificate on the Amazon EC2 instance and trust it
on your local computer.
When using Internet Explorer on Windows, you might encounter an error like Your connection is not
private. To set up the connection, the general steps are as follows:
1. Copy the SSL certificate from the Amazon EC2 instance to your local computer.
2. Find the Internet Options page, navigate to the Content tab, and then find the Certificates
section.
3. In the Certificates window, navigate to the Trusted Root Certification Authorities tab, and
choose Import to import the SSL certificate.
4. Place the certificate in the Certificate store for Trusted Root Certification Authorities.
5. Trust by installing the certificate.
6. Verify that the SHA-1 Thumbprint that is displayed by the certificate in the browser matches that
of the certificate generated on the Amazon EC2 instance. To find the certificate on the browser,
navigate to the list of Trusted Root Certification Authorities, and choose the certificate Issued
To the Amazon EC2 instance. Choose to View the certificate, choose Details, and then view the
Thumbprint for sha1. You can find the corresponding SHA-1 fingerprint of the certificate by
running an openssl command on the Amazon EC2 instance.
212
AWS Glue Developer Guide
Notebooks on the Console
7. When the certificate expires, generate a new certificate on the Amazon EC2 instance and trust it
on your local computer.
After you trust the certificate, to connect with HTTPS on port 443, open a web browser and enter
the URL for the notebook server. You can find this URL on the development notebook details page
for your notebook server. Enter the contents of the HTTPS URL field; for example:
https://public-dns-address-of-ec2-instance:443
AWS Glue provides an interface to Amazon SageMaker notebooks and Apache Zeppelin notebook
servers. On the AWS Glue notebooks page, you can create Amazon SageMaker notebooks and attach
them to a development endpoint. You can also manage Zeppelin notebook servers that you created and
attached to a development endpoint. To create a Zeppelin notebook server, see Creating a Notebook
Server Hosted on Amazon EC2 (p. 187).
The Notebooks page on the AWS Glue console lists all the Amazon SageMaker notebooks and Zeppelin
notebook servers in your AWS Glue environment. You can use the console to perform several actions
on your notebooks. To display details for a notebook or notebook server, choose the notebook in the
list. Notebook details include the information that you defined when you created it using the Create
SageMaker notebook or Create Zeppelin Notebook server wizard.
Important
AWS Glue only manages Amazon SageMaker notebooks in certain AWS Regions. For more
information, see Managing Notebooks (p. 205).
Ensure you have permissions to manage Amazon SageMaker notebooks in the AWS Glue console. For
more information, see AWSGlueConsoleSageMakerNotebookFullAccess in Step 3: Attach a Policy to
IAM Users That Access AWS Glue (p. 15).
Notebook name
The name of the development endpoint that this notebook is attached to.
Important
This development endpoint must have been created after August 15, 2018.
213
AWS Glue Developer Guide
Notebooks on the Console
Status
The provisioning status of the notebook and whether it is Ready, Failed, Starting, Stopping, or
Stopped.
Failure reason
The IAM role that was used to create the Amazon SageMaker notebook.
This role has a trust relationship to Amazon SageMaker. You create this role in the IAM console.
When creating the role, choose Amazon SageMaker, and attach a policy for the notebook, such as
AWSGlueServiceSageMakerNotebookRoleDefault. For more information, see Step 7: Create an IAM
Role for Amazon SageMaker Notebooks (p. 28).
The unique name that you give the endpoint when you create it.
Provisioning status
The name of the AWS CloudFormation stack that was used to create the notebook server.
EC2 instance
The name of Amazon EC2 instance that is created to host your notebook. This links to the Amazon
EC2 console (https://console.aws.amazon.com/ec2/) where the instance is tagged with the key aws-
glue-dev-endpoint and value of the name of the development endpoint.
SSH to EC2 server command
Enter this command in a terminal window to connect to the Amazon EC2 instance that is running
your notebook server. The Amazon EC2 address shown in this command is either public or private,
depending on whether you chose to Attach a public IP to the notebook server EC2 instance.
Copy certificate
Example scp command to copy the keystore that is required to set up the Zeppelin notebook server
to the Amazon EC2 instance that hosts the notebook server. Run the command from a terminal
window in the directory where the Amazon EC2 private key is located. The key to access the Amazon
EC2 instance is the parameter to the -i option. You provide the path-to-keystore-file. The
214
AWS Glue Developer Guide
Notebooks on the Console
remaining part of the command is the location where the development endpoint private SSH key on
the Amazon EC2 server is located.
HTTPS URL
After setting up a notebook server, enter this URL in a browser to connect to your notebook using
HTTPS.
215
AWS Glue Developer Guide
The main objective of AWS Glue is to provide an easier way to extract and transform your data from
source to target. To accomplish this objective, an ETL job follows these typical steps (as shown in the
diagram that follows):
1. A trigger fires to initiate a job run. This event can be set up on a recurring schedule or to satisfy a
dependency.
2. The job extracts data from your source. If required, connection properties are used to access your
source.
3. The job transforms your data using a script that you created and the values of any arguments. The
script contains the Scala or PySpark Python code that transforms your data.
4. The transformed data is loaded to your data targets. If required, connection properties are used to
access the target.
5. Statistics are collected about the job run and are written to your Data Catalog.
The following diagram shows the ETL workflow containing these five steps.
216
AWS Glue Developer Guide
Automated Tools
Topics
• Automated Monitoring Tools (p. 217)
• Time-Based Schedules for Jobs and Crawlers (p. 217)
• Tracking Processed Data Using Job Bookmarks (p. 219)
• AWS Tags in AWS Glue (p. 224)
• Automating AWS Glue with CloudWatch Events (p. 226)
• Monitoring Jobs Using the Apache Spark Web UI (p. 228)
• Monitoring with Amazon CloudWatch (p. 237)
• Job Monitoring and Debugging (p. 254)
• Logging AWS Glue API Calls with AWS CloudTrail (p. 275)
You can use the following automated monitoring tools to watch AWS Glue and report when something is
wrong:
• Amazon CloudWatch Events delivers a near real-time stream of system events that describe changes
in AWS resources. CloudWatch Events enables automated event-driven computing. You can write rules
that watch for certain events and trigger automated actions in other AWS services when these events
occur. For more information, see the Amazon CloudWatch Events User Guide.
• Amazon CloudWatch Logs enables you to monitor, store, and access your log files from Amazon EC2
instances, AWS CloudTrail, and other sources. CloudWatch Logs can monitor information in the log
files and notify you when certain thresholds are met. You can also archive your log data in highly
durable storage. For more information, see the Amazon CloudWatch Logs User Guide.
• AWS CloudTrail captures API calls and related events made by or on behalf of your AWS account
and delivers the log files to an Amazon S3 bucket that you specify. You can identify which users and
accounts call AWS, the source IP address from which the calls are made, and when the calls occur. For
more information, see the AWS CloudTrail User Guide.
Cron Expressions
Cron expressions have six required fields, which are separated by white space.
Syntax
217
AWS Glue Developer Guide
Cron Expressions
Wildcards
• The , (comma) wildcard includes additional values. In the Month field, JAN,FEB,MAR would include
January, February, and March.
• The - (dash) wildcard specifies ranges. In the Day field, 1–15 would include days 1 through 15 of the
specified month.
• The * (asterisk) wildcard includes all values in the field. In the Hours field, * would include every hour.
• The / (forward slash) wildcard specifies increments. In the Minutes field, you could enter 1/10 to
specify every 10th minute, starting from the first minute of the hour (for example, the 11th, 21st, and
31st minute).
• The ? (question mark) wildcard specifies one or another. In the Day-of-month field you could enter
7, and if you didn't care what day of the week the seventh was, you could enter ? in the Day-of-week
field.
• The L wildcard in the Day-of-month or Day-of-week fields specifies the last day of the month or
week.
• The W wildcard in the Day-of-month field specifies a weekday. In the Day-of-month field, 3W
specifies the day closest to the third weekday of the month.
Limits
• You can't specify the Day-of-month and Day-of-week fields in the same cron expression. If you
specify a value in one of the fields, you must use a ? (question mark) in the other.
• Cron expressions that lead to rates faster than 5 minutes are not supported.
Examples
When creating a schedule, you can use the following sample cron strings.
0 10 * * ? * Run at 10:00
am (UTC)
every day
15 12 * * ? * Run at 12:15
pm (UTC)
every day
0 18 ? * MON-FRI * Run at
6:00 pm
(UTC) every
218
AWS Glue Developer Guide
Job Bookmarks
0 8 1 * ? * Run at 8:00
am (UTC)
every first
day of the
month
cron(15 12 * * ? *)
Job bookmarks are implemented for some Amazon Simple Storage Service (Amazon S3) sources and the
Relationalize transform. The following table lists the Amazon S3 source formats that AWS Glue supports
for job bookmarks.
219
AWS Glue Developer Guide
Using Job Bookmarks
Version 1.0 and later JSON, CSV, Apache Avro, XML, Parquet, ORC
For information about Glue versions, see Defining Job Properties (p. 162).
Job bookmarks are implemented for a limited use case for a relational database (JDBC connection)
input source. For this input source, job bookmarks are supported only if the table's primary keys are
in sequential order. Also, job bookmarks search for new rows, but not updated rows. This is because
bookmarks look for the primary keys, which already exist.
Topics
• Using Job Bookmarks in AWS Glue (p. 220)
• Using Job Bookmarks with the AWS Glue Generated Script (p. 221)
• Tracking Files Using Modification Timestamps (p. 223)
Enable Causes the job to update the state after a run to keep track of previously
processed data. If your job has a source with job bookmark support, it will
keep track of processed data, and when a job runs, it processes new data
since the last checkpoint.
Disable Job bookmarks are not used, and the job always processes the entire
dataset. You are responsible for managing the output from previous job
runs. This is the default.
Pause Process incremental data since the last successful run or the data in the
range identified by the following sub-options, without updating the state of
last bookmark. You are responsible for managing the output from previous
job runs. The two sub-options are:
The job bookmark state is not updated when this option set is specified.
The sub-options are optional, however when used both the sub-options
needs to be provided.
For details about the parameters passed to a job, and specifically for a job bookmark, see Special
Parameters Used by AWS Glue (p. 296).
220
AWS Glue Developer Guide
Using an AWS Glue Script
For Amazon S3 input sources, AWS Glue job bookmarks check the last modified time of the objects to
verify which objects need to be reprocessed. If your input source data has been modified since your last
job run, the files are reprocessed when you run the job again.
You can rewind your job bookmarks for your Glue Spark ETL jobs to any previous job run. You can
support data backfilling scenarios better by rewinding your job bookmarks to any previous job run,
resulting in the subsequent job run reprocessing data only from the bookmarked job run.
If you intend to reprocess all the data using the same job, reset the job bookmark. To reset
the job bookmark state, use the AWS Glue console, the ResetJobBookmark Action (Python:
reset_job_bookmark) (p. 554) API operation, or the AWS CLI. For example, enter the following
command using the AWS CLI:
AWS Glue keeps track of job bookmarks by job. If you delete a job, the job bookmark is deleted.
In some cases, you might have enabled AWS Glue job bookmarks but your ETL job is reprocessing data
that was already processed in an earlier run. For information about resolving common causes of this
error, see Troubleshooting Errors in AWS Glue (p. 288).
Transformation Context
Many of the AWS Glue PySpark dynamic frame methods include an optional parameter
named transformation_ctx, which is a unique identifier for the ETL operator instance. The
transformation_ctx parameter is used to identify state information within a job bookmark for the
given operator. Specifically, AWS Glue uses transformation_ctx to index the key to the bookmark
state.
For job bookmarks to work properly, enable the job bookmark parameter and set the
transformation_ctx parameter. If you don't pass in the transformation_ctx parameter, then
job bookmarks are not enabled for a dynamic frame or a table used in the method. For example,
if you have an ETL job that reads and joins two Amazon S3 sources, you might choose to pass the
transformation_ctx parameter only to those methods that you want to enable bookmarks. If you
reset the job bookmark for a job, it resets all transformations that are associated with the job regardless
of the transformation_ctx used.
For more information about the DynamicFrameReader class, see DynamicFrameReader Class (p. 350).
For more information about PySpark extensions, see AWS Glue PySpark Extensions Reference (p. 333).
Job bookmarks store the states for a job. Each instance of the state is keyed by a job name and a version
number. When a script invokes job.init, it retrieves its state and always gets the latest version. Within
a state, there are multiple state elements, which are specific to each source, transformation, and sink
instance in the script. These state elements are identified by a transformation context that is attached to
the corresponding element (source, transformation, or sink) in the script. The state elements are saved
atomically when job.commit is invoked from the user script. The script gets the job name and the
control option for the job bookmarks from the arguments.
221
AWS Glue Developer Guide
Using an AWS Glue Script
The state elements in the job bookmark are source, transformation, or sink-specific data. For example,
suppose that you want to read incremental data from an Amazon S3 location that is being constantly
written to by an upstream job or process. In this case, the script must determine what has been
processed so far. The job bookmark implementation for the Amazon S3 source saves information so that
when the job runs again, it can filter only the new objects using the saved information and recompute
the state for the next run of the job. A timestamp is used to filter the new files.
In addition to the state elements, job bookmarks have a run number, an attempt number, and a version
number. The run number tracks the run of the job, and the attempt number records the attempts for
a job run. The job run number is a monotonically increasing number that is incremented for every
successful run. The attempt number tracks the attempts for each run, and is only incremented when
there is a run after a failed attempt. The version number increases monotonically and tracks the updates
to a job bookmark.
The following is an example of the generated script. The script and its associated arguments illustrate
the various elements that are required for using job bookmarks. For more information about these
elements see the GlueContext Class (p. 352) API, and the DynamicFrameWriter Class (p. 349) API.
# Sample Script
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
*job = Job(glueContext)*
*job.init(args['JOB_NAME'], args)*
## @type: DataSource
## @args: [database = "database", table_name = "relatedqueries_csv", transformation_ctx =
"datasource0"]
## @return: datasource0
## @inputs: []
datasource0 = glueContext.create_dynamic_frame.from_catalog(database = "database",
table_name = "relatedqueries_csv", *transformation_ctx = "datasource0")*
## @type: ApplyMapping
## @args: [mapping = [("col0", "string", "name", "string"), ("col1", "string", "number",
"string")], transformation_ctx = "applymapping1"]
## @return: applymapping1
## @inputs: [frame = datasource0]
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [("col0", "string",
"name", "string"), ("col1", "string", "number", "string")], *transformation_ctx =
"applymapping1"*)
## @type: DataSink
## @args: [connection_type = "s3", connection_options = {"path": "s3://input_path"}, format
= "json", transformation_ctx = "datasink2"]
## @return: datasink2
## @inputs: [frame = applymapping1]
datasink2 = glueContext.write_dynamic_frame.from_options(frame = applymapping1,
connection_type = "s3", connection_options = {"path": "s3://input_path"}, format =
"json", *transformation_ctx = "datasink2"*)
*job.commit()*
Job Arguments :
*--job-bookmark-option, job-bookmark-enable*
*--JOB_NAME, name-1-s3-2-s3-encrypted*
222
AWS Glue Developer Guide
Using Modification Timestamps
Consider the following example. In the diagram, the X axis is a time axis, from left to right, with the left-
most point being T0. The Y axis is list of files observed at time T. The elements representing the list are
placed in the graph based on their modification time.
In this example, when a job starts at modification timestamp 1 (T1), it looks for files that have a
modification time greater than T0 and less than or equal to T1. Those files are F2, F3, F4, and F5. The job
bookmark stores the timestamps T0 and T1 as the low and high timestamps respectively.
When the job reruns at T2, it filters files that have a modification time greater than T1 and less than or
equal to T2. Those files are F7, F8, F9, and F10. It thereby misses the files F3', F4', and F5'. The reason
that the files F3', F4', and F5', which have a modification time less than or equal to T1, show up after T1 is
because of Amazon S3 list consistency.
To account for Amazon S3 eventual consistency, AWS Glue includes a list of files (or path hash) in the
job bookmark. AWS Glue assumes that the Amazon S3 file list is only inconsistent up to a finite period
(dt) before the current time. That is, the file list for files with a modification time between T1 - dt and T1
when listing is done at T1 is inconsistent. However, the list of files with a modification time less than or
equal to T1 - d1 is consistent at a time greater than or equal to T1.
You specify the period of time in which AWS Glue will save files (and where the files are likely to be
consistent) by using the MaxBand option in the AWS Glue connection options. The default value is 900
223
AWS Glue Developer Guide
AWS Tags
seconds (15 minutes). For more information about this property, see Connection Types and Options for
ETL in AWS Glue (p. 298).
When the job reruns at timestamp 2 (T2), it lists the files in the following ranges:
• T1 - dt (exclusive) to T1 (inclusive). This list includes F4, F5, F4', and F5'. This list is a consistent range.
However, this range is inconsistent for a listing at T1 and has a list of files F3, F4, and F5 saved. For
getting the files to be processed at T2, the files F3, F4, and F5 will be removed.
• T1 (exclusive) to T2 - dt (inclusive). This list includes F7 and F8. This list is a consistent range.
• T2 - dt (exclusive) - T2 (inclusive). This list includes F9 and F10. This list is an inconsistent range.
The resultant list of files is F3', F4', F5', F7, F8, F9, and F10.
The new files in the inconsistent list are F9 and F10, which are saved in the filter for the next run.
For more information about Amazon S3 eventual consistency, see Introduction to Amazon S3 in the
Amazon Simple Storage Service Developer Guide.
If a job run fails before the job.commit() (at T1), the files are processed in a subsequent run, in which
AWS Glue processes the files from T0 to T2.
• Crawler
• Job
• Trigger
• Development endpoint
Note
As a best practice, to allow tagging of these AWS Glue resources, always include the
glue:TagResource action in your policies.
224
AWS Glue Developer Guide
Examples
• The tag key and the tag value must not contain the prefix aws. No operations are allowed on such tags.
• The maximum tag key length is 128 Unicode characters in UTF-8. The tag key must not be empty or
null.
• The maximum tag value length is 256 Unicode characters in UTF-8. The tag value may be empty or
null.
Examples
The following examples create a job with assigned tags.
AWS CLI
{
"Description": "AWS Glue Job Test Tags",
"Resources": {
"MyJobRole": {
"Type": "AWS::IAM::Role",
"Properties": {
"AssumeRolePolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Service": [
"glue.amazonaws.com"
]
},
"Action": [
"sts:AssumeRole"
]
}
]
},
"Path": "/",
"Policies": [
{
"PolicyName": "root",
"PolicyDocument": {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "*",
"Resource": "*"
}
]
}
}
]
}
},
"MyJob": {
"Type": "AWS::Glue::Job",
"Properties": {
225
AWS Glue Developer Guide
Automating with CloudWatch Events
"Command": {
"Name": "glueetl",
"ScriptLocation": "s3://aws-glue-scripts//prod-job1"
},
"DefaultArguments": {
"--job-bookmark-option": "job-bookmark-enable"
},
"ExecutionProperty": {
"MaxConcurrentRuns": 2
},
"MaxRetries": 0,
"Name": "cf-job1",
"Role": {
"Ref": "MyJobRole",
"Tags": {
"key1": "value1", "key2":"value2"
}
}
}
}
}
}
For information about how to control access using tags, see Identity-Based Policies (IAM Policies) with
Tags (p. 55).
Some examples of using CloudWatch Events with AWS Glue include the following:
• Events for "detail-type":"Glue Job State Change" are generated for SUCCEEDED, FAILED,
TIMEOUT, and STOPPED.
• Events for "detail-type":"Glue Job Run Status" are generated for RUNNING, STARTING, and
STOPPING job runs when they exceed the job delay notification threshold.
226
AWS Glue Developer Guide
Automating with CloudWatch Events
• Events for "detail-type":"Glue Crawler State Change" are generated for Started,
Succeeded, and Failed.
• Events for "detail-type":"Glue Data Catalog Database State Change" are generated for
CreateDatabase, DeleteDatabase, CreateTable, DeleteTable and BatchDeleteTable. For
example, if a table is created or deleted, a notification is sent to CloudWatch Events. Note that you
cannot write a program that depends on the order or existence of notification events, as they might be
out of sequence or missing. Events are emitted on a best effort basis. In the details of the notification:
• The typeOfChange contains the name of the API operation.
• The databaseName contains the name of the affected database.
• The changedTables contains up to 100 names of affected tables per notification. When table
names are long, multiple notifications might be created.
• Events for "detail-type":"Glue Data Catalog Table State Change" are generated
for UpdateTable, CreatePartition, BatchCreatePartition, DeletePartition and
BatchDeletePartition. For example, if a table or partition is updated, a notification is sent to
CloudWatch Events. Note that you cannot write a program that depends on the order or existence of
notification events, as they might be out of sequence or missing. Events are emitted on a best effort
basis. In the details of the notification:
• The typeOfChange contains the name of the API operation.
• The databaseName contains the name of the database that contains the affected resources.
• The tableName contains the name of the affected table.
• The changedPartitions specifies up to 100 affected partitions in one notification. When partition
names are long, multiple notifications might be created.
For example if there are two partition keys, Year and Month, then "2018,01", "2018,02"
modifies the partition where "Year=2018" and "Month=01" and the partition where
"Year=2018" and "Month=02".
{
"version":"0",
"id":"abcdef00-1234-5678-9abc-def012345678",
"detail-type":"Glue Data Catalog Table State Change",
"source":"aws.glue",
"account":"123456789012",
"time":"2017-09-07T18:57:21Z",
"region":"us-west-2",
"resources":["arn:aws:glue:us-west-2:123456789012:database/default/foo"],
"detail":{
"changedPartitions": [
"2018,01",
"2018,02"
],
"databaseName": "default",
"tableName": "foo",
"typeOfChange": "BatchCreatePartition"
}
}
For more information, see the Amazon CloudWatch Events User Guide. For events specific to AWS Glue,
see AWS Glue Events.
227
AWS Glue Developer Guide
Monitoring with the Spark UI
You can enable the Spark UI using the AWS Glue console or the AWS Command Line Interface (AWS CLI).
When you enable the Spark UI, AWS Glue ETL jobs and Spark applications on AWS Glue development
endpoints can persist Spark event logs to a location that you specify in Amazon Simple Storage Service
(Amazon S3). AWS Glue also provides a sample AWS CloudFormation template to start the Spark history
server and show the Spark UI using the event logs. The persisted event logs in Amazon S3 can be used
with the Spark UI both in real time as the job is executing and after the job is complete.
The following is an example of a Spark application which reads from two data sources, performs a join
transform, and writes it out to Amazon S3 in Parquet format.
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
from pyspark.sql.functions import count, when, expr, col, sum, isnull
from pyspark.sql.functions import countDistinct
from awsglue.dynamicframe import DynamicFrame
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'])
df_persons = spark.read.json("s3://awsglue-datasets/examples/us-legislators/all/
persons.json")
df_memberships = spark.read.json("s3://awsglue-datasets/examples/us-legislators/all/
memberships.json")
job.commit()
The following DAG visualization shows the different stages in this Spark job.
228
AWS Glue Developer Guide
Monitoring with the Spark UI
The following event timeline for a job shows the start, execution, and termination of different Spark
executors.
229
AWS Glue Developer Guide
Monitoring with the Spark UI
The following screen shows the details of the SparkSQL query plans:
230
AWS Glue Developer Guide
Monitoring with the Spark UI
231
AWS Glue Developer Guide
Enabling the Spark UI for Jobs
You can still use AWS Glue continuous logging to view the Spark application log streams for Spark driver
and executors. For more information, see Continuous Logging for AWS Glue Jobs.
Topics
• Enabling the Apache Spark Web UI for AWS Glue Jobs (p. 232)
• Enabling the Apache Spark Web UI for Development Endpoints (p. 233)
• Launching the Spark History Server (p. 234)
Topics
• Configuring the Spark UI (Console) (p. 232)
• Configuring the Spark UI (AWS CLI) (p. 233)
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. In the navigation pane, choose Jobs.
3. Choose Add job.
4. In Configure the job properties, open the Monitoring options.
5. In the Spark UI tab, choose Enable.
6. Specify an Amazon S3 path for storing the Spark event logs for the job.
232
AWS Glue Developer Guide
Enabling the Spark UI for Dev Endpoints
'--enable-spark-ui': 'true',
'--spark-event-logs-path': 's3://s3-event-log-path'
Every 30 seconds, AWS Glue flushes the Spark event logs to the Amazon S3 path that you specify.
Topics
• Enabling the Spark UI (Console) (p. 233)
• Enabling the Spark UI (AWS CLI) (p. 233)
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. In the navigation pane, choose Dev endpoints.
3. Choose Add endpoint.
4. In Configuration, open the Spark UI options.
5. In the Spark UI tab, choose Enable.
233
AWS Glue Developer Guide
Launching the Spark History Server
{
"EndpointName": "Name",
"RoleArn": "role_ARN",
"PublicKey": "public_key_contents",
"NumberOfNodes": 2,
"Arguments": {
"--enable-spark-ui": "true",
"--spark-event-logs-path": "s3://s3-event-log-path"
}
}
Topics
• Launching the Spark History Server and Viewing the Spark UI Using AWS CloudFormation (p. 234)
• Launching the Spark History Server and Viewing the Spark UI Using Docker (p. 236)
To start the Spark history server and view the Spark UI using AWS CloudFormation
1. Choose one of the Launch Stack buttons in the following table. This launches the stack on the AWS
CloudFormation console.
234
AWS Glue Developer Guide
Launching the Spark History Server
EU (Frankfurt) View
EU (Ireland) View
EU (London) View
EU (Paris) View
EU (Stockholm) View
a. Spark UI Configuration
• IP address range — The IP address range that can be used to view the Spark UI. If you want
to restrict access from a specific IP address range, you should use a custom value.
• History server port — The port for the Spark UI. You can use the default value.
• Event log directory — Choose the location where Spark event logs are stored from the AWS
Glue job or development endpoints. You must use s3a:// for the event logs path scheme.
• Spark package location — You can use the default value.
• Keystore path — SSL/TLS keystore path for HTTPS. If you want to use a custom keystore file,
you can specify the S3 path s3://path_to_your_keystore_file here. If you leave this
parameter empty, a self-signed certificate based keystore is generated and used.
Note
With a self-signed certificate based keystore, each local machine that connects to
the Spark UI must be configured to trust the certificate generated before connecting
to the Spark UI. Also, when the generated certificate expires, a new certificate must
be generated and trusted on all local machines. For more information about the
235
AWS Glue Developer Guide
Launching the Spark History Server
setup, see Self-signed certificates. For more information, see Self-signed certificate
in Wikipedia.
• Keystore password — SSL/TLS keystore password for HTTPS.
b. EC2 Instance Configuration
• Instance type — The type of Amazon EC2 instance that hosts the Spark history server.
Because this template launches Amazon EC2 instance in your account, Amazon EC2 cost will
be charged in your account separately.
• Latest AMI ID — The AMI ID of Amazon Linux 2 for the Spark history server instance. You can
use the default value.
• VPC ID — The virtual private cloud (VPC) ID for the Spark history server instance. You can use
any of the VPCs available in your account Using a default VPC with a default Network ACL is
not recommended. For more information, see Default VPC and Default Subnets and Creating
a VPC in the Amazon VPC User Guide.
• Subnet ID — The ID for the Spark history server instance. You can use any of the subnets in
your VPC. You must be able to reach the network from your client to the subnet. If you want
to access via the internet, you must use a public subnet that has the internet gateway in the
route table.
4. On the Configure stack options page, choose Next.
5. On the Review page, review the template. Select I acknowledge that AWS CloudFormation might
create IAM resources, and then choose Create stack.
6. Wait for the stack to be created.
7. Open the Outputs tab.
Prerequisites
For information about how to install Docker on your laptop see the Docker Engine community.
To start the Spark history server and view the Spark UI locally using Docker
• Download the Dockerfile and pom.xml from AWS Glue code samples.
2. Run the following commands:
236
AWS Glue Developer Guide
Monitoring with CloudWatch
AWS Glue also supports real-time continuous logging for AWS Glue jobs. When continuous logging is
enabled for a job, you can view the real-time logs on the AWS Glue console or the CloudWatch console
dashboard. For more information, see Continuous Logging for AWS Glue Jobs (p. 251).
Topics
• Monitoring AWS Glue Using Amazon CloudWatch Metrics (p. 237)
• Setting Up Amazon CloudWatch Alarms on AWS Glue Job Profiles (p. 251)
• Continuous Logging for AWS Glue Jobs (p. 251)
You can view summary or detailed graphs of metrics for a job, or detailed graphs for a job run. For
details about the graphs and metrics you can access in the AWS Glue console dashboard, see Working
with Jobs on the AWS Glue Console (p. 171).
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. In the navigation pane, choose Jobs.
3. Select a job from the Jobs list.
237
AWS Glue Developer Guide
Using CloudWatch Metrics
Metrics are grouped first by the service namespace, and then by the various dimension combinations
within each namespace.
AWS Glue reports metrics to CloudWatch every 30 seconds, and the CloudWatch metrics dashboards
are configured to display them every minute. The AWS Glue metrics represent delta values from the
previously reported values. Where appropriate, metrics dashboards aggregate (sum) the 30-second
values to obtain a value for the entire last minute. AWS Glue metrics are enabled at initialization of
a GlueContext in a script and are generally updated only at the end of an Apache Spark task. They
represent the aggregate values across all completed Spark tasks so far.
However, the Spark metrics that AWS Glue passes on to CloudWatch are generally absolute values
representing the current state at the time they are reported. AWS Glue reports them to CloudWatch
every 30 seconds, and the metrics dashboards generally show the average across the data points
received in the last 1 minute.
AWS Glue metrics names are all preceded by one of the following types of prefix:
• glue.driver. – Metrics whose names begin with this prefix either represent AWS Glue metrics that
are aggregated from all executors at the Spark driver, or Spark metrics corresponding to the Spark
driver.
• glue.executorId. – The executorId is the number of a specific Spark executor. It corresponds with the
executors listed in the logs.
• glue.ALL. – Metrics whose names begin with this prefix aggregate values from all Spark executors.
Metric Description
glue.driver.aggregate.bytesRead The number of bytes read from all data sources by all
completed Spark tasks running in all executors..
238
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Valid Statistics: SUM. This metric is a delta value from
the last reported value, so on the AWS Glue Metrics
Dashboard, a SUM statistic is used for aggregation.
Unit: Bytes
• Bytes read.
• Job progress.
• JDBC data sources.
• Job Bookmark Issues.
• Variance across Job Runs.
Unit: Milliseconds
239
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Unit: Count
• Job progress.
• Per-stage timeline of job execution,when correlated
with other metrics.
Unit: Count
• Job progress.
• Parallelism within a stage.
240
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Unit: Count
Unit: Count
241
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
glue.driver.aggregate.recordsRead The number of records read from all data sources by all
completed Spark tasks running in all executors.
Unit: Count
• Records read.
• Job progress.
• JDBC data sources.
• Job Bookmark Issues.
• Skew in Job Runs over days.
Unit: Bytes
242
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Unit: Bytes
Unit: Megabytes
243
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Unit: Count
• Job activity.
• Straggling executors (with a few executors running
only)
• Current executor-level parallelism.
244
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Unit: Count
• Job activity.
• Current executor-level parallelism and backlog
of pending tasks not yet scheduled because of
unavailable executors due to DPU capacity or killed/
failed executors.
245
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Unit: Percentage
246
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
glue.driver.jvm.heap.used The number of memory bytes used by the JVM heap for
the driver, the executor identified by executorId, or ALL
executors.
glue.executorId.jvm.heap.used
Valid dimensions: JobName (the name of the AWS Glue
Job), JobRunId (the JobRun ID. or ALL), and Type
glue.ALL.jvm.heap.used (gauge).
Unit: Bytes
247
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Unit: Bytes.
248
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Unit: Bytes
249
AWS Glue Developer Guide
Using CloudWatch Metrics
Metric Description
Unit: Percentage
Dimension Description
250
AWS Glue Developer Guide
Setting Up Amazon CloudWatch
Alarms on AWS Glue Job Profiles
• Jobs running out of memory (OOM): Set an alarm when the memory usage exceeds the normal
average for either the driver or an executor for an AWS Glue job.
• Straggling executors: Set an alarm when the number of executors falls below a certain threshold for a
large duration of time in an AWS Glue job.
• Data backlog or reprocessing: Compare the metrics from individual jobs in a workflow using a
CloudWatch math expression. You can then trigger an alarm on the resulting expression value (such as
the ratio of bytes written by a job and bytes read by a following job).
For detailed instructions on setting alarms, see Create or Edit a CloudWatch Alarm in the Amazon
CloudWatch Events User Guide.
For monitoring and debugging scenarios using CloudWatch, see Job Monitoring and
Debugging (p. 254).
When you start an AWS Glue job, it sends the real-time logging information to CloudWatch (every 5
seconds and before each executor termination) after the Spark application starts running. You can view
the logs on the AWS Glue console or the CloudWatch console dashboard.
• Continuous logging with a default filter to reduce high verbosity in the logs
• Continuous logging with no filter
• A custom script logger to log application-specific messages
• A console progress bar to track the running status of the current AWS Glue job
Topics
• Enabling Continuous Logging for AWS Glue Jobs (p. 251)
• Viewing Continuous Logging for AWS Glue Jobs (p. 254)
You can enable continuous logging with either a standard filter or no filter when you create a new job,
edit an existing job, or enable it through the AWS CLI. Choosing the Standard filter prunes out non-
251
AWS Glue Developer Guide
Continuous Logging for AWS Glue Jobs
useful Apache Spark driver/executor and Apache Hadoop YARN heartbeat log messages. Choosing No
filter gives you all the log messages.
You can also specify custom configuration options such as the AWS CloudWatch log group name,
CloudWatch log stream prefix before the AWS Glue job run ID driver/executor ID, and log conversion
pattern for log messages. These configurations help you to set aggregate logs in custom CloudWatch log
groups with different expiration policies, and analyze them further with custom log stream prefixes and
conversions patterns.
Topics
• Using the AWS Management Console (p. 252)
• Logging Application-Specific Messages Using the Custom Script Logger (p. 253)
• Enabling the Progress Bar to Show Job Progress (p. 254)
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. In the navigation pane, choose Jobs.
3. Choose Add job.
4. In Configure the job properties, choose Monitoring options.
5. In the Continuous logging tab, choose Enable.
6. Choose Standard filter or No filter.
To enable continuous logging for all newly created AWS Glue jobs
These user preferences are applied to all new jobs unless you override them explicitly when creating an
AWS Glue job or by editing an existing job as described previously.
252
AWS Glue Developer Guide
Continuous Logging for AWS Glue Jobs
To enable continuous logging, you pass in job parameters to an AWS Glue job. When you want to use the
standard filter, pass the following special job parameters similar to other AWS Glue job parameters. For
more information, see Special Parameters Used by AWS Glue (p. 296).
'--enable-continuous-cloudwatch-log': 'true'
'--enable-continuous-cloudwatch-log': 'true',
'--enable-continuous-log-filter': 'false'
You can specify a custom AWS CloudWatch log group name. If not specified, the default log group name
is /aws-glue/jobs/logs-v2/.
'--continuous-log-logGroup': 'custom_log_group_name'
You can specify a custom AWS CloudWatch log stream prefix. If not specified, the default log stream
prefix is the job run ID.
'--continuous-log-logStreamPrefix': 'custom_log_stream_prefix'
You can specify a custom continuous logging conversion pattern. If not specified, the default conversion
pattern is %d{yy/MM/dd HH:mm:ss} %p %c{1}: %m%n. Note that the conversion pattern only applies
to driver logs and executor logs. It does not affect the Glue progress bar.
'--continuous-log-conversionPattern': 'custom_log_conversion_pattern'
sc = SparkContext()
glueContext = GlueContext(sc)
logger = glueContext.get_logger()
logger.info("info message")
logger.warn("warn message")
logger.error("error message")
import com.amazonaws.services.glue.log.GlueLogger
object GlueApp {
def main(sysArgs: Array[String]) {
val logger = new GlueLogger
logger.info("info message")
logger.warn("warn message")
253
AWS Glue Developer Guide
Job Monitoring and Debugging
logger.error("error message")
}
}
The progress bar shows the following progress update every 5 seconds.
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. In the navigation pane, choose Jobs.
3. Add or start an existing job. Choose Action, Run job.
When you start running a job, you navigate to a page that contains information about the running
job:
You can view the driver logs, executor logs, and progress bar (if using the Standard filter).
254
AWS Glue Developer Guide
Debugging OOM Exceptions and Job Abnormalities
1. Enable the Job metrics option in the job definition. You can enable profiling in the AWS Glue console
or as a parameter to the job. For more information see Defining Job Properties (p. 162) or Special
Parameters Used by AWS Glue (p. 296).
2. Confirm that the job script initializes a GlueContext. For example, the following script snippet
initializes a GlueContext and shows where profiled code is placed in the script. This general format is
used in the debugging scenarios that follow.
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
import time
## @params: [JOB_NAME]
args = getResolvedOptions(sys.argv, ['JOB_NAME'])
sc = SparkContext()
glueContext = GlueContext(sc)
spark = glueContext.spark_session
job = Job(glueContext)
job.init(args['JOB_NAME'], args)
...
...
code-to-profile
...
...
job.commit()
Topics
• Debugging OOM Exceptions and Job Abnormalities (p. 255)
• Debugging Demanding Stages and Straggler Tasks (p. 262)
• Monitoring the Progress of Multiple Jobs (p. 266)
• Monitoring for DPU Capacity Planning (p. 270)
255
AWS Glue Developer Guide
Debugging OOM Exceptions and Job Abnormalities
The job run soon fails, and the following error appears in the History tab on the AWS Glue console:
Command Failed with Exit Code 1. This error string means that the job failed due to a systemic error—
which in this case is the driver running out of memory.
256
AWS Glue Developer Guide
Debugging OOM Exceptions and Job Abnormalities
On the console, choose the Error logs link on the History tab to confirm the finding about driver OOM
from the CloudWatch Logs. Search for "Error" in the job's error logs to confirm that it was indeed an
OOM exception that failed the job:
On the History tab for the job, choose Logs. You can find the following trace of driver execution in
the CloudWatch Logs at the beginning of the job. The Spark driver tries to list all the files in all the
directories, constructs an InMemoryFileIndex, and launches one task per file. This in turn results in the
Spark driver having to maintain a large amount of state in memory to track all the tasks. It caches the
complete list of a large number of files for the in-memory index, resulting in a driver OOM.
To check the memory profile of the AWS Glue job, profile the following code with grouping enabled:
You can monitor the memory profile and the ETL data movement in the AWS Glue job profile.
The driver executes below the threshold of 50 percent memory usage over the entire duration of the
AWS Glue job. The executors stream the data from Amazon S3, process it, and write it out to Amazon S3.
As a result, they consume less than 5 percent memory at any point in time.
The data movement profile below shows the total number of Amazon S3 bytes that are read (p. 248)
and written (p. 249) in the last minute by all executors as the job progresses. Both follow a similar
257
AWS Glue Developer Guide
Debugging OOM Exceptions and Job Abnormalities
pattern as the data is streamed across all the executors. The job finishes processing all one million files in
less than three hours.
258
AWS Glue Developer Guide
Debugging OOM Exceptions and Job Abnormalities
As the following graph shows, there is always a single executor (p. 244) running until the job fails. This
is because a new executor is launched to replace the killed executor. The JDBC data source reads are not
parallelized by default because it would require partitioning the table on a column and opening multiple
connections. As a result, only one executor reads in the complete table sequentially.
As the following graph shows, Spark tries to launch a new task four times before failing the job. You can
see the memory profile (p. 247) of three executors. Each executor quickly uses up all of its memory. The
fourth executor runs out of memory, and the job fails. As a result, its metric is not reported immediately.
259
AWS Glue Developer Guide
Debugging OOM Exceptions and Job Abnormalities
You can confirm from the error string on the AWS Glue console that the job failed due to OOM
exceptions, as shown in the following image.
Job output logs: To further confirm your finding of an executor OOM exception, look at the CloudWatch
Logs. When you search for Error, you find the four executors being killed in roughly the same time
windows as shown on the metrics dashboard. All are terminated by YARN as they exceed their memory
limits.
Executor 1
Executor 2
260
AWS Glue Developer Guide
Debugging OOM Exceptions and Job Abnormalities
18/06/13 16:55:35 WARN TaskSetManager: Lost task 0.1 in stage 0.0 (TID 1,
ip-10-1-2-16.ec2.internal, executor 2): ExecutorLostFailure (executor 2 exited
caused by one of the running tasks) Reason: Container killed by YARN for
exceeding memory limits. 5.8 GB of 5.5 GB physical memory used. Consider boosting
spark.yarn.executor.memoryOverhead.
Executor 3
Executor 4
Fix the Fetch Size Setting Using AWS Glue Dynamic Frames
The executor ran out of memory while reading the JDBC table because the default configuration for the
Spark JDBC fetch size is zero. This means that the JDBC driver on the Spark executor tries to fetch the 34
million rows from the database together and cache them, even though Spark streams through the rows
one at a time. With Spark, you can avoid this scenario by setting the fetch size parameter to a non-zero
default value.
You can also fix this issue by using AWS Glue dynamic frames instead. By default, dynamic frames use a
fetch size of 1,000 rows that is a typically sufficient value. As a result, the executor does not take more
than 7 percent of its total memory. The AWS Glue job finishes in less than two minutes with only a single
executor. While using AWS Glue dynamic frames is the recommended approach, it is also possible to
set the fetch size using the Apache Spark fetchsize property. See the Spark SQL, DataFrames and
Datasets Guide.
261
AWS Glue Developer Guide
Debugging Demanding Stages and Straggler Tasks
val df = source.getDynamicFrame
glueContext.write_dynamic_frame.from_options(frame = df, connection_type = "s3",
connection_options = {"path": output_path}, format = "parquet", transformation_ctx =
"datasink")
Normal profiled metrics: The executor memory (p. 246) with AWS Glue dynamic frames never exceeds
the safe threshold, as shown in the following image. It streams in the rows from the database and caches
only 1,000 rows in the JDBC driver at any point in time. An out of memory exception does not occur.
You can profile the following code—a common pattern in Apache Spark—to coalesce a large number of
small files into larger output files. For this example, the input dataset is 32 GB of JSON Gzip compressed
files. The output dataset has roughly 190 GB of uncompressed JSON files.
datasource0 = spark.read.format("json").load("s3://input_path")
df = datasource0.coalesce(1)
df.write.format("json").save(output_path)
262
AWS Glue Developer Guide
Debugging Demanding Stages and Straggler Tasks
• Job execution
• Memory profile
ETL data movement: In the ETL Data Movement profile, the bytes are read (p. 248) fairly quickly by
all the executors in the first stage that completes within the first six minutes. However, the total job
execution time is around one hour, mostly consisting of the data writes (p. 249).
Data shuffle across executors: The number of bytes read (p. 243) and written (p. 242) during
shuffling also shows a spike before Stage 2 ends, as indicated by the Job Execution and Data Shuffle
metrics. After the data shuffles from all executors, the reads and writes proceed from executor number 3
only.
Job execution: As shown in the graph below, all other executors are idle and are eventually relinquished
by the time 10:09. At that point, the total number of executors decreases to only one. This clearly shows
that executor number 3 consists of the straggler task that is taking the longest execution time and is
contributing to most of the job execution time.
263
AWS Glue Developer Guide
Debugging Demanding Stages and Straggler Tasks
Memory profile: After the first two stages, only executor number 3 (p. 247) is actively consuming
memory to process the data. The remaining executors are simply idle or have been relinquished shortly
after the completion of the first two stages.
To check the ETL data movements in the AWS Glue job, profile the following code with grouping
enabled:
264
AWS Glue Developer Guide
Debugging Demanding Stages and Straggler Tasks
ETL data movement: The data writes are now streamed in parallel with the data reads throughout the
job execution time. As a result, the job finishes within eight minutes—much faster than previously.
Data shuffle across executors: As the input files are coalesced during the reads using the grouping
feature, there is no costly data shuffle after the data reads.
Job execution: The job execution metrics show that the total number of active executors running and
processing data remains fairly constant. There is no single straggler in the job. All executors are active
and are not relinquished until the completion of the job. Because there is no intermediate shuffle of data
across the executors, there is only a single stage in the job.
265
AWS Glue Developer Guide
Monitoring the Progress of Multiple Jobs
Memory profile: The metrics show the active memory consumption (p. 247) across all executors—
reconfirming that there is activity across all executors. As data is streamed in and written out in parallel,
the total memory footprint of all executors is roughly uniform and well below the safe threshold for all
executors.
Topics
• Profiled Code (p. 267)
• Visualize the Profiled Metrics on the AWS Glue Console (p. 267)
• Fix the Processing of Files (p. 269)
266
AWS Glue Developer Guide
Monitoring the Progress of Multiple Jobs
Profiled Code
In this workflow, you have two jobs: an Input job and an Output job. The Input job is scheduled to run
every 30 minutes using a periodic trigger. The Output job is scheduled to run after each successful run of
the Input job. These scheduled jobs are controlled using job triggers.
Input job: This job reads in data from an Amazon Simple Storage Service (Amazon S3) location,
transforms it using ApplyMapping, and writes it to a staging Amazon S3 location. The following code is
profiled code for the Input job:
datasource0 = glueContext.create_dynamic_frame.from_options(connection_type="s3",
connection_options = {"paths": ["s3://input_path"],
"useS3ListImplementation":True,"recurse":True}, format="json")
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [map_spec])
datasink2 = glueContext.write_dynamic_frame.from_options(frame = applymapping1,
connection_type = "s3", connection_options = {"path": staging_path, "compression":
"gzip"}, format = "json")
Output job: This job reads the output of the Input job from the staging location in Amazon S3,
transforms it again, and writes it to a destination:
datasource0 = glueContext.create_dynamic_frame.from_options(connection_type="s3",
connection_options = {"paths": [staging_path],
"useS3ListImplementation":True,"recurse":True}, format="json")
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [map_spec])
datasink2 = glueContext.write_dynamic_frame.from_options(frame = applymapping1,
connection_type = "s3", connection_options = {"path": output_path}, format = "json")
267
AWS Glue Developer Guide
Monitoring the Progress of Multiple Jobs
In this example, job bookmarks are not enabled. No transformation contexts are used to enable job
bookmarks in the script code.
Job History: The Input and Output jobs have multiple runs, as shown on the History tab, starting from
12:00 PM.
The Input job on the AWS Glue console looks like this:
First job runs: As shown in the Data Bytes Read and Written graph below, the first job runs of the Input
and Output jobs between 12:00 and 12:30 show roughly the same area under the curves. Those areas
represent the Amazon S3 bytes written by the Input job and the Amazon S3 bytes read by the Output
job. This data is also confirmed by the ratio of Amazon S3 bytes written (summed over 30 minutes – the
job trigger frequency for the Input job). The data point for the ratio for the Input job run that started at
12:00PM is also 1.
The following graph shows the data flow ratio across all the job runs:
Second job runs: In the second job run, there is a clear difference in the number of bytes read by the
Output job compared to the number of bytes written by the Input job. (Compare the area under the
curve across the two job runs for the Output job, or compare the areas in the second run of the Input
and Output jobs.) The ratio of the bytes read and written shows that the Output Job read about 2.5x
the data written by the Input job in the second span of 30 minutes from 12:30 to 13:00. This is because
the Output Job reprocessed the output of the first job run of the Input job because job bookmarks were
not enabled. A ratio above 1 shows that there is an additional backlog of data that was processed by the
Output job.
268
AWS Glue Developer Guide
Monitoring the Progress of Multiple Jobs
Third job runs: The Input job is fairly consistent in terms of the number of bytes written (see the area
under the red curves). However, the third job run of the Input job ran longer than expected (see the
long tail of the red curve). As a result, the third job run of the Output job started late. The third job run
processed only a fraction of the data accumulated in the staging location in the remaining 30 minutes
between 13:00 and 13:30. The ratio of the bytes flow shows that it only processed 0.83 of data written
by the third job run of the Input job (see the ratio at 13:00).
Overlap of Input and Output jobs: The fourth job run of the Input job started at 13:30 as per the
schedule, before the third job run of the Output job finished. There is a partial overlap between these
two job runs. However, the third job run of the Output job captures only the files that it listed in the
staging location of Amazon S3 when it began around 13:17. This consists of all data output from the first
job runs of the Input job. The actual ratio at 13:30 is around 2.75. The third job run of the Output job
processed about 2.75x of data written by the fourth job run of the Input job from 13:30 to 14:00.
As these images show, the Output job is reprocessing data from the staging location from all prior job
runs of the Input job. As a result, the fourth job run for the Output job is the longest and overlaps with
the entire fifth job run of the Input job.
datasource0 = glueContext.create_dynamic_frame.from_options(connection_type="s3",
connection_options = {"paths": [staging_path],
"useS3ListImplementation":True,"recurse":True}, format="json", transformation_ctx =
"bookmark_ctx")
With job bookmarks enabled, the Output job doesn't reprocess the data in the staging location from all
the previous job runs of the Input job. In the following image showing the data read and written, the
area under the brown curve is fairly consistent and similar with the red curves.
The ratios of byte flow also remain roughly close to 1 because there is no additional data processed.
269
AWS Glue Developer Guide
Monitoring for DPU Capacity Planning
A job run for the Output job starts and captures the files in the staging location before the next Input job
run starts putting more data into the staging location. As long as it continues to do this, it processes only
the files captured from the previous Input job run, and the ratio stays close to 1.
Suppose that the Input job takes longer than expected, and as a result, the Output job captures files in
the staging location from two Input job runs. The ratio is then higher than 1 for that Output job run.
However, the following job runs of the Output job don't process any files that are already processed by
the previous job runs of the Output job.
Topics
• Profiled Code (p. 271)
270
AWS Glue Developer Guide
Monitoring for DPU Capacity Planning
• Visualize the Profiled Metrics on the AWS Glue Console (p. 271)
• Determine the Optimal DPU Capacity (p. 273)
Profiled Code
The following script reads an Amazon Simple Storage Service (Amazon S3) partition containing 428
gzipped JSON files. The script applies a mapping to change the field names, and converts and writes
them to Amazon S3 in Apache Parquet format. You provision 10 DPUs as per the default and execute this
job.
datasource0 = glueContext.create_dynamic_frame.from_options(connection_type="s3",
connection_options = {"paths": [input_path],
"useS3ListImplementation":True,"recurse":True}, format="json")
applymapping1 = ApplyMapping.apply(frame = datasource0, mappings = [(map_spec])
datasink2 = glueContext.write_dynamic_frame.from_options(frame = applymapping1,
connection_type = "s3", connection_options = {"path": output_path}, format = "parquet")
The number of maximum needed executors is computed by adding the total number of running tasks
and pending tasks, and dividing by the tasks per executor. This result is a measure of the total number of
executors required to satisfy the current load.
In contrast, the number of actively running executors measures how many executors are running active
Apache Spark tasks. As the job progresses, the maximum needed executors can change and typically
goes down towards the end of the job as the pending task queue diminishes.
The horizontal red line in the following graph shows the number of maximum allocated executors, which
depends on the number of DPUs that you allocate for the job. In this case, you allocate 10 DPUs for
the job run. One DPU is reserved for the master. Nine DPUs run two executors each and one executor
is reserved for the Spark driver. The Spark driver runs inside the application master. So, the number of
maximum allocated executors is 2*9 - 1 = 17 executors.
271
AWS Glue Developer Guide
Monitoring for DPU Capacity Planning
As the graph shows, the number of maximum needed executors starts at 107 at the beginning of the
job, whereas the number of active executors remains 17. This is the same as the number of maximum
allocated executors with 10 DPUs. The ratio between the maximum needed executors and maximum
allocated executors (adding 1 to both for the Spark driver) gives you the under-provisioning factor:
108/18 = 6x. You can provision 6 (under provisioning ratio) *9 (current DPU capacity - 1) + 1 DPUs = 55
DPUs to scale out the job to run it with maximum parallelism and finish faster.
The AWS Glue console displays the detailed job metrics as a static line representing the original number
of maximum allocated executors. The console computes the maximum allocated executors from the job
definition for the metrics. By constrast, for detailed job run metrics, the console computes the maximum
allocated executors from the job run configuration, specifically the DPUs allocated for the job run. To
view metrics for an individual job run, select the job run and choose View run metrics.
Looking at the Amazon S3 bytes read (p. 248) and written (p. 249), notice that the job spends all six
minutes streaming in data from Amazon S3 and writing it out in parallel. All the cores on the allocated
272
AWS Glue Developer Guide
Monitoring for DPU Capacity Planning
DPUs are reading and writing to Amazon S3. The maximum number of needed executors being 107 also
matches the number of files in the input Amazon S3 path—428. Each executor can launch four Spark
tasks to process four input files (JSON gzipped).
As the above image shows, the total number of active executors reaches the maximum allocated
—107 executors. Similarly, the maximum needed executors is never above the maximum allocated
executors. The maximum needed executors number is computed from the actively running and pending
task counts, so it might be smaller than the number of active executors. This is because there can be
executors that are partially or completely idle for a short period of time and are not yet decommissioned.
273
AWS Glue Developer Guide
Monitoring for DPU Capacity Planning
This job run uses 6x more executors to read and write from Amazon S3 in parallel. As a result, this job
run uses more Amazon S3 bandwidth for both reads and writes, and finishes faster.
274
AWS Glue Developer Guide
Logging Using CloudTrail
jr_c894524c8ef5048a4d9... 10 6 min.
jr_1a466cf2575e7ffe6856... 55 3 min.
To learn more about CloudTrail, see the AWS CloudTrail User Guide.
For an ongoing record of events in your AWS account, including events for AWS Glue, create a trail. A trail
enables CloudTrail to deliver log files to an Amazon S3 bucket. By default, when you create a trail in the
console, the trail applies to all AWS Regions. The trail logs events from all Regions in the AWS partition
and delivers the log files to the Amazon S3 bucket that you specify. Additionally, you can configure
other AWS services to further analyze and act upon the event data collected in CloudTrail logs. For more
information, see the following:
All AWS Glue actions are logged by CloudTrail and are documented in the AWS Glue API (p. 446) . For
example, calls to the CreateDatabase, CreateTable and CreateScript actions generate entries in
the CloudTrail log files.
Every event or log entry contains information about who generated the request. The identity
information helps you determine the following:
275
AWS Glue Developer Guide
Understanding AWS Glue Log File Entries
• Whether the request was made with root or AWS Identity and Access Management (IAM) user
credentials.
• Whether the request was made with temporary security credentials for a role or federated user.
• Whether the request was made by another AWS service.
However, CloudTrail doesn't log all information regarding calls. For example, it doesn't log certain
sensitive information, such as the ConnectionProperties used in connection requests, and it logs a
null instead of the responses returned by the following APIs:
The following example shows a CloudTrail log entry that demonstrates the DeleteCrawler action.
{
"eventVersion": "1.05",
"userIdentity": {
"type": "IAMUser",
"principalId": "AKIAIOSFODNN7EXAMPLE",
"arn": "arn:aws:iam::123456789012:user/johndoe",
"accountId": "123456789012",
"accessKeyId": "AKIAIOSFODNN7EXAMPLE",
"userName": "johndoe"
},
"eventTime": "2017-10-11T22:29:49Z",
"eventSource": "glue.amazonaws.com",
"eventName": "DeleteCrawler",
"awsRegion": "us-east-1",
"sourceIPAddress": "72.21.198.64",
"userAgent": "aws-cli/1.11.148 Python/3.6.1 Darwin/16.7.0 botocore/1.7.6",
"requestParameters": {
"name": "tes-alpha"
},
"responseElements": null,
"requestID": "b16f4050-aed3-11e7-b0b3-75564a46954f",
"eventID": "e73dd117-cfd1-47d1-9e2f-d1271cad838c",
"eventType": "AwsApiCall",
"recipientAccountId": "123456789012"
}
This example shows a CloudTrail log entry that demonstrates a CreateConnection action.
276
AWS Glue Developer Guide
Understanding AWS Glue Log File Entries
"eventVersion": "1.05",
"userIdentity": {
"type": "IAMUser",
"principalId": "AKIAIOSFODNN7EXAMPLE",
"arn": "arn:aws:iam::123456789012:user/johndoe",
"accountId": "123456789012",
"accessKeyId": "AKIAIOSFODNN7EXAMPLE",
"userName": "johndoe"
},
"eventTime": "2017-10-13T00:19:19Z",
"eventSource": "glue.amazonaws.com",
"eventName": "CreateConnection",
"awsRegion": "us-east-1",
"sourceIPAddress": "72.21.198.66",
"userAgent": "aws-cli/1.11.148 Python/3.6.1 Darwin/16.7.0 botocore/1.7.6",
"requestParameters": {
"connectionInput": {
"name": "test-connection-alpha",
"connectionType": "JDBC",
"physicalConnectionRequirements": {
"subnetId": "subnet-323232",
"availabilityZone": "us-east-1a",
"securityGroupIdList": [
"sg-12121212"
]
}
}
},
"responseElements": null,
"requestID": "27136ebc-afac-11e7-a7d6-ab217e5c3f19",
"eventID": "e8b3baeb-c511-4597-880f-c16210c60a4a",
"eventType": "AwsApiCall",
"recipientAccountId": "123456789012"
}
277
AWS Glue Developer Guide
Overview of Workflows
You can create workflows using the AWS Management Console or the AWS Glue API. The console enables
you to visualize the components and flow of a workflow with a graph.
Topics
• Overview of Workflows (p. 278)
• Creating and Running Workflows (p. 279)
• Getting and Setting Workflow Run Properties (p. 282)
• Querying Workflows Using the AWS Glue API (p. 283)
Overview of Workflows
In AWS Glue, you can use workflows to create and visualize complex extract, transform, and load (ETL)
activities involving multiple crawlers, jobs, and triggers. Each workflow manages the execution and
monitoring of all its components. As a workflow runs each component, it records execution progress
and status, providing you with an overview of the larger task and the details of each step. The AWS Glue
console provides a visual representation of a workflow as a graph.
To share and manage state throughout a workflow run, you can define default workflow run properties.
These properties, which are name/value pairs, are available to all the jobs in the workflow. Using the
AWS Glue API, jobs can retrieve the workflow run properties and modify them for jobs that come later in
the workflow.
The following image shows the graph of a basic workflow on the AWS Glue console. Your workflow could
have dozens of components.
278
AWS Glue Developer Guide
Static and Dynamic Workflow Views
This workflow is started by a schedule trigger, which starts two jobs. Upon successful completion of both
jobs, an event trigger starts a crawler.
When a workflow is running, the console displays the dynamic view, graphically indicating the jobs
that have completed and that are yet to be run. You can also retrieve a dynamic view of a running
workflow using the AWS Glue API. For more information, see Querying Workflows Using the AWS Glue
API (p. 283).
Workflow Restrictions
Keep the following workflow restrictions in mind:
Topics
• Creating and Building Out a Workflow Using the Console (p. 280)
• Running a Workflow (p. 282)
279
AWS Glue Developer Guide
Creating and Building Out a Workflow Using the Console
You build out your workflow by adding triggers to the workflow graph, and defining the watched
events and actions for each trigger. You begin with a start trigger, which can be either an on-demand or
schedule trigger, and complete the graph by adding event (conditional) triggers.
Any optional default run properties that you add are made available as arguments to all jobs in the
workflow. For more information, see Getting and Setting Workflow Run Properties (p. 282).
4. Choose Add workflow.
• Choose Add new, and complete the Add trigger form, selecting Schedule or On demand for
Trigger Type. Then choose Add.
The trigger appears on the graph, along with a placeholder node (labeled Add node). At this point,
the trigger is not yet saved.
280
AWS Glue Developer Guide
Creating and Building Out a Workflow Using the Console
• Choose Clone existing, and choose a trigger to clone. Then choose Add.
The trigger appears on the graph, along with the jobs and crawlers that it watches and the jobs
and crawlers that it starts.
If you mistakenly selected the wrong trigger, select the trigger on the graph, and then choose
Remove.
3. If you added a new trigger, complete these steps:
The trigger is saved, and the selected jobs or crawlers appear on the graph with connectors from
the trigger.
If you mistakenly added the wrong jobs or crawlers, you can select either the trigger or a
connector and choose Remove.
• To clone an existing trigger, ensure that no node on the graph is selected, and on the Action
menu, choose Add trigger.
• To add a new trigger that watches a particular job or crawler on the graph, select the job or
crawler node, and then choose the Add trigger placeholder node.
You can add more jobs or crawlers to watch for this trigger in a later step.
2. In the Add trigger dialog box, do one of the following:
• Choose Add new, and complete the Add trigger form. Then choose Add.
The trigger appears on the graph. You will complete the trigger in a later step.
• Choose Clone existing, and choose a trigger to clone. Then choose Add.
The trigger appears on the graph, along with the jobs and crawlers that it watches and the jobs
and crawlers that it starts.
If you mistakenly chose the wrong trigger, select the trigger on the graph, and then choose
Remove.
3. If you added a new trigger, complete these steps:
As the following graph shows, placeholder nodes appear for (1) events to watch and (2) actions.
281
AWS Glue Developer Guide
Running a Workflow
b. (Optional if the trigger already watches an event and you want to add more jobs or crawlers to
watch.) Choose the events-to-watch placeholder node, and in the Add job(s) and crawler(s) to
watch dialog box, select one or more jobs or crawlers. Choose an event to watch (SUCCEEDED,
FAILED, etc.), and choose Add.
c. Ensure that the trigger is selected, and choose the actions placeholder node.
d. In the Add job(s) and crawler(s) to watch dialog box, select one or more jobs or crawlers, and
choose Add.
The selected jobs and crawlers appear on the graph, with connectors from the trigger.
Running a Workflow
If the start trigger for a workflow is an on-demand trigger, you can start the workflow from the AWS
Glue console.
To run a workflow
The following sample Python code from an extract, transform, and load (ETL) job demonstrates how to
get the workflow run properties.
import sys
282
AWS Glue Developer Guide
Querying Workflows Using the AWS Glue API
import boto3
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from awsglue.context import GlueContext
from pyspark.context import SparkContext
glue_client = boto3.client("glue")
args = getResolvedOptions(sys.argv, ['JOB_NAME','WORKFLOW_NAME', 'WORKFLOW_RUN_ID'])
workflow_name = args['WORKFLOW_NAME']
workflow_run_id = args['WORKFLOW_RUN_ID']
workflow_params = glue_client.get_workflow_run_properties(Name=workflow_name,
RunId=workflow_run_id)["RunProperties"]
target_database = workflow_params['target_database']
target_s3_location = workflow_params['target_s3_location']
The following code continues by setting the target_format run property to 'csv'.
workflow_params['target_format'] = 'csv'
glue_client.put_workflow_run_properties(Name=workflow_name, RunId=workflow_run_id,
RunProperties=workflow_params)
Topics
• Querying Static Views (p. 283)
• Querying Dynamic Views (p. 284)
The static view returned by this API is the most up-to-date view according to the latest definition of
triggers associated with the workflow.
Graph Definition
A workflow graph G is an ordered pair (N, E), where N is a set of nodes and E a set of edges. Node is a
vertex in the graph identified by a unique number. A node can be of type trigger, job, or crawler; for
example: {name:T1, type:Trigger, uniqueId:1}, {name:J1, type:Job, uniqueId:2}
283
AWS Glue Developer Guide
Querying Dynamic Views
Edge is a 2-tuple of the form (src, dest), where src and dest are nodes and there is a directed edge
from src to dest.
J1 ---> T ---> J2
Nodes: J1, T, J2
For instance, nodes representing jobs in the GetWorkflowRun call have a list of job runs initiated as part
of the latest run of the workflow. You can use this list to display the run status of each job in the graph
itself. For downstream dependencies that are not yet executed, this field is set to null. The graphed
information makes you aware of the current state of any workflow at any point of time.
The dynamic view returned by this API is as per the static view that was present when the workflow run
was started.
{
Nodes : [
{
"type" : Trigger,
"name" : "t1",
"uniqueId" : 1
},
{
"type" : Job,
"name" : "j1",
"uniqueId" : 2
},
{
"type" : Trigger,
"name" : "t2",
"uniqueId" : 3
},
{
"type" : Job,
284
AWS Glue Developer Guide
Querying Dynamic Views
"name" : "j2",
"uniqueId" : 4
}
],
Edges : [
{
"sourceId" : 1,
"destinationId" : 2
},
{
"sourceId" : 2,
"destinationId" : 3
},
{
"sourceId" : 3,
"destinationId" : 4
}
}
{
Nodes : [
{
"type" : Trigger,
"name" : "t1",
"uniqueId" : 1,
"jobDetails" : null,
"crawlerDetails" : null
},
{
"type" : Job,
"name" : "j1",
"uniqueId" : 2,
"jobDetails" : [
{
"id" : "jr_12334",
"jobRunState" : "SUCCEEDED",
"errorMessage" : "error string"
}
],
"crawlerDetails" : null
},
{
"type" : Trigger,
"name" : "t2",
"uniqueId" : 3,
"jobDetails" : null,
"crawlerDetails" : null
},
{
"type" : Job,
"name" : "j2",
"uniqueId" : 4,
"jobDetails" : [
{
"id" : "jr_1233sdf4",
"jobRunState" : "SUCCEEDED",
"errorMessage" : "error string"
}
],
"crawlerDetails" : null
}
],
Edges : [
285
AWS Glue Developer Guide
Querying Dynamic Views
{
"sourceId" : 1,
"destinationId" : 2
},
{
"sourceId" : 2,
"destinationId" : 3
},
{
"sourceId" : 3,
"destinationId" : 4
}
}
Consider Flow:
T(t1) ---> J(j1) ---> T(t2) ---> J(j2)
| |
| |
>+------> T(t3) <-----+
|
|
J(j3)
Graph generated:
Nodes: t1, t2, t3, j1, j2, j3
Edges: (t1, j1), (j1, t2), (t2, j2), (j1, t3), (j2, t3), (t3, j3)
286
AWS Glue Developer Guide
Gathering AWS Glue Troubleshooting Information
Along with your account ID, gather the following information for each of these types of failures:
Logs from crawler runs are located in CloudWatch Logs under /aws-glue/crawlers.
When a test connection fails, gather the following information:
• Connection name
• Connection ID
• JDBC connection string in the form jdbc:protocol://host:port/database-name.
Logs from test connections are located in CloudWatch Logs under /aws-glue/
testconnection.
When a job fails, gather the following information:
• Job name
• Job run ID in the form jr_xxxxx.
Logs from job runs are located in CloudWatch Logs under /aws-glue/jobs.
In addition, Apache Spark requires bi-directional connectivity among driver and executor nodes. One of
the security groups needs to allow ingress rules on all TCP ports. You can prevent it from being open to
the world by restricting the source of the security group to itself with a self-referencing security group.
Here are some typical actions you can take to troubleshoot connection problems:
287
AWS Glue Developer Guide
Troubleshooting Errors
Topics
• Error: Resource Unavailable (p. 288)
• Error: Could Not Find S3 Endpoint or NAT Gateway for subnetId in VPC (p. 289)
• Error: Inbound Rule in Security Group Required (p. 289)
• Error: Outbound Rule in Security Group Required (p. 289)
• Error: Job Run Failed Because the Role Passed Should Be Given Assume Role Permissions for the AWS
Glue Service (p. 289)
• Error: DescribeVpcEndpoints Action Is Unauthorized. Unable to Validate VPC ID vpc-id (p. 289)
• Error: DescribeRouteTables Action Is Unauthorized. Unable to Validate Subnet Id: subnet-id in VPC id:
vpc-id (p. 290)
• Error: Failed to Call ec2:DescribeSubnets (p. 290)
• Error: Failed to Call ec2:DescribeSecurityGroups (p. 290)
• Error: Could Not Find Subnet for AZ (p. 290)
• Error: Job Run Exception When Writing to a JDBC Target (p. 290)
• Error: Amazon S3 Timeout (p. 291)
• Error: Amazon S3 Access Denied (p. 291)
• Error: Amazon S3 Access Key ID Does Not Exist (p. 291)
• Error: Job Run Fails When Accessing Amazon S3 with an s3a:// URI (p. 291)
• Error: Amazon S3 Service Token Expired (p. 292)
• Error: No Private DNS for Network Interface Found (p. 293)
• Error: Development Endpoint Provisioning Failed (p. 293)
• Error: Notebook Server CREATE_FAILED (p. 293)
• Error: Local Notebook Fails to Start (p. 293)
• Error: Notebook Usage Errors (p. 293)
• Error: Running Crawler Failed (p. 294)
• Error: Upgrading Athena Data Catalog (p. 294)
• Error: A Job is Reprocessing Data When Job Bookmarks Are Enabled (p. 294)
288
AWS Glue Developer Guide
Error: Could Not Find S3 Endpoint
or NAT Gateway for subnetId in VPC
• For any connections and development endpoints that you use, check that your cluster has not run out
of elastic network interfaces.
• Check that you have an Amazon S3 VPC endpoint set up, which is required with AWS Glue. In addition,
check your NAT gateway if that's part of your configuration. For more information, see Amazon VPC
Endpoints for Amazon S3 (p. 30).
• For any connections that you use, check your security group for an inbound rule that is self-
referencing. For more information, see Setting Up Your Environment to Access Data Stores (p. 29).
• When you are using a development endpoint, check your security group for an inbound rule that is
self-referencing. For more information, see Setting Up Your Environment to Access Data Stores (p. 29).
• For any connections that you use, check your security group for an outbound rule that is self-
referencing. For more information, see Setting Up Your Environment to Access Data Stores (p. 29).
• When you are using a development endpoint, check your security group for an outbound rule that is
self-referencing. For more information, see Setting Up Your Environment to Access Data Stores (p. 29).
• When a user creates an AWS Glue job, confirm that the user's role contains a policy that contains
iam:PassRole for AWS Glue. For more information, see Step 3: Attach a Policy to IAM Users That
Access AWS Glue (p. 15).
289
AWS Glue Developer Guide
Error: DescribeRouteTables Action Is Unauthorized.
Unable to Validate Subnet Id: subnet-id in VPC id: vpc-id
• If your job writes to a Microsoft SQL Server table, and the table has columns defined as type Boolean,
then the table must be predefined in the SQL Server database. When you define the job on the AWS
Glue console using a SQL Server target with the option Create tables in your data target, don't map
any source columns to a target column with data type Boolean. You might encounter an error when
the job runs.
290
AWS Glue Developer Guide
Error: Amazon S3 Timeout
• An Amazon S3 VPC endpoint can only route traffic to buckets within an AWS Region. If you need
to connect to buckets in other Regions, a possible workaround is to use a NAT gateway. For more
information, see NAT Gateways.
• An ETL job must have access to an Amazon S3 data store used as a source or target. A crawler must
have access to an Amazon S3 data store that it crawls. For more information, see Step 2: Create an IAM
Role for AWS Glue (p. 14).
• An ETL job uses an IAM role to access data stores, confirm that the IAM role for your job was not
deleted before the job started.
• An IAM role contains permissions to access your data stores, confirm that any attached Amazon S3
policy containing s3:ListBucket is correct.
291
AWS Glue Developer Guide
Error: Amazon S3 Service Token Expired
10. at com.amazonaws.http.AmazonHttpClient
$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1272)
11. at com.amazonaws.http.AmazonHttpClient
$RequestExecutor.executeHelper(AmazonHttpClient.java:1056)
12. at com.amazonaws.http.AmazonHttpClient
$RequestExecutor.doExecute(AmazonHttpClient.java:743)
13. at com.amazonaws.http.AmazonHttpClient
$RequestExecutor.executeWithTimer(AmazonHttpClient.java:717)
14. at com.amazonaws.http.AmazonHttpClient
$RequestExecutor.execute(AmazonHttpClient.java:699)
15. at com.amazonaws.http.AmazonHttpClient$RequestExecutor.access
$500(AmazonHttpClient.java:667)
16. at com.amazonaws.http.AmazonHttpClient
$RequestExecutionBuilderImpl.execute(AmazonHttpClient.java:649)
17. at com.amazonaws.http.AmazonHttpClient.execute(AmazonHttpClient.java:513)
18. at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4325)
19. at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4272)
20. at com.amazonaws.services.s3.AmazonS3Client.invoke(AmazonS3Client.java:4266)
21. at com.amazonaws.services.s3.AmazonS3Client.listObjects(AmazonS3Client.java:834)
22. at org.apache.hadoop.fs.s3a.S3AFileSystem.getFileStatus(S3AFileSystem.java:971)
23. at
org.apache.hadoop.fs.s3a.S3AFileSystem.deleteUnnecessaryFakeDirectories(S3AFileSystem.java:1155)
24. at org.apache.hadoop.fs.s3a.S3AFileSystem.finishedWrite(S3AFileSystem.java:1144)
25. at org.apache.hadoop.fs.s3a.S3AOutputStream.close(S3AOutputStream.java:142)
26. at org.apache.hadoop.fs.FSDataOutputStream
$PositionCache.close(FSDataOutputStream.java:74)
27. at org.apache.hadoop.fs.FSDataOutputStream.close(FSDataOutputStream.java:108)
28. at org.apache.parquet.hadoop.ParquetFileWriter.end(ParquetFileWriter.java:467)
29. at
org.apache.parquet.hadoop.InternalParquetRecordWriter.close(InternalParquetRecordWriter.java:117)
30. at org.apache.parquet.hadoop.ParquetRecordWriter.close(ParquetRecordWriter.java:112)
31. at
org.apache.spark.sql.execution.datasources.parquet.ParquetOutputWriter.close(ParquetOutputWriter.scala
32. at org.apache.spark.sql.execution.datasources.FileFormatWriter
$SingleDirectoryWriteTask.releaseResources(FileFormatWriter.scala:252)
33. at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun
$org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask
$3.apply(FileFormatWriter.scala:191)
34. at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun
$org$apache$spark$sql$execution$datasources$FileFormatWriter$$executeTask
$3.apply(FileFormatWriter.scala:188)
35. at org.apache.spark.util.Utils$.tryWithSafeFinallyAndFailureCallbacks(Utils.scala:1341)
36. at org.apache.spark.sql.execution.datasources.FileFormatWriter$.org$apache$spark$sql
$execution$datasources$FileFormatWriter$$executeTask(FileFormatWriter.scala:193)
37. at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1$
$anonfun$3.apply(FileFormatWriter.scala:129)
38. at org.apache.spark.sql.execution.datasources.FileFormatWriter$$anonfun$write$1$
$anonfun$3.apply(FileFormatWriter.scala:128)
39. at org.apache.spark.scheduler.ResultTask.runTask(ResultTask.scala:87)
40. at org.apache.spark.scheduler.Task.run(Task.scala:99)
41. at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:282)
42. at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
43. at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
44. at java.lang.Thread.run(Thread.java:748)
292
AWS Glue Developer Guide
Error: No Private DNS for Network Interface Found
• If you are using the Amazon provided DNS, the value of enableDnsHostnames must be set to true.
For more information, see DNS.
• When you define a development endpoint, the VPC, subnet, and security groups are validated to
confirm that they meet certain requirements.
• If you provided the optional SSH public key, check that it is a valid SSH public key.
• Check in the VPC console that your VPC uses a valid DHCP option set. For more information, see DHCP
option sets.
• If the cluster remains in the PROVISIONING state, contact AWS Support.
• AWS Glue passes an IAM role to Amazon EC2 when it is setting up the notebook server. The IAM role
must have a trust relationship to Amazon EC2.
• The IAM role must have an instance profile of the same name. When you create the role for Amazon
EC2 with the IAM console, the instance profile with the same name is automatically created. Check for
an error in the log regarding an invalid instance profile name iamInstanceProfile.name. For more
information, see Using Instance Profiles.
• Check that your role has permission to access aws-glue* buckets in the policy that you pass to create
the notebook server.
• If you are running on Microsoft Windows, make sure that the JAVA_HOME environment variable points
to the correct Java directory. It's possible to update Java without updating this variable, and if it points
to a folder that no longer exists, Zeppelin notebooks fail to start.
• You provide an IAM role with an attached policy when you created the notebook server. If the
policy does not include all the required permissions, you might get an error such as assumed-
293
AWS Glue Developer Guide
Error: Running Crawler Failed
• Check the logs for the crawler run in CloudWatch Logs under /aws-glue/crawlers.
Max Concurrency
Ensure that the maximum number of concurrent runs for the job is 1. For more information, see the
discussion of max concurrency in Adding Jobs in AWS Glue (p. 161). When you have multiple concurrent
jobs with job bookmarks and the maximum concurrency is set to 1, the job bookmark doesn't work
correctly.
Ensure that your job run script ends with the following commit:
job.commit()
When you include this object, AWS Glue records the timestamp and path of the job run. If you run the
job again with the same path, AWS Glue processes only the new files. If you don't include this object and
job bookmarks are enabled, the job reprocesses the already processed files along with the new files and
creates redundancy in the job's target data store.
Transformation context is an optional parameter in the GlueContext class, but job bookmarks don't
work if you don't include it. To resolve this error, add the transformation context parameter when you
create the DynamicFrame, as shown following:
sample_dynF=create_dynamic_frame_from_catalog(database,
table_name,transformation_ctx="sample_dynF")
294
AWS Glue Developer Guide
AWS Glue Limits
Input Source
If you are using a relational database (a JDBC connection) for the input source, job bookmarks work only
if the table's primary keys are in sequential order. Job bookmarks work for new rows, but not for updated
rows. That is because job bookmarks look for the primary keys, which already exist. This does not apply if
your input source is Amazon Simple Storage Service (Amazon S3).
For Amazon S3 input sources, job bookmarks check the last modified time of the objects, rather than the
file names, to verify which objects need to be reprocessed. If your input source data has been modified
since your last job run, the files are reprocessed when you run the job again.
295
AWS Glue Developer Guide
General Information
Topics
• Special Parameters Used by AWS Glue (p. 296)
• Connection Types and Options for ETL in AWS Glue (p. 298)
• Format Options for ETL Inputs and Outputs in AWS Glue (p. 300)
• Managing Partitions for ETL Output in AWS Glue (p. 303)
• Reading Input Files in Larger Groups (p. 304)
• Reading from JDBC Tables in Parallel (p. 305)
• Moving Data to and from Amazon Redshift (p. 306)
• AWS Glue Data Catalog Support for Spark SQL Jobs (p. 307)
• Excluding Amazon S3 Storage Classes (p. 309)
• Developing and Testing ETL Scripts Locally Using the AWS Glue ETL Library (p. 311)
• --job-language — The script programming language. This must be either scala or python. If this
parameter is not present, the default is python.
• --class — The Scala class that serves as the entry point for your Scala script. This only applies if
your --job-language is set to scala.
• --scriptLocation — The S3 location where your ETL script is located (in a form like s3://path/
to/my/script.py). This overrides a script location set in the JobCommand object.
• --extra-py-files — S3 path(s) to additional Python modules that AWS Glue will add to the
Python path before executing your script. Multiple values must be complete paths separated by a
comma (,). Only individual files are supported, not a directory path. Note that only pure Python
modules will work currently. Extension modules written in C or other languages are not supported.
• --extra-jars — S3 path(s) to additional Java .jar file(s) that AWS Glue will add to the Java
classpath before executing your script. Multiple values must be complete paths separated by a comma
(,).
• --extra-files — S3 path(s) to additional files such as configuration files that AWS Glue will copy
to the working directory of your script before executing it. Multiple values must be complete paths
separated by a comma (,). Only individual files are supported, not a directory path.
• --job-bookmark-option — Controls the behavior of a job bookmark. The following option values
can be set:
296
AWS Glue Developer Guide
Special Parameters
‑‑job‑bookmark‑option Value
Description
Keep track of previously processed data. When a job runs, process new data since the last
job-
checkpoint.
bookmark-
enable
Always process the entire dataset. You are responsible for managing the output from previous job
job-
runs.
bookmark-
disable
Process incremental data since the last successful run or the data in the range identified by the
job-
following sub-options, without updating the state of last bookmark. You are responsible for
bookmark-
managing the output from previous job runs. The two sub-options are:
pause
• job-bookmark-from <from-value> is the run ID which represents all the input that was processed
until the last successful run before and including the specified run ID. The corresponding input is
ignored.
• job-bookmark-to <to-value> is the run ID which represents all the input that was processed
until the last successful run before and including the specified run ID. The corresponding input
excluding the input identified by the <from-value> is processed by the job. Any input later than
this input is also excluded for processing.
The job bookmark state is not updated when this option set is specified.
The sub-options are optional, however when used both the sub-options needs to be provided.
'--job-bookmark-option': 'job-bookmark-enable'
• --TempDir — Specifies an S3 path to a bucket that can be used as a temporary directory for the Job.
'--TempDir': 's3-path-to-directory'
• --enable-metrics — Enables the collection of metrics for job profiling for this job run. These
metrics are available on the AWS Glue console and CloudWatch console. To enable metrics, only
specify the key, no value is needed.
• --enable-glue-datacatalog — Enables you to use the AWS Glue Data Catalog as a Spark Hive
metastore.
• --enable-continuous-cloudwatch-log — Enables real-time, continuous logging for AWS Glue
jobs. You can view real-time Apache Spark job logs in Amazon CloudWatch.
• --enable-continuous-log-filter — Specifies a standard filter (true) or no filter (false) when
you create or edit a job enabled for continuous logging. Choosing the standard filter prunes out non-
useful Apache Spark driver/executor and Apache Hadoop YARN heartbeat log messages. Choosing no
filter gives you all the log messages.
• --continuous-log-logGroup — Specifies a custom AWS CloudWatch log group name for a job
enabled for continuous logging.
• --continuous-log-logStreamPrefix — Specifies a custom AWS CloudWatch log stream prefix
for a job enabled for continuous logging.
• --continuous-log-conversionPattern — Specifies a custom conversion log pattern for a job
enabled for continuous logging. The conversion pattern only applies to driver logs and executor logs. It
does not affect the Glue progress bar.
297
AWS Glue Developer Guide
Connection Parameters
For example, the following is the syntax for running a job with a --argument and a special parameter:
There are also several argument names used by AWS Glue internally that you should never set:
The connectionType parameter can take the following values, and the associated "connectionOptions"
parameter values for each type are documented below:
In general, these are for ETL input and do not apply to ETL sinks.
• "connectionType": "s3" (p. 298): Designates a connection to Amazon Simple Storage Service (Amazon
S3).
• "connectionType": "parquet" (p. 299): Designates a connection to files stored in Amazon S3 in the
Apache Parquet file format.
• "connectionType": "orc" (p. 299): Designates a connection to files stored in Amazon S3 in the Apache
Hive Optimized Row Columnar (ORC) file format.
• "connectionType": "mysql" (p. 299): Designates a connection to a MySQL database (see JDBC
connectionType values (p. 299)).
• "connectionType": "redshift" (p. 299): Designates a connection to an Amazon Redshift database (see
JDBC connectionType values (p. 299)).
• "connectionType": "oracle" (p. 299): Designates a connection to an Oracle database (see JDBC
connectionType values (p. 299)).
• "connectionType": "sqlserver" (p. 299): Designates a connection to a Microsoft SQL Server database
(see JDBC connectionType values (p. 299)).
• "connectionType": "postgresql" (p. 299): Designates a connection to a PostgreSQL database (see JDBC
connectionType values (p. 299)).
• "connectionType": "dynamodb" (p. 300): Designates a connection to Amazon DynamoDB;
(DynamoDB).
"connectionType": "s3"
Designates a connection to Amazon Simple Storage Service (Amazon S3).
298
AWS Glue Developer Guide
Connection Parameters
"connectionType": "parquet"
Designates a connection to files stored in Amazon Simple Storage Service (Amazon S3) in the Apache
Parquet file format.
"connectionType": "orc"
Designates a connection to files stored in Amazon S3 in the Apache Hive Optimized Row Columnar (ORC)
file format.
299
AWS Glue Developer Guide
Format Options
All other option name/value pairs that are included in connectionOptions for a JDBC connection,
including formatting options, are passed directly to the underlying SparkSQL DataSource. For more
information, see Redshift data source for Spark.
"connectionType": "dynamodb"
Designates a connection to Amazon DynamoDB (DynamoDB).
format="avro"
This value designates the Apache Avro data format.
format="csv"
This value designates comma-separated-values as the data format (for example, see RFC 4180 and
RFC 7111).
• separator: Specifies the delimiter character. The default is a comma: ',', but any other character
can be specified.
• escaper: Specifies a character to use for escaping. The default value is "none". If enabled, the
character which immediately follows is used as-is, except for a small set of well-known escapes (\n,
\r, \t, and \0).
300
AWS Glue Developer Guide
Format Options
• quoteChar: Specifies the character to use for quoting. The default is a double quote: '"'. Set this to
'-1' to disable quoting entirely.
• multiline: A Boolean value that specifies whether a single record can span multiple lines. This can
occur when a field contains a quoted new-line character. You must set this option to "true" if any
record spans multiple lines. The default value is "false", which allows for more aggressive file-
splitting during parsing.
• withHeader: A Boolean value that specifies whether to treat the first line as a header. The default
value is "false". This option can be used in the DynamicFrameReader class.
• writeHeader: A Boolean value that specifies whether to write the header to output. The default
value is "true". This option can be used in the DynamicFrameWriter class.
• skipFirst: A Boolean value that specifies whether to skip the first data line. The default value is
"false".
format="ion"
This value designates Amazon Ion as the data format. (For more information, see the Amazon Ion
Specification.)
format="grokLog"
This value designates a log data format specified by one or more Logstash grok patterns (for example,
see Logstash Reference (6.2]: Grok filter plugin).
• logFormat: Specifies the grok pattern that matches the log's format.
• customPatterns: Specifies additional grok patterns used here.
• MISSING: Specifies the signal to use in identifying missing values. The default is '-'.
• LineCount: Specifies the number of lines in each log record. The default is '1', and currently only
single-line records are supported.
• StrictMode: A Boolean value that specifies whether strict mode is enabled. In strict mode, the reader
doesn't do automatic type conversion or recovery. The default value is "false".
format="json"
This value designates a JSON (JavaScript Object Notation) data format.
Currently, AWS Glue does not support format_options for json output.
• jsonPath: A JsonPath expression that identifies an object to be read into records. This is particularly
useful when a file contains records nested inside an outer array. For example, the following JsonPath
expression targets the id field of a JSON object:
301
AWS Glue Developer Guide
Format Options
• multiline: A Boolean value that specifies whether a single record can span multiple lines. This can
occur when a field contains a quoted new-line character. You must set this option to "true" if any
record spans multiple lines. The default value is "false", which allows for more aggressive file-
splitting during parsing.
format="orc"
This value designates Apache ORC as the data format. (For more information, see the LanguageManual
ORC.)
There are no format_options values for format="orc". However, any options that are accepted by
the underlying SparkSQL code can be passed to it by way of the connection_options map parameter.
format="parquet"
This value designates Apache Parquet as the data format.
There are no format_options values for format="parquet". However, any options that are accepted
by the underlying SparkSQL code can be passed to it by way of the connection_options map
parameter.
format="glueparquet"
This value designates a custom Parquet writer type that is optimized for Dynamic Frames as the
data format. A precomputed schema is not required before writing. As data comes in, glueparquet
computes and modifies the schema dynamically.
• compression: Specifies the compression codec used when writing Parquet files. The default value is
"snappy".
• blockSize: Specifies the size of a row group being buffered in memory. The default value is
"128MB".
• pageSize: Specifies the size of the smallest unit that must be read fully to access a single record. The
default value is "1MB".
Limitations:
• glueparquet supports only a schema shrinkage or expansion, but not a type change.
• glueparquet is not able to store a schema-only file.
format="xml"
This value designates XML as the data format, parsed through a fork of the XML Data Source for Apache
Spark parser.
• rowTag: Specifies the XML tag in the file to treat as a row. Row tags cannot be self-closing.
• encoding: Specifies the character encoding. The default value is "UTF-8".
• excludeAttribute: A Boolean value that specifies whether you want to exclude attributes in
elements or not. The default value is "false".
302
AWS Glue Developer Guide
Managing Partitions
• treatEmptyValuesAsNulls: A Boolean value that specifies whether to treat white space as a null
value. The default value is "false".
• attributePrefix: A prefix for attributes to differentiate them from elements. This prefix is used for
field names. The default value is "_".
• valueTag: The tag used for a value when there are attributes in the element that have no child. The
default is "_VALUE".
• ignoreSurroundingSpaces: A Boolean value that specifies whether the white space that surrounds
values should be ignored. The default value is "false".
For example, you might decide to partition your application logs in Amazon Simple Storage Service
(Amazon S3) by date, broken down by year, month, and day. Files that correspond to a single day's
worth of data are then placed under a prefix such as s3://my_bucket/logs/year=2018/month=01/
day=23/. Systems like Amazon Athena, Amazon Redshift Spectrum, and now AWS Glue can use these
partitions to filter data by partition value without having to read all the underlying data from Amazon
S3.
Crawlers not only infer file types and schemas, they also automatically identify the partition structure
of your dataset when they populate the AWS Glue Data Catalog. The resulting partition columns are
available for querying in AWS Glue ETL jobs or query engines like Amazon Athena.
After you crawl a table, you can view the partitions that the crawler created by navigating to the table in
the AWS Glue console and choosing View Partitions.
For Apache Hive-style partitioned paths in key=val style, crawlers automatically populate the column
name using the key name. Otherwise, it uses default names like partition_0, partition_1, and so
on. To change the default names on the console, navigate to the table, choose Edit Schema, and modify
the names of the partition columns there.
In your ETL scripts, you can then filter on the partition columns.
glue_context.create_dynamic_frame.from_catalog(
database = "my_S3_data_set",
table_name = "catalog_data_table",
push_down_predicate = my_partition_predicate)
This creates a DynamicFrame that loads only the partitions in the Data Catalog that satisfy the predicate
expression. Depending on how small a subset of your data you are loading, this can save a great deal of
processing time.
The predicate expression can be any Boolean expression supported by Spark SQL. Anything you
could put in a WHERE clause in a Spark SQL query will work. For example, the predicate expression
303
AWS Glue Developer Guide
Grouping Input Files
In addition to Hive-style partitioning for Amazon S3 paths, Apache Parquet and Apache ORC file
formats further partition each file into blocks of data that represent column values. Each block also
stores statistics for the records that it contains, such as min/max for column values. AWS Glue supports
pushdown predicates for both Hive-style partitions and block partitions in these formats. In this way,
you can prune unnecessary Amazon S3 partitions in Parquet and ORC formats, and skip blocks that you
determine are unnecessary using column statistics.
Writing Partitions
By default, a DynamicFrame is not partitioned when it is written. All of the output files are written at
the top level of the specified output path. Until recently, the only way to write a DynamicFrame into
partitions was to convert it to a Spark SQL DataFrame before writing.
However, DynamicFrames now support native partitioning using a sequence of keys, using the
partitionKeys option when you create a sink. For example, the following Python code writes out a
dataset to Amazon S3 in the Parquet format, into directories partitioned by the type field. From there,
you can process these partitions using other systems, such as Amazon Athena.
glue_context.write_dynamic_frame.from_options(
frame = projectedEvents,
connection_type = "s3",
connection_options = {"path": "$outpath", "partitionKeys": ["type"]},
format = "parquet")
To enable grouping files for a table, you set key-value pairs in the parameters field of your table
structure. Use JSON notation to set a value for the parameter field of your table. For more information
about editing the properties of a table, see Viewing and Editing Table Details (p. 108).
You can use this method to enable grouping for tables in the Data Catalog with Amazon S3 data stores.
groupFiles
Set groupFiles to inPartition to enable the grouping of files within an Amazon S3 data partition.
AWS Glue automatically enables grouping if there are more than 50,000 input files. For example:
'groupFiles': 'inPartition'
groupSize
Set groupSize to the target size of groups in bytes. The groupSize property is optional, if not
provided, AWS Glue calculates a size to use all the CPU cores in the cluster while still reducing the
overall number of ETL tasks and in-memory partitions.
304
AWS Glue Developer Guide
Reading from JDBC in Parallel
'groupSize': '1048576'
Note that the groupsize should be set with the result of a calculation. For example 1024 * 1024 =
1048576.
recurse
Set recurse to True to recursively read files in all subdirectories when specifying paths as an
array of paths. You do not need to set recurse if paths is an array of object keys in Amazon S3. For
example:
'recurse':True
To enable parallel reads, you can set key-value pairs in the parameters field of your table structure.
Use JSON notation to set a value for the parameter field of your table. For more information
about editing the properties of a table, see Viewing and Editing Table Details (p. 108). You
can also enable parallel reads when you call the ETL (extract, transform, and load) methods
create_dynamic_frame_from_options and create_dynamic_frame_from_catalog. For
more information about specifying options in these methods, see from_options (p. 351) and
from_catalog (p. 352) .
You can use this method for JDBC tables, that is, most tables whose base data is a JDBC data store. These
properties are ignored when reading Amazon Redshift and Amazon S3 tables.
hashfield
Set hashfield to the name of a column in the JDBC table to be used to divide the data into
partitions. For best results, this column should have an even distribution of values to spread the
data between partitions. This column can be of any data type. AWS Glue generates non-overlapping
queries that run in parallel to read the data partitioned by this column. For example, if your data is
evenly distributed by month, you can use the month column to read each month of data in parallel:
'hashfield': 'month'
305
AWS Glue Developer Guide
Moving Data to and from Amazon Redshift
AWS Glue creates a query to hash the field value to a partition number and runs the query for all
partitions in parallel. To use your own query to partition a table read, provide a hashexpression
instead of a hashfield.
hashexpression
Set hashexpression to an SQL expression (conforming to the JDBC database engine grammar)
that returns a whole number. A simple expression is the name of any numeric column in the table.
AWS Glue generates SQL queries to read the JDBC data in parallel using the hashexpression in
the WHERE clause to partition data.
For example, use the numeric column customerID to read data partitioned by a customer number:
'hashexpression': 'customerID'
To have AWS Glue control the partitioning, provide a hashfield instead of a hashexpression.
hashpartitions
Set hashpartitions to the number of parallel reads of the JDBC table. If this property is not set,
the default value is 7.
For example, set the number of parallel reads to 5 so that AWS Glue reads your data with five
queries (or fewer):
'hashpartitions': '5'
To address this issue, you can associate one or more IAM roles with the Amazon Redshift cluster itself.
COPY and UNLOAD can use the role, and Amazon Redshift refreshes the credentials as needed. For more
information about associating a role with your Amazon Redshift cluster, see IAM Permissions for COPY,
UNLOAD, and CREATE LIBRARY in the Amazon Redshift Database Developer Guide. Make sure that the
role you associate with your cluster has permissions to read from and write to the Amazon S3 temporary
directory that you specified in your job.
After you set up a role for the cluster, you need to specify it in ETL (extract, transform, and load)
statements in the AWS Glue script. The syntax depends on how your script reads and writes your dynamic
frame. If your script reads from an AWS Glue Data Catalog table, you can specify a role as follows:
glueContext.create_dynamic_frame.from_catalog(
database = "database-name",
table_name = "table-name",
redshift_tmp_dir = args["TempDir"],
additional_options = {"aws_iam_role": "arn:aws:iam::account-id:role/role-name"})
306
AWS Glue Developer Guide
Data Catalog Support for Spark SQL Jobs
Similarly, if your scripts writes a dynamic frame and reads from an Data Catalog, you can specify the role
as follows:
glueContext.write_dynamic_frame.from_catalog(
database = "database-name",
table_name = "table-name",
redshift_tmp_dir = args["TempDir"],
additional_options = {"aws_iam_role": "arn:aws:iam::account-id:role/role-name"})
In these examples, role-name is the role that you associated with your Amazon Redshift cluster, and
database-name and table-name refer to an Amazon Redshift table in your Data Catalog.
You can also specify a role when you use a dynamic frame and you use copy_from_options. The
syntax is similar, but you put the additional parameter in the connection-options map:
connection_options = {
"url": "jdbc:redshift://host:port/redshift-database",
"dbtable": "redshift-table",
"user": "username",
"password": "password",
"redshiftTmpDir": args["TempDir"],
"aws_iam_role": "arn:aws:iam::account-id:role/role-name"
}
df = glueContext.create_dynamic_frame_from_options("redshift", connection-options)
connection_options = {
"dbtable": "redshift-table",
"database": "redshift-database",
"aws_iam_role": "arn:aws:iam::account-id:role/role-name"
}
glueContext.write_dynamic_frame.from_jdbc_conf(
frame = input-dynamic-frame,
catalog_connection = "connection-name",
connection_options = connection-options,
redshift_tmp_dir = args["TempDir"])
You can configure AWS Glue jobs and development endpoints by adding the "--enable-glue-
datacatalog": "" argument to job arguments and development endpoint arguments respectively.
Passing this argument sets certain configurations in Spark that enable it to access the Data Catalog as an
external Hive metastore. It also enables Hive support in the SparkSession object created in the AWS
Glue job or development endpoint.
307
AWS Glue Developer Guide
Data Catalog Support for Spark SQL Jobs
To enable the Data Catalog access, check the Use Glue Data Catalog as the Hive metastore check box in
the Catalog options group on the Add job or Add endpoint page on the console. Note that the IAM role
used for the job or development endpoint should have glue:CreateDatabase permissions. A database
called "default" is created in the Data Catalog if it does not exist.
Lets look at an example of how you can use this feature in your Spark SQL jobs. The following example
assumes that you have crawled the US legislators dataset available at s3://awsglue-datasets/
examples/us-legislators.
To serialize/deserialize data from the tables defined in the Glue Data Catalog, Spark SQL needs the Hive
SerDe class for the format defined in the Glue Data Catalog in the classpath of the spark job.
SerDes for certain common formats are distributed by AWS Glue. The following are the Amazon S3 links
for these:
• JSON
• XML
• Grok
Add the JSON SerDe as an extra JAR to the development endpoint. For jobs, you can add the SerDe using
the --extra-jars argument in the arguments field. For more information, see Special Parameters Used
by AWS Glue (p. 296).
Here is an example input JSON to create a development endpoint with the Data Catalog enabled for
Spark SQL.
{
"EndpointName": "Name",
"RoleArn": "role_ARN",
"PublicKey": "public_key_contents",
"NumberOfNodes": 2,
"Arguments": {
"--enable-glue-datacatalog": ""
},
"ExtraJarsS3Path": "s3://crawler-public/json/serde/json-serde.jar"
}
Now query the tables created from the US legislators dataset using Spark SQL.
308
AWS Glue Developer Guide
Excluding Amazon S3 Storage Classes
If the SerDe class for the format is not available in the job's classpath, you will see an error similar to the
one shown below.
To view only the distinct organization_ids from the memberships table, execute the following SQL
query.
If you need to do the same with dynamic frames, execute the following.
While DynamicFrames are optimized for ETL operations, enabling Spark SQL to access the Data Catalog
directly provides a concise way to execute complex SQL statements or port existing applications.
309
AWS Glue Developer Guide
Excluding Amazon S3 Storage Classes
For more information, see Amazon S3 Storage Classes in the Amazon S3 Developer Guide.
The examples in this section show how to exclude the GLACIER and DEEP_ARCHIVE storage classes.
These classes allow you to list files, but they won't let you read the files unless they are restored. (For
more information, see Restoring Archived Objects in the Amazon S3 Developer Guide.)
By using storage class exclusions, you can ensure that your AWS Glue jobs will work on tables that have
partitions across these storage class tiers. Without exclusions, jobs that read data from these tiers fail
with the following error: AmazonS3Exception: The operation is not valid for the object's storage class.
There are different ways that you can filter Amazon S3 storage classes in AWS Glue.
Topics
• Excluding Amazon S3 Storage Classes When Creating a Dynamic Frame (p. 310)
• Excluding Amazon S3 Storage Classes on a Data Catalog Table (p. 310)
The following Python and Scala examples show how to exclude the GLACIER and DEEP_ARCHIVE
storage classes when creating a dynamic frame.
Python example:
glueContext.create_dynamic_frame.from_catalog(
database = "my_database",
tableName = "my_table_name",
redshift_tmp_dir = "",
transformation_ctx = "my_transformation_context",
additional_options = {
"excludeStorageClasses" : ["GLACIER", "DEEP_ARCHIVE"]
}
)
Scala example:
310
AWS Glue Developer Guide
Developing and Testing ETL Scripts Locally
You can also specify excluded storage classes on the AWS Glue console.
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. In the navigation pane on the left, choose Tables.
3. Choose the table name in the list, and then choose Edit table.
4. In Table properties, add excludeStorageClasses as a key and [\"GLACIER\",
\"DEEP_ARCHIVE\"] as a value.
5. Choose Apply.
Local development is available for AWS Glue versions 0.9 and 1.0. For information about the versions of
Python and Apache Spark that are available with AWS Glue, see the Glue version job property (p. 162).
Topics
• Local Development Restrictions (p. 311)
• Developing Locally with Python (p. 311)
• Developing Locally with Scala (p. 312)
• Avoid creating an assembly jar ("fat jar" or "uber jar") with the AWS Glue library, as this will cause the
following features to be disabled:
• Job bookmarks
• Glue Parquet writer (format="glueparquet" (p. 302))
• FindMatches transform
These feature are available only within the AWS Glue job system.
311
AWS Glue Developer Guide
Developing and Testing ETL Scripts Locally
Use the following utilities and frameworks to test and run your Python script. The commands listed
in the following table are run from the root directory of the AWS Glue Python package (https://
github.com/awslabs/aws-glue-libs).
Glue Shell ./bin/gluepyspark Enter and run Python scripts in a shell that
integrates with AWS Glue ETL libraries.
Pytest ./bin/gluepytest Write and run unit tests of your Python code. The
pytest module must be installed and available
in the PATH. For more information, see https://
docs.pytest.org/en/latest/.
In this task you install software and set the required environment variable.
312
AWS Glue Developer Guide
Developing and Testing ETL Scripts Locally
<properties>
<scala.version>2.11.1</scala.version>
</properties>
<dependencies>
<dependency>
<groupId>org.scala-lang</groupId>
<artifactId>scala-library</artifactId>
<version>${scala.version}</version>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>AWSGlueETL</artifactId>
<version>Glue version</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>aws-glue-etl-artifacts</id>
<url>https://aws-glue-etl-artifacts.s3.amazonaws.com/release/</url>
</repository>
</repositories>
<build>
<sourceDirectory>src/main/scala</sourceDirectory>
<plugins>
<plugin>
<!-- see http://davidb.github.com/scala-maven-plugin -->
<groupId>net.alchim31.maven</groupId>
<artifactId>scala-maven-plugin</artifactId>
<version>3.4.0</version>
<executions>
<execution>
<goals>
<goal>compile</goal>
<goal>testCompile</goal>
313
AWS Glue Developer Guide
Developing and Testing ETL Scripts Locally
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
<execution>
<goals>
<goal>java</goal>
</goals>
</execution>
</executions>
<configuration>
<systemProperties>
<systemProperty>
<key>spark.master</key>
<value>local[*]</value>
</systemProperty>
<systemProperty>
<key>spark.app.name</key>
<value>localrun</value>
</systemProperty>
<systemProperty>
<key>org.xerial.snappy.lib.name</key>
<value>libsnappyjava.jnilib</value>
</systemProperty>
</systemProperties>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-enforcer-plugin</artifactId>
<version>3.0.0-M2</version>
<executions>
<execution>
<id>enforce-maven</id>
<goals>
<goal>enforce</goal>
</goals>
<configuration>
<rules>
<requireMavenVersion>
<version>3.5.3</version>
</requireMavenVersion>
</rules>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
Replace mainClass with the fully qualified class name of the script's main class. Replace jobName with
the desired job name.
314
AWS Glue Developer Guide
ETL Programming in Python
315
AWS Glue Developer Guide
Python Setup
1. If you don't already have Python installed, download and install it from the Python.org download
page.
2. Install the AWS Command Line Interface (AWS CLI) as documented in the AWS CLI documentation.
The AWS CLI is not directly necessary for using Python. However, installing and configuring it is a
convenient way to set up AWS with your account credentials and verify that they work.
3. Install the AWS SDK for Python (Boto 3), as documented in the Boto3 Quickstart.
Boto 3 resource APIs are not yet available for AWS Glue. Currently, only the Boto 3 client APIs can be
used.
For more information about Boto 3, see AWS SDK for Python (Boto 3) Getting Started.
You can find Python code examples and utilities for AWS Glue in the AWS Glue samples repository on the
GitHub website.
However, although the AWS Glue API names themselves are transformed to lowercase, their parameter
names remain capitalized. It is important to remember this, because parameters should be passed by
name when calling AWS Glue APIs, as described in the following section.
316
AWS Glue Developer Guide
Calling APIs
It is helpful to understand that Python creates a dictionary of the name/value tuples that you specify
as arguments to an ETL script in a Job Structure (p. 534) or JobRun Structure (p. 546). Boto 3 then
passes them to AWS Glue in JSON format by way of a REST API call. This means that you cannot rely on
the order of the arguments when you access them in your script.
For example, suppose that you're starting a JobRun in a Python Lambda handler function, and you want
to specify several parameters. Your code might look something like the following:
client = boto3.client('glue')
response = client.start_job_run(
JobName = 'my_test_Job',
Arguments = {
'--day_partition_key': 'partition_0',
'--hour_partition_key': 'partition_1',
'--day_partition_value': day_partition_value,
'--hour_partition_value': hour_partition_value } )
To access these parameters reliably in your ETL script, specify them by name using AWS Glue's
getResolvedOptions function and then access them from the resulting dictionary:
import sys
from awsglue.utils import getResolvedOptions
args = getResolvedOptions(sys.argv,
['JOB_NAME',
'day_partition_key',
'hour_partition_key',
'day_partition_value',
'hour_partition_value'])
print "The day partition key is: ", args['day_partition_key']
print "and the day partition value is: ", args['day_partition_value']
import boto3
glue = boto3.client(service_name='glue', region_name='us-east-1',
endpoint_url='https://glue.us-east-1.amazonaws.com')
2. Create a job. You must use glueetl as the name for the ETL command, as shown in the following
code:
317
AWS Glue Developer Guide
Python Libraries
3. Start a new run of the job that you created in the previous step:
myNewJobRun = glue.start_job_run(JobName=myJob['Name'])
print status['JobRun']['JobRunState']
If your library only consists of a single Python module in one .py file, you do not need to place it in a
.zip file.
You can use the console to specify one or more library .zip files for a development endpoint when you
create it. After assigning a name and an IAM role, choose Script Libraries and job parameters (optional)
and enter the full Amazon S3 path to your library .zip file in the Python library path box. For example:
s3://bucket/prefix/site-packages.zip
If you want, you can specify multiple full paths to files, separating them with commas but no spaces, like
this:
s3://bucket/prefix/lib_A.zip,s3://bucket_B/prefix/lib_X.zip
If you update these .zip files later, you can use the console to re-import them into your development
endpoint. Navigate to the developer endpoint in question, check the box beside it, and choose Update
ETL libraries from the Action menu.
In a similar way, you can specify library files using the AWS Glue APIs. When you create a development
endpoint by calling CreateDevEndpoint Action (Python: create_dev_endpoint) (p. 578), you can specify
one or more full paths to libraries in the ExtraPythonLibsS3Path parameter, in a call that looks this:
dep = glue.create_dev_endpoint(
318
AWS Glue Developer Guide
Python Samples
EndpointName="testDevEndpoint",
RoleArn="arn:aws:iam::123456789012",
SecurityGroupIds="sg-7f5ad1ff",
SubnetId="subnet-c12fdba4",
PublicKey="ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCtp04H/y...",
NumberOfNodes=3,
ExtraPythonLibsS3Path="s3://bucket/prefix/lib_A.zip,s3://bucket_B/prefix/
lib_X.zip")
When you update a development endpoint, you can also update the libraries it loads using a
DevEndpointCustomLibraries (p. 577) object and setting the UpdateEtlLibraries parameter to
True when calling UpdateDevEndpoint (update_dev_endpoint) (p. 581).
If you are using a Zeppelin Notebook with your development endpoint, you will need to call the
following PySpark function before importing a package or packages from your .zip file:
sc.addPyFile(“/home/glue/downloads/python/yourZipFileName.zip”)
s3://bucket/prefix/lib_A.zip,s3://bucket_B/prefix/lib_X.zip
If you are calling CreateJob (create_job) (p. 540), you can specify one or more full paths to default
libraries using the --extra-py-files default parameter, like this:
job = glue.create_job(Name='sampleJob',
Role='Glue_DefaultRole',
Command={'Name': 'glueetl',
'ScriptLocation': 's3://my_script_bucket/scripts/
my_etl_script.py'},
DefaultArguments={'--extra-py-files': 's3://bucket/prefix/
lib_A.zip,s3://bucket_B/prefix/lib_X.zip'})
Then when you are starting a JobRun, you can override the default library setting with a different one:
runId = glue.start_job_run(JobName='sampleJob',
Arguments={'--extra-py-files': 's3://bucket/prefix/lib_B.zip'})
319
AWS Glue Developer Guide
Python Samples
You can find the source code for this example in the join_and_relationalize.py file in the AWS
Glue samples repository on the GitHub website.
Using this data, this tutorial shows you how to do the following:
• Use an AWS Glue crawler to classify objects that are stored in a public Amazon S3 bucket and save
their schemas into the AWS Glue Data Catalog.
• Examine the table metadata and schemas that result from the crawl.
• Write a Python extract, transfer, and load (ETL) script that uses the metadata in the Data Catalog to do
the following:
• Join the data in the different source files together into a single data table (that is, denormalize the
data).
• Filter the joined table into separate tables by type of legislator.
• Write out the resulting data to separate Apache Parquet files for later analysis.
The easiest way to debug Python or PySpark scripts is to create a development endpoint and run your
code there. We recommend that you start by setting up a development endpoint to work in. For more
information, see the section called “Viewing Development Endpoint Properties” (p. 184).
• persons_json
• memberships_json
• organizations_json
• events_json
• areas_json
• countries_r_json
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
320
AWS Glue Developer Guide
Python Samples
glueContext = GlueContext(SparkContext.getOrCreate())
persons = glueContext.create_dynamic_frame.from_catalog(
database="legislators",
table_name="persons_json")
print "Count: ", persons.count()
persons.printSchema()
Count: 1961
root
|-- family_name: string
|-- name: string
|-- links: array
| |-- element: struct
| | |-- note: string
| | |-- url: string
|-- gender: string
|-- image: string
|-- identifiers: array
| |-- element: struct
| | |-- scheme: string
| | |-- identifier: string
|-- other_names: array
| |-- element: struct
| | |-- note: string
| | |-- name: string
| | |-- lang: string
|-- sort_name: string
|-- images: array
| |-- element: struct
| | |-- url: string
|-- given_name: string
|-- birth_date: string
|-- id: string
|-- contact_details: array
| |-- element: struct
| | |-- type: string
| | |-- value: string
|-- death_date: string
memberships = glueContext.create_dynamic_frame.from_catalog(
database="legislators",
table_name="memberships_json")
print "Count: ", memberships.count()
memberships.printSchema()
321
AWS Glue Developer Guide
Python Samples
Count: 10439
root
|-- area_id: string
|-- on_behalf_of_id: string
|-- organization_id: string
|-- role: string
|-- person_id: string
|-- legislative_period_id: string
|-- start_date: string
|-- end_date: string
The organizations are parties and the two chambers of Congress, the Senate and House of
Representatives. To view the schema of the organizations_json table, type the following:
orgs = glueContext.create_dynamic_frame.from_catalog(
database="legislators",
table_name="organizations_json")
print "Count: ", orgs.count()
orgs.printSchema()
Count: 13
root
|-- classification: string
|-- links: array
| |-- element: struct
| | |-- note: string
| | |-- url: string
|-- image: string
|-- identifiers: array
| |-- element: struct
| | |-- scheme: string
| | |-- identifier: string
|-- other_names: array
| |-- element: struct
| | |-- lang: string
| | |-- note: string
| | |-- name: string
|-- id: string
|-- name: string
|-- seats: int
|-- type: string
The toDF() converts a DynamicFrame to an Apache Spark DataFrame, so you can apply the
transforms that already exist in Apache Spark SQL:
orgs = orgs.drop_fields(['other_names',
'identifiers']).rename_field(
'id', 'org_id').rename_field(
'name', 'org_name')
322
AWS Glue Developer Guide
Python Samples
orgs.toDF().show()
+--------------+--------------------+--------------------+--------------------+-----
+-----------+--------------------+
|classification| org_id| org_name| links|seats|
type| image|
+--------------+--------------------+--------------------+--------------------+-----
+-----------+--------------------+
| party| party/al| AL| null| null|
null| null|
| party| party/democrat| Democrat|[[website,http://...| null|
null|https://upload.wi...|
| party|party/democrat-li...| Democrat-Liberal|[[website,http://...| null|
null| null|
| legislature|d56acebe-8fdc-47b...|House of Represen...| null| 435|lower
house| null|
| party| party/independent| Independent| null| null|
null| null|
| party|party/new_progres...| New Progressive|[[website,http://...| null|
null|https://upload.wi...|
| party|party/popular_dem...| Popular Democrat|[[website,http://...| null|
null| null|
| party| party/republican| Republican|[[website,http://...| null|
null|https://upload.wi...|
| party|party/republican-...|Republican-Conser...|[[website,http://...| null|
null| null|
| party| party/democrat| Democrat|[[website,http://...| null|
null|https://upload.wi...|
| party| party/independent| Independent| null| null|
null| null|
| party| party/republican| Republican|[[website,http://...| null|
null|https://upload.wi...|
| legislature|8fa6c3d2-71dc-478...| Senate| null| 100|upper
house| null|
+--------------+--------------------+--------------------+--------------------+-----
+-----------+--------------------+
memberships.select_fields(['organization_id']).toDF().distinct().show()
+--------------------+
| organization_id|
+--------------------+
|d56acebe-8fdc-47b...|
|8fa6c3d2-71dc-478...|
+--------------------+
323
AWS Glue Developer Guide
Python Samples
l_history = Join.apply(orgs,
Join.apply(persons, memberships, 'id', 'person_id'),
'org_id', 'organization_id').drop_fields(['person_id', 'org_id'])
print "Count: ", l_history.count()
l_history.printSchema()
Count: 10439
root
|-- role: string
|-- seats: int
|-- org_name: string
|-- links: array
| |-- element: struct
| | |-- note: string
| | |-- url: string
|-- type: string
|-- sort_name: string
|-- area_id: string
|-- images: array
| |-- element: struct
| | |-- url: string
|-- on_behalf_of_id: string
|-- other_names: array
| |-- element: struct
| | |-- note: string
| | |-- name: string
| | |-- lang: string
|-- contact_details: array
| |-- element: struct
| | |-- type: string
| | |-- value: string
|-- name: string
|-- birth_date: string
|-- organization_id: string
|-- gender: string
|-- classification: string
|-- death_date: string
|-- legislative_period_id: string
|-- identifiers: array
| |-- element: struct
| | |-- scheme: string
| | |-- identifier: string
|-- image: string
|-- given_name: string
|-- family_name: string
|-- id: string
|-- start_date: string
|-- end_date: string
You now have the final table that you can use for analysis. You can write it out in a compact, efficient
format for analytics—namely Parquet—that you can run SQL over in AWS Glue, Amazon Athena, or
Amazon Redshift Spectrum.
324
AWS Glue Developer Guide
Python Samples
The following call writes the table across multiple files to support fast parallel reads when doing analysis
later:
glueContext.write_dynamic_frame.from_options(frame = l_history,
connection_type = "s3",
connection_options = {"path": "s3://glue-sample-target/output-dir/
legislator_history"},
format = "parquet")
To put all the history data into a single file, you must convert it to a data frame, repartition it, and write
it out:
s_history = l_history.toDF().repartition(1)
s_history.write.parquet('s3://glue-sample-target/output-dir/legislator_single')
l_history.toDF().write.parquet('s3://glue-sample-target/output-dir/legislator_part',
partitionBy=['org_name'])
Using the l_history DynamicFrame in this example, pass in the name of a root table (hist_root)
and a temporary working path to relationalize. This returns a DynamicFrameCollection. You can
then list the names of the DynamicFrames in that collection:
Relationalize broke the history table out into six new tables: a root table that contains a record
for each object in the DynamicFrame, and auxiliary tables for the arrays. Array handling in relational
databases is often suboptimal, especially as those arrays become large. Separating the arrays into
different tables makes the queries go much faster.
l_history.select_fields('contact_details').printSchema()
dfc.select('hist_root_contact_details').toDF().where("id = 10 or id =
75").orderBy(['id','index']).show()
325
AWS Glue Developer Guide
Python Samples
root
|-- contact_details: array
| |-- element: struct
| | |-- type: string
| | |-- value: string
+---+-----+------------------------+-------------------------+
| id|index|contact_details.val.type|contact_details.val.value|
+---+-----+------------------------+-------------------------+
| 10| 0| fax| |
| 10| 1| | 202-225-1314|
| 10| 2| phone| |
| 10| 3| | 202-225-3772|
| 10| 4| twitter| |
| 10| 5| | MikeRossUpdates|
| 75| 0| fax| |
| 75| 1| | 202-225-7856|
| 75| 2| phone| |
| 75| 3| | 202-225-2711|
| 75| 4| twitter| |
| 75| 5| | SenCapito|
+---+-----+------------------------+-------------------------+
The contact_details field was an array of structs in the original DynamicFrame. Each element of
those arrays is a separate row in the auxiliary table, indexed by index. The id here is a foreign key into
the hist_root table with the key contact_details:
dfc.select('hist_root').toDF().where(
"contact_details = 10 or contact_details = 75").select(
['id', 'given_name', 'family_name', 'contact_details']).show()
+--------------------+----------+-----------+---------------+
| id|given_name|family_name|contact_details|
+--------------------+----------+-----------+---------------+
|f4fc30ee-7b42-432...| Mike| Ross| 10|
|e3c60f34-7d1b-4c0...| Shelley| Capito| 75|
+--------------------+----------+-----------+---------------+
Notice in these commands that toDF() and then a where expression are used to filter for the rows that
you want to see.
So, joining the hist_root table with the auxiliary tables lets you do the following:
You already have a connection set up named redshift3. For information about how to create your own
connection, see the section called “Adding a Connection to Your Data Store” (p. 109).
Next, write this collection into Amazon Redshift by cycling through the DynamicFrames one at a time:
326
AWS Glue Developer Guide
Python Samples
glueContext.write_dynamic_frame.from_jdbc_conf(frame = m_df,
catalog_connection = "redshift3",
connection_options = {"dbtable":
df_name, "database": "testdb"},
redshift_tmp_dir = "s3://glue-sample-
target/temp-dir/")
The dbtable property is the name of the JDBC table. For JDBC data stores that support schemas within
a database, specify schema.table-name. If a schema is not provided, then the default "public" schema
is used.
For more information, see Connection Types and Options for ETL in AWS Glue (p. 298).
Here's what the tables look like in Amazon Redshift. (You connected to Amazon Redshift through psql.)
testdb=# \d
List of relations
schema | name | type | owner
--------+---------------------------+-------+-----------
public | hist_root | table | test_user
public | hist_root_contact_details | table | test_user
public | hist_root_identifiers | table | test_user
public | hist_root_images | table | test_user
public | hist_root_links | table | test_user
public | hist_root_other_names | table | test_user
(6 rows)
testdb=# \d hist_root_contact_details
Table "public.hist_root_contact_details"
Column | Type | Modifiers
---------------------------+--------------------------+-----------
id | bigint |
index | integer |
contact_details.val.type | character varying(65535) |
contact_details.val.value | character varying(65535) |
testdb=# \d hist_root
Table "public.hist_root"
Column | Type | Modifiers
-----------------------+--------------------------+-----------
role | character varying(65535) |
seats | integer |
org_name | character varying(65535) |
links | bigint |
type | character varying(65535) |
sort_name | character varying(65535) |
area_id | character varying(65535) |
images | bigint |
on_behalf_of_id | character varying(65535) |
other_names | bigint |
birth_date | character varying(65535) |
name | character varying(65535) |
organization_id | character varying(65535) |
gender | character varying(65535) |
classification | character varying(65535) |
legislative_period_id | character varying(65535) |
identifiers | bigint |
given_name | character varying(65535) |
image | character varying(65535) |
family_name | character varying(65535) |
id | character varying(65535) |
death_date | character varying(65535) |
start_date | character varying(65535) |
327
AWS Glue Developer Guide
Python Samples
contact_details | bigint |
end_date | character varying(65535) |
Now you can query these tables using SQL in Amazon Redshift:
Conclusion
Overall, AWS Glue is very flexible. It lets you accomplish, in a few lines of code, what normally
would take days to write. You can find the entire source-to-target ETL scripts in the Python file
join_and_relationalize.py in the AWS Glue samples on GitHub.
You can find the source code for this example in the data_cleaning_and_lambda.py file in the AWS
Glue examples GitHub repository.
The easiest way to debug Python or PySpark scripts is to create a development endpoint and run your
code there. We recommend that you start by setting up a development endpoint to work in. For more
information, see the section called “Viewing Development Endpoint Properties” (p. 184).
328
AWS Glue Developer Guide
Python Samples
import sys
from awsglue.transforms import *
from awsglue.utils import getResolvedOptions
from pyspark.context import SparkContext
from awsglue.context import GlueContext
from awsglue.job import Job
glueContext = GlueContext(SparkContext.getOrCreate())
medicare = spark.read.format(
"com.databricks.spark.csv").option(
"header", "true").option(
"inferSchema", "true").load(
's3://awsglue-datasets/examples/medicare/Medicare_Hospital_Provider.csv')
medicare.printSchema()
root
|-- DRG Definition: string (nullable = true)
|-- Provider Id: string (nullable = true)
|-- Provider Name: string (nullable = true)
|-- Provider Street Address: string (nullable = true)
|-- Provider City: string (nullable = true)
|-- Provider State: string (nullable = true)
|-- Provider Zip Code: integer (nullable = true)
|-- Hospital Referral Region Description: string (nullable = true)
|-- Total Discharges : integer (nullable = true)
|-- Average Covered Charges : string (nullable = true)
329
AWS Glue Developer Guide
Python Samples
medicare_dynamicframe = glueContext.create_dynamic_frame.from_catalog(
database = "payments",
table_name = "medicare")
medicare_dynamicframe.printSchema()
root
|-- drg definition: string
|-- provider id: choice
| |-- long
| |-- string
|-- provider name: string
|-- provider street address: string
|-- provider city: string
|-- provider state: string
|-- provider zip code: long
|-- hospital referral region description: string
|-- total discharges: long
|-- average covered charges: string
|-- average total payments: string
|-- average medicare payments: string
The DynamicFrame generates a schema in which provider id could be either a long or a string
type. The DataFrame schema lists Provider Id as being a string type, and the Data Catalog lists
provider id as being a bigint type.
Which one is correct? There are two records at the end of the file (out of 160,000 records) with string
values in that column. These are the erroneous records that were introduced to illustrate a problem.
To address this kind of problem, the AWS Glue DynamicFrame introduces the concept of a choice type.
In this case, the DynamicFrame shows that both long and string values can appear in that column.
The AWS Glue crawler missed the string values because it considered only a 2 MB prefix of the data.
The Apache Spark DataFrame considered the whole dataset, but it was forced to assign the most
general type to the column, namely string. In fact, Spark often resorts to the most general case when
there are complex types or variations with which it is unfamiliar.
To query the provider id column, resolve the choice type first. You can use the resolveChoice
transform method in your DynamicFrame to convert those string values to long values with a
cast:long option:
root
|-- drg definition: string
|-- provider id: long
|-- provider name: string
330
AWS Glue Developer Guide
Python Samples
Where the value was a string that could not be cast, AWS Glue inserted a null.
Another option is to convert the choice type to a struct, which keeps values of both types.
+--------------------+-----------+---------------+-----------------------+-------------
+--------------+-----------------+------------------------------------+----------------
+-----------------------+----------------------+-------------------------+
| drg definition|provider id| provider name|provider street address|provider city|
provider state|provider zip code|hospital referral region description|total discharges|
average covered charges|average total payments|average medicare payments|
+--------------------+-----------+---------------+-----------------------+-------------
+--------------+-----------------+------------------------------------+----------------
+-----------------------+----------------------+-------------------------+
|948 - SIGNS & SYM...| null| INC| 1050 DIVISION ST| MAUSTON|
WI| 53948| WI - Madison| 12|
$11961.41| $4619.00| $3775.33|
|948 - SIGNS & SYM...| null| INC- ST JOSEPH| 5000 W CHAMBERS ST| MILWAUKEE|
WI| 53210| WI - Milwaukee| 14|
$10514.28| $5562.50| $4522.78|
+--------------------+-----------+---------------+-----------------------+-------------
+--------------+-----------------+------------------------------------+----------------
+-----------------------+----------------------+-------------------------+
medicare_dataframe = medicare_res.toDF()
medicare_dataframe = medicare_dataframe.where("'provider id' is NOT NULL")
Step 4: Map the Data and Use Apache Spark Lambda Functions
AWS Glue does not yet directly support Lambda functions, also known as user-defined functions. But
you can always convert a DynamicFrame to and from an Apache Spark DataFrame to take advantage of
Spark functionality in addition to the special features of DynamicFrames.
Next, turn the payment information into numbers, so analytic engines like Amazon Redshift or Amazon
Athena can do their number crunching faster:
331
AWS Glue Developer Guide
Python Samples
+--------+-------+-------+
| ACC| ATP| AMP|
+--------+-------+-------+
|32963.07|5777.24|4763.73|
|15131.85|5787.57|4976.71|
|37560.37|5434.95|4453.79|
|13998.28|5417.56|4129.16|
|31633.27|5658.33|4851.44|
|16920.79|6653.80|5374.14|
|11977.13|5834.74|4761.41|
|35841.09|8031.12|5858.50|
|28523.39|6113.38|5228.40|
|75233.38|5541.05|4386.94|
|67327.92|5461.57|4493.57|
|39607.28|5356.28|4408.20|
|22862.23|5374.65|4186.02|
|31110.85|5366.23|4376.23|
|25411.33|5282.93|4383.73|
| 9234.51|5676.55|4509.11|
|15895.85|5930.11|3972.85|
|19721.16|6192.54|5179.38|
|10710.88|4968.00|3898.88|
|51343.75|5996.00|4962.45|
+--------+-------+-------+
only showing top 20 rows
These are all still strings in the data. We can use the powerful apply_mapping transform method to
drop, rename, cast, and nest the data so that other data programming languages and systems can easily
access it:
root
|-- drg: string
|-- provider: struct
| |-- id: long
332
AWS Glue Developer Guide
PySpark Extensions
Turning the data back into a Spark DataFrame, you can show what it looks like now:
medicare_nest_dyf.toDF().show()
+--------------------+--------------------+---------------+--------------------+
| drg| provider| rr| charges|
+--------------------+--------------------+---------------+--------------------+
|039 - EXTRACRANIA...|[10001,SOUTHEAST ...| AL - Dothan|[32963.07,5777.24...|
|039 - EXTRACRANIA...|[10005,MARSHALL M...|AL - Birmingham|[15131.85,5787.57...|
|039 - EXTRACRANIA...|[10006,ELIZA COFF...|AL - Birmingham|[37560.37,5434.95...|
|039 - EXTRACRANIA...|[10011,ST VINCENT...|AL - Birmingham|[13998.28,5417.56...|
|039 - EXTRACRANIA...|[10016,SHELBY BAP...|AL - Birmingham|[31633.27,5658.33...|
|039 - EXTRACRANIA...|[10023,BAPTIST ME...|AL - Montgomery|[16920.79,6653.8,...|
|039 - EXTRACRANIA...|[10029,EAST ALABA...|AL - Birmingham|[11977.13,5834.74...|
|039 - EXTRACRANIA...|[10033,UNIVERSITY...|AL - Birmingham|[35841.09,8031.12...|
|039 - EXTRACRANIA...|[10039,HUNTSVILLE...|AL - Huntsville|[28523.39,6113.38...|
|039 - EXTRACRANIA...|[10040,GADSDEN RE...|AL - Birmingham|[75233.38,5541.05...|
|039 - EXTRACRANIA...|[10046,RIVERVIEW ...|AL - Birmingham|[67327.92,5461.57...|
|039 - EXTRACRANIA...|[10055,FLOWERS HO...| AL - Dothan|[39607.28,5356.28...|
|039 - EXTRACRANIA...|[10056,ST VINCENT...|AL - Birmingham|[22862.23,5374.65...|
|039 - EXTRACRANIA...|[10078,NORTHEAST ...|AL - Birmingham|[31110.85,5366.23...|
|039 - EXTRACRANIA...|[10083,SOUTH BALD...| AL - Mobile|[25411.33,5282.93...|
|039 - EXTRACRANIA...|[10085,DECATUR GE...|AL - Huntsville|[9234.51,5676.55,...|
|039 - EXTRACRANIA...|[10090,PROVIDENCE...| AL - Mobile|[15895.85,5930.11...|
|039 - EXTRACRANIA...|[10092,D C H REGI...|AL - Tuscaloosa|[19721.16,6192.54...|
|039 - EXTRACRANIA...|[10100,THOMAS HOS...| AL - Mobile|[10710.88,4968.0,...|
|039 - EXTRACRANIA...|[10103,BAPTIST ME...|AL - Birmingham|[51343.75,5996.0,...|
+--------------------+--------------------+---------------+--------------------+
only showing top 20 rows
glueContext.write_dynamic_frame.from_options(
frame = medicare_nest_dyf,
connection_type = "s3",
connection_options = {"path": "s3://glue-sample-target/output-dir/
medicare_parquet"},
format = "parquet")
333
AWS Glue Developer Guide
PySpark Extensions
import sys
from awsglue.utils import getResolvedOptions
getResolvedOptions(args, options)
Suppose that you created a JobRun in a script, perhaps within a Lambda function:
response = client.start_job_run(
JobName = 'my_test_Job',
Arguments = {
'--day_partition_key': 'partition_0',
'--hour_partition_key': 'partition_1',
'--day_partition_value': day_partition_value,
'--hour_partition_value': hour_partition_value } )
To retrieve the arguments that are passed, you can use the getResolvedOptions function as follows:
import sys
from awsglue.utils import getResolvedOptions
args = getResolvedOptions(sys.argv,
['JOB_NAME',
'day_partition_key',
'hour_partition_key',
'day_partition_value',
'hour_partition_value'])
print "The day-partition key is: ", args['day_partition_key']
print "and the day-partition value is: ", args['day_partition_value']
Note that each of the arguments are defined as beginning with two hyphens, then referenced in the
script without the hyphens. Your arguments need to follow this convention to be resolved.
334
AWS Glue Developer Guide
PySpark Extensions
DataType
The base class for the other AWS Glue types.
__init__(properties={})
typeName(cls)
Returns the type of the AWS Glue type class (that is, the class name with "Type" removed from the end).
jsonValue( )
Returns a JSON object that contains the data type and properties of the class:
{
"dataType": typeName,
"properties": properties
}
fromJsonValue(cls, json_value)
The following types are simple derivatives of the AtomicType (p. 335) class:
335
AWS Glue Developer Guide
PySpark Extensions
DecimalType(AtomicType)
Inherits from and extends the AtomicType (p. 335) class to represent a decimal number (a number
expressed in decimal digits, as opposed to binary base-2 numbers).
• precision – The number of digits in the decimal number (optional; the default is 10).
• scale – The number of digits to the right of the decimal point (optional; the default is 2).
• properties – The properties of the decimal number (optional).
EnumType(AtomicType)
Inherits from and extends the AtomicType (p. 335) class to represent an enumeration of valid options.
__init__(options)
Collection Types
• ArrayType(DataType) (p. 336)
• ChoiceType(DataType) (p. 336)
• MapType(DataType) (p. 337)
• Field(Object) (p. 337)
• StructType(DataType) (p. 337)
• EntityType(DataType) (p. 337)
ArrayType(DataType)
__init__(elementType=UnknownType(), properties={})
• elementType – The type of elements in the array (optional; the default is UnknownType).
• properties – Properties of the array (optional).
ChoiceType(DataType)
__init__(choices=[], properties={})
add(new_choice)
Adds a new choice to the list of possible choices.
336
AWS Glue Developer Guide
PySpark Extensions
merge(new_choices)
MapType(DataType)
__init__(valueType=UnknownType, properties={})
• valueType – The type of values in the map (optional; the default is UnknownType).
• properties – Properties of the map (optional).
Field(Object)
Creates a field object out of an object that derives from DataType (p. 335).
StructType(DataType)
Defines a data structure (struct).
__init__(fields=[], properties={})
• fields – A list of the fields (of type Field) to include in the structure (optional).
• properties – Properties of the structure (optional).
add(field)
hasField(field)
Returns True if this structure has a field of the same name, or False if not.
getField(field)
• field – A field name or an object of type Field whose name is used. If the structure has a field of the
same name, it is returned.
EntityType(DataType)
__init__(entity, base_type, properties)
337
AWS Glue Developer Guide
PySpark Extensions
Other Types
• DataSource(object) (p. 338)
• DataSink(object) (p. 338)
DataSource(object)
setFormat(format, **options)
getFrame()
DataSink(object)
__init__(j_sink, sql_ctx)
setFormat(format, **options)
setAccumulableSize(size)
writeFrame(dynamic_frame, info="")
338
AWS Glue Developer Guide
PySpark Extensions
write(dynamic_frame_or_dfc, info="")
Writes a DynamicFrame or a DynamicFrameCollection.
DynamicFrame Class
One of the major abstractions in Apache Spark is the SparkSQL DataFrame, which is similar to the
DataFrame construct found in R and Pandas. A DataFrame is similar to a table and supports functional-
style (map/reduce/filter/etc.) operations and SQL operations (select, project, aggregate).
DataFrames are powerful and widely used, but they have limitations with respect to extract, transform,
and load (ETL) operations. Most significantly, they require a schema to be specified before any data is
loaded. SparkSQL addresses this by making two passes over the data—the first to infer the schema,
and the second to load the data. However, this inference is limited and doesn't address the realities of
messy data. For example, the same field might be of a different type in different records. Apache Spark
often gives up and reports the type as string using the original field text. This might not be correct,
and you might want finer control over how schema discrepancies are resolved. And for large datasets, an
additional pass over the source data might be prohibitively expensive.
To address these limitations, AWS Glue introduces the DynamicFrame. A DynamicFrame is similar to a
DataFrame, except that each record is self-describing, so no schema is required initially. Instead, AWS
Glue computes a schema on-the-fly when required, and explicitly encodes schema inconsistencies using a
choice (or union) type. You can resolve these inconsistencies to make your datasets compatible with data
stores that require a fixed schema.
You can convert DynamicFrames to and from DataFrames once you resolve any schema
inconsistencies.
— Construction —
• __init__ (p. 339)
• fromDF (p. 339)
• toDF (p. 340)
__init__
__init__(jdf, glue_ctx, name)
• jdf – A reference to the data frame in the Java Virtual Machine (JVM).
• glue_ctx – A GlueContext Class (p. 352) object.
• name – An optional name string, empty by default.
fromDF
fromDF(dataframe, glue_ctx, name)
Converts a DataFrame to a DynamicFrame by converting DataFrame fields to DynamicRecord fields.
Returns the new DynamicFrame.
339
AWS Glue Developer Guide
PySpark Extensions
toDF
toDF(options)
• options – A list of options. Specify the target type if you choose the Project and Cast action type.
Examples include the following:
>>>toDF([ResolveOption("a.b.c", "KeepAsStruct")])
>>>toDF([ResolveOption("a.b.c", "Project", DoubleType())])
— Information —
• count (p. 340)
• schema (p. 340)
• printSchema (p. 340)
• show (p. 340)
count
count( ) – Returns the number of rows in the underlying DataFrame.
schema
schema( ) – Returns the schema of this DynamicFrame, or if that is not available, the schema of the
underlying DataFrame.
printSchema
printSchema( ) – Prints the schema of the underlying DataFrame.
show
show(num_rows) – Prints a specified number of rows from the underlying DataFrame.
— Transforms —
• apply_mapping (p. 341)
340
AWS Glue Developer Guide
PySpark Extensions
apply_mapping
apply_mapping(mappings, transformation_ctx="", info="", stageThreshold=0,
totalThreshold=0)
Applies a declarative mapping to this DynamicFrame and returns a new DynamicFrame with those
mappings applied.
• mappings – A list of mapping tuples, each consisting of: (source column, source type, target column,
target type). Required.
• transformation_ctx – A unique string that is used to identify state information (optional).
• info – A string to be associated with error reporting for this transformation (optional).
• stageThreshold – The number of errors encountered during this transformation at which the
process should error out (optional: zero by default, indicating that the process should not error out).
• totalThreshold – The number of errors encountered up to and including this transformation at
which the process should error out (optional: zero by default, indicating that the process should not
error out).
drop_fields
drop_fields(paths, transformation_ctx="", info="", stageThreshold=0,
totalThreshold=0)
Calls the FlatMap Class (p. 367) transform to remove fields from a DynamicFrame. Returns a new
DynamicFrame with the specified fields dropped.
• paths – A list of strings, each containing the full path to a field node you want to drop.
• transformation_ctx – A unique string that is used to identify state information (optional).
• info – A string to be associated with error reporting for this transformation (optional).
• stageThreshold – The number of errors encountered during this transformation at which the
process should error out (optional: zero by default, indicating that the process should not error out).
• totalThreshold – The number of errors encountered up to and including this transformation at
which the process should error out (optional: zero by default, indicating that the process should not
error out).
341
AWS Glue Developer Guide
PySpark Extensions
filter
filter(f, transformation_ctx="", info="", stageThreshold=0,
totalThreshold=0)
Returns a new DynamicFrame built by selecting all DynamicRecords within the input DynamicFrame
that satisfy the specified predicate function f.
• f – The predicate function to apply to the DynamicFrame. The function must take a DynamicRecord
as an argument and return True if the DynamicRecord meets the filter requirements, or False if not
(required).
For an example of how to use the filter transform, see Filter Class (p. 364).
join
join(paths1, paths2, frame2, transformation_ctx="", info="",
stageThreshold=0, totalThreshold=0)
Performs an equality join with another DynamicFrame and returns the resulting DynamicFrame.
map
map(f, transformation_ctx="", info="", stageThreshold=0,
totalThreshold=0)
Returns a new DynamicFrame that results from applying the specified mapping function to all records in
the original DynamicFrame.
• f – The mapping function to apply to all records in the DynamicFrame. The function must take a
DynamicRecord as an argument and return a new DynamicRecord (required).
342
AWS Glue Developer Guide
PySpark Extensions
For an example of how to use the map transform, see Map Class (p. 369).
relationalize
relationalize(root_table_name, staging_path, options,
transformation_ctx="", info="", stageThreshold=0, totalThreshold=0)
Relationalizes a DynamicFrame by producing a list of frames that are generated by unnesting nested
columns and pivoting array columns. The pivoted array column can be joined to the root table using the
joinkey generated during the unnest phase.
rename_field
rename_field(oldName, newName, transformation_ctx="", info="",
stageThreshold=0, totalThreshold=0)
Renames a field in this DynamicFrame and returns a new DynamicFrame with the field renamed.
If the old name has dots in it, RenameField will not work unless you place back-ticks around it (`). For
example, to replace this.old.name with thisNewName, you would call rename_field as follows:
343
AWS Glue Developer Guide
PySpark Extensions
resolveChoice
resolveChoice(specs = None, option="", transformation_ctx="", info="",
stageThreshold=0, totalThreshold=0)
Resolves a choice type within this DynamicFrame and returns the new DynamicFrame.
• specs – A list of specific ambiguities to resolve, each in the form of a tuple: (path, action).
The path value identifies a specific ambiguous element, and the action value identifies the
corresponding resolution. Only one of the specs and option parameters can be used. If the spec
parameter is not None, then the option parameter must be an empty string. Conversely if the
option is not an empty string, then the spec parameter must be None. If neither parameter is
provided, AWS Glue tries to parse the schema and use it to resolve ambiguities.
The action portion of a specs tuple can specify one of four resolution strategies:
• cast: Allows you to specify a type to cast to (for example, cast:int).
• make_cols: Resolves a potential ambiguity by flattening the data. For example, if columnA could
be an int or a string, the resolution would be to produce two columns named columnA_int and
columnA_string in the resulting DynamicFrame.
• make_struct: Resolves a potential ambiguity by using a struct to represent the data. For example,
if data in a column could be an int or a string, using the make_struct action produces a column
of structures in the resulting DynamicFrame that each contains both an int and a string.
• project: Resolves a potential ambiguity by projecting all the data to one of the possible data
types. For example, if data in a column could be an int or a string, using a project:string
action produces a column in the resulting DynamicFrame where all the int values have been
converted to strings.
If the path identifies an array, place empty square brackets after the name of the array to avoid
ambiguity. For example, suppose you are working with data structured as follows:
"myList": [
{ "price": 100.00 },
{ "price": "$100.00" }
]
You can select the numeric rather than the string version of the price by setting the path to
"myList[].price", and the action to "cast:double".
• option – The default resolution action if the specs parameter is None. If the specs parameter is not
None, then this must not be set to anything but an empty string.
• transformation_ctx – A unique string that is used to identify state information (optional).
• info – A string to be associated with error reporting for this transformation (optional).
• stageThreshold – The number of errors encountered during this transformation at which the
process should error out (optional: zero by default, indicating that the process should not error out).
• totalThreshold – The number of errors encountered up to and including this transformation at
which the process should error out (optional: zero by default, indicating that the process should not
error out).
Example
344
AWS Glue Developer Guide
PySpark Extensions
select_fields
select_fields(paths, transformation_ctx="", info="", stageThreshold=0,
totalThreshold=0)
• paths – A list of strings, each of which is a path to a top-level node that you want to select.
• transformation_ctx – A unique string that is used to identify state information (optional).
• info – A string to be associated with error reporting for this transformation (optional).
• stageThreshold – The number of errors encountered during this transformation at which the
process should error out (optional: zero by default, indicating that the process should not error out).
• totalThreshold – The number of errors encountered up to and including this transformation at
which the process should error out (optional: zero by default, indicating that the process should not
error out).
spigot
spigot(path, options={})
Writes sample records to a specified destination during a transformation, and returns the input
DynamicFrame with an additional write step.
split_fields
split_fields(paths, name1, name2, transformation_ctx="", info="",
stageThreshold=0, totalThreshold=0)
Returns a new DynamicFrameCollection that contains two DynamicFrames: the first containing all
the nodes that have been split off, and the second containing the nodes that remain.
• paths – A list of strings, each of which is a full path to a node that you want to split into a new
DynamicFrame.
• name1 – A name string for the DynamicFrame that is split off.
• name2 – A name string for the DynamicFrame that remains after the specified nodes have been split
off.
• transformation_ctx – A unique string that is used to identify state information (optional).
• info – A string to be associated with error reporting for this transformation (optional).
• stageThreshold – The number of errors encountered during this transformation at which the
process should error out (optional: zero by default, indicating that the process should not error out).
• totalThreshold – The number of errors encountered up to and including this transformation at
which the process should error out (optional: zero by default, indicating that the process should not
error out).
345
AWS Glue Developer Guide
PySpark Extensions
split_rows
Splits one or more rows in a DynamicFrame off into a new DynamicFrame.
Returns a new DynamicFrameCollection containing two DynamicFrames: the first containing all the
rows that have been split off and the second containing the rows that remain.
• comparison_dict – A dictionary in which the key is a path to a column and the value is another
dictionary for mapping comparators to values to which the column value are compared. For example,
{"age": {">": 10, "<": 20}} splits off all rows whose value in the age column is greater than
10 and less than 20.
• name1 – A name string for the DynamicFrame that is split off.
• name2 – A name string for the DynamicFrame that remains after the specified nodes have been split
off.
• transformation_ctx – A unique string that is used to identify state information (optional).
• info – A string to be associated with error reporting for this transformation (optional).
• stageThreshold – The number of errors encountered during this transformation at which the
process should error out (optional: zero by default, indicating that the process should not error out).
• totalThreshold – The number of errors encountered up to and including this transformation at
which the process should error out (optional: zero by default, indicating that the process should not
error out).
unbox
unbox(path, format, transformation_ctx="", info="", stageThreshold=0,
totalThreshold=0, **options)
Unboxes a string field in a DynamicFrame and returns a new DynamicFrame containing the unboxed
DynamicRecords.
346
AWS Glue Developer Guide
PySpark Extensions
unnest
Unnests nested objects in a DynamicFrame, making them top-level objects, and returns a new unnested
DynamicFrame.
Unnests nested objects in a DynamicFrame, making them top-level objects, and returns a new unnested
DynamicFrame.
write
write(connection_type, connection_options, format, format_options,
accumulator_size)
Gets a DataSink(object) (p. 338) of the specified connection type from the GlueContext Class (p. 352)
of this DynamicFrame, and uses it to format and write the contents of this DynamicFrame. Returns the
new DynamicFrame formatted and written as specified.
• connection_type – The connection type to use. Valid values include s3, mysql, postgresql,
redshift, sqlserver, and oracle.
• connection_options – The connection option to use (optional). For a connection_type of s3, an
Amazon S3 path is defined.
For JDBC connections, several properties must be defined. Note that the database name must be part
of the URL. It can optionally be included in the connection options.
• format – A format specification (optional). This is used for an Amazon Simple Storage Service
(Amazon S3) or an AWS Glue connection that supports multiple formats. See Format Options for ETL
Inputs and Outputs in AWS Glue (p. 300) for the formats that are supported.
• format_options – Format options for the specified format. See Format Options for ETL Inputs and
Outputs in AWS Glue (p. 300) for the formats that are supported.
• accumulator_size – The accumulable size to use (optional).
347
AWS Glue Developer Guide
PySpark Extensions
— Errors —
• assertErrorThreshold (p. 348)
• errorsAsDynamicFrame (p. 348)
• errorsCount (p. 348)
• stageErrorsCount (p. 348)
assertErrorThreshold
assertErrorThreshold( ) – An assert for errors in the transformations that created this
DynamicFrame. Returns an Exception from the underlying DataFrame.
errorsAsDynamicFrame
errorsAsDynamicFrame( ) – Returns a DynamicFrame that has error records nested inside.
errorsCount
errorsCount( ) – Returns the total number of errors in a DynamicFrame.
stageErrorsCount
stageErrorsCount – Returns the number of errors that occurred in the process of generating this
DynamicFrame.
DynamicFrameCollection Class
A DynamicFrameCollection is a dictionary of DynamicFrame Class (p. 339) objects, in which the
keys are the names of the DynamicFrames and the values are the DynamicFrame objects.
__init__
__init__(dynamic_frames, glue_ctx)
keys
keys( ) – Returns a list of the keys in this collection, which generally consists of the names of the
corresponding DynamicFrame values.
values
values(key) – Returns a list of the DynamicFrame values in this collection.
select
select(key)
Returns the DynamicFrame that corresponds to the specfied key (which is generally the name of the
DynamicFrame).
348
AWS Glue Developer Guide
PySpark Extensions
map
map(callable, transformation_ctx="")
Uses a passed-in function to create and return a new DynamicFrameCollection based on the
DynamicFrames in this collection.
• callable – A function that takes a DynamicFrame and the specified transformation context as
parameters and returns a DynamicFrame.
• transformation_ctx – A transformation context to be used by the callable (optional).
flatmap
flatmap(f, transformation_ctx="")
Uses a passed-in function to create and return a new DynamicFrameCollection based on the
DynamicFrames in this collection.
DynamicFrameWriter Class
Methods
• __init__ (p. 349)
• from_options (p. 349)
• from_catalog (p. 350)
• from_jdbc_conf (p. 350)
__init__
__init__(glue_context)
from_options
from_options(frame, connection_type, connection_options={}, format=None,
format_options={}, transformation_ctx="")
349
AWS Glue Developer Guide
PySpark Extensions
For JDBC connections, several properties must be defined. Note that the database name must be part
of the URL. It can optionally be included in the connection options.
The dbtable property is the name of the JDBC table. For JDBC data stores that support schemas
within a database, specify schema.table-name. If a schema is not provided, then the default "public"
schema is used.
For more information, see Connection Types and Options for ETL in AWS Glue (p. 298).
• format – A format specification (optional). This is used for an Amazon Simple Storage Service
(Amazon S3) or an AWS Glue connection that supports multiple formats. See Format Options for ETL
Inputs and Outputs in AWS Glue (p. 300) for the formats that are supported.
• format_options – Format options for the specified format. See Format Options for ETL Inputs and
Outputs in AWS Glue (p. 300) for the formats that are supported.
• transformation_ctx – A transformation context to use (optional).
from_catalog
from_catalog(frame, name_space, table_name, redshift_tmp_dir="",
transformation_ctx="")
Writes a DynamicFrame using the specified catalog database and table name.
from_jdbc_conf
from_jdbc_conf(frame, catalog_connection, connection_options={},
redshift_tmp_dir = "", transformation_ctx="")
DynamicFrameReader Class
— Methods —
• __init__ (p. 351)
• from_rdd (p. 351)
350
AWS Glue Developer Guide
PySpark Extensions
__init__
__init__(glue_context)
from_rdd
from_rdd(data, name, schema=None, sampleRatio=None)
from_options
from_options(connection_type, connection_options={}, format=None,
format_options={}, transformation_ctx="", push_down_predicate="")
• connection_type – The connection type. Valid values include s3, mysql, postgresql, redshift,
sqlserver, oracle, and dynamodb.
• connection_options – Connection options, such as path and database table (optional). For a
connection_type of s3, Amazon S3 paths are defined in an array.
For JDBC connections, several properties must be defined. Note that the database name must be part
of the URL. It can optionally be included in the connection options.
For a JDBC connection that performs parallel reads, you can set the hashfield option. For example:
For more information, see Reading from JDBC Tables in Parallel (p. 305).
• format – A format specification (optional). This is used for an Amazon Simple Storage Service
(Amazon S3) or an AWS Glue connection that supports multiple formats. See Format Options for ETL
Inputs and Outputs in AWS Glue (p. 300) for the formats that are supported.
• format_options – Format options for the specified format. See Format Options for ETL Inputs and
Outputs in AWS Glue (p. 300) for the formats that are supported.
351
AWS Glue Developer Guide
PySpark Extensions
from_catalog
from_catalog(name_space, table_name, redshift_tmp_dir="",
transformation_ctx="", push_down_predicate="", additional_options={})
Reads a DynamicFrame using the specified catalog namespace and table name.
For more information, see Reading from JDBC Tables in Parallel (p. 305).
GlueContext Class
Wraps the Apache SparkSQL SQLContext object, and thereby provides mechanisms for interacting with
the Apache Spark platform.
Creating
• __init__ (p. 352)
• getSource (p. 352)
• create_dynamic_frame_from_rdd (p. 353)
• create_dynamic_frame_from_catalog (p. 353)
• create_dynamic_frame_from_options (p. 353)
__init__
__init__(sparkContext)
getSource
getSource(connection_type, transformation_ctx = "", **options)
Creates a DataSource object that can be used to read DynamicFrames from external sources.
352
AWS Glue Developer Guide
PySpark Extensions
• connection_type – The connection type to use, such as Amazon S3, Amazon Redshift, and JDBC.
Valid values include s3, mysql, postgresql, redshift, sqlserver, oracle, and dynamodb.
• transformation_ctx – The transformation context to use (optional).
• options – A collection of optional name-value pairs. For more information, see Connection Types and
Options for ETL in AWS Glue (p. 298).
create_dynamic_frame_from_rdd
create_dynamic_frame_from_rdd(data, name, schema=None, sample_ratio=None,
transformation_ctx="")
Returns a DynamicFrame that is created from an Apache Spark Resilient Distributed Dataset (RDD).
create_dynamic_frame_from_catalog
create_dynamic_frame_from_catalog(database, table_name, redshift_tmp_dir,
transformation_ctx = "", push_down_predicate= "", additional_options =
{}, catalog_id = None)
Returns a DynamicFrame that is created using a catalog database and table name.
create_dynamic_frame_from_options
create_dynamic_frame_from_options(connection_type, connection_options={},
format=None, format_options={}, transformation_ctx = "",
push_down_predicate= "")
353
AWS Glue Developer Guide
PySpark Extensions
• connection_type – The connection type, such as Amazon S3, Amazon Redshift, and JDBC. Valid
values include s3, mysql, postgresql, redshift, sqlserver, oracle, and dynamodb.
• connection_options – Connection options, such as paths and database table (optional). For a
connection_type of s3, a list of Amazon S3 paths is defined.
For JDBC connections, several properties must be defined. Note that the database name must be part
of the URL. It can optionally be included in the connection options.
The dbtable property is the name of the JDBC table. For JDBC data stores that support schemas
within a database, specify schema.table-name. If a schema is not provided, then the default "public"
schema is used.
For more information, see Connection Types and Options for ETL in AWS Glue (p. 298).
• format – A format specification (optional). This is used for an Amazon Simple Storage Service
(Amazon S3) or an AWS Glue connection that supports multiple formats. See Format Options for ETL
Inputs and Outputs in AWS Glue (p. 300) for the formats that are supported.
• format_options – Format options for the specified format. See Format Options for ETL Inputs and
Outputs in AWS Glue (p. 300) for the formats that are supported.
• transformation_ctx – The transformation context to use (optional).
• push_down_predicate – Filters partitions without having to list and read all the files in your dataset.
AWS Glue supports predicate pushdown only for Amazon S3 sources; and does not support JDBC
sources. For more information, see Pre-Filtering Using Pushdown Predicates (p. 303).
Writing
• getSink (p. 354)
• write_dynamic_frame_from_options (p. 355)
• write_from_options (p. 355)
• write_dynamic_frame_from_catalog (p. 356)
• write_dynamic_frame_from_jdbc_conf (p. 356)
• write_from_jdbc_conf (p. 357)
getSink
Gets a DataSink object that can be used to write DynamicFrames to external sources. Check the
SparkSQL format first to be sure to get the expected sink.
• connection_type – The connection type to use, such as Amazon S3, Amazon Redshift, and JDBC.
Valid values include s3, mysql, postgresql, redshift, sqlserver, and oracle.
• format – The SparkSQL format to use (optional).
• transformation_ctx – The transformation context to use (optional).
• options – A collection of option name-value pairs.
354
AWS Glue Developer Guide
PySpark Extensions
For example:
write_dynamic_frame_from_options
write_dynamic_frame_from_options(frame, connection_type,
connection_options={}, format=None, format_options={}, transformation_ctx
= "")
Writes and returns a DynamicFrame using the specified connection and format.
For JDBC connections, several properties must be defined. Note that the database name must be part
of the URL. It can optionally be included in the connection options.
The dbtable property is the name of the JDBC table. For JDBC data stores that support schemas
within a database, specify schema.table-name. If a schema is not provided, then the default "public"
schema is used.
For more information, see Connection Types and Options for ETL in AWS Glue (p. 298).
• format – A format specification (optional). This is used for an Amazon Simple Storage Service
(Amazon S3) or an AWS Glue connection that supports multiple formats. See Format Options for ETL
Inputs and Outputs in AWS Glue (p. 300) for the formats that are supported.
• format_options – Format options for the specified format. See Format Options for ETL Inputs and
Outputs in AWS Glue (p. 300) for the formats that are supported.
• transformation_ctx – A transformation context to use (optional).
write_from_options
write_from_options(frame_or_dfc, connection_type, connection_options={},
format={}, format_options={}, transformation_ctx = "")
Writes and returns a DynamicFrame or DynamicFrameCollection that is created with the specified
connection and format information.
355
AWS Glue Developer Guide
PySpark Extensions
For JDBC connections, several properties must be defined. Note that the database name must be part
of the URL. It can optionally be included in the connection options.
The dbtable property is the name of the JDBC table. For JDBC data stores that support schemas
within a database, specify schema.table-name. If a schema is not provided, then the default "public"
schema is used.
For more information, see Connection Types and Options for ETL in AWS Glue (p. 298).
• format – A format specification (optional). This is used for an Amazon Simple Storage Service
(Amazon S3) or an AWS Glue connection that supports multiple formats. See Format Options for ETL
Inputs and Outputs in AWS Glue (p. 300) for the formats that are supported.
• format_options – Format options for the specified format. See Format Options for ETL Inputs and
Outputs in AWS Glue (p. 300) for the formats that are supported.
• transformation_ctx – A transformation context to use (optional).
write_dynamic_frame_from_catalog
write_dynamic_frame_from_catalog(frame, database, table_name,
redshift_tmp_dir, transformation_ctx = "", addtional_options = {},
catalog_id = None)
Writes and returns a DynamicFrame using a catalog database and a table name.
write_dynamic_frame_from_jdbc_conf
write_dynamic_frame_from_jdbc_conf(frame, catalog_connection,
connection_options={}, redshift_tmp_dir = "", transformation_ctx = "",
catalog_id = None)
Writes and returns a DynamicFrame using the specified JDBC connection information.
356
AWS Glue Developer Guide
PySpark Transforms
• catalog_id — The catalog ID (account ID) of the Data Catalog being accessed. When None, the
default account ID of the caller is used.
write_from_jdbc_conf
write_from_jdbc_conf(frame_or_dfc, catalog_connection,
connection_options={}, redshift_tmp_dir = "", transformation_ctx = "",
catalog_id = None)
Extracting
• extract_jdbc_conf (p. 357)
extract_jdbc_conf
extract_jdbc_conf(connection_name, catalog_id = None)
Returns a dict with keys user, password, vendor, and url from the connection object in the Data
Catalog.
357
AWS Glue Developer Guide
PySpark Transforms
The classes all define a __call__ method. They either override the GlueTransform class methods
listed in the following sections, or they are called using the class name by default.
Methods
• apply(cls, *args, **kwargs) (p. 358)
• name(cls) (p. 358)
• describeArgs(cls) (p. 358)
• describeReturn(cls) (p. 359)
• describeTransform(cls) (p. 359)
• describeErrors(cls) (p. 359)
• describe(cls) (p. 359)
name(cls)
Returns the name of the derived transform class.
describeArgs(cls)
• cls – The self class object.
Returns a list of dictionaries, each corresponding to a named argument, in the following format:
[
{
358
AWS Glue Developer Guide
PySpark Transforms
describeReturn(cls)
• cls – The self class object.
Returns a dictionary with information about the return type, in the following format:
{
"type": "(return type)",
"description": "(description of output)"
}
describeTransform(cls)
Returns a string describing the transform.
describeErrors(cls)
• cls – The self class object.
Returns a list of dictionaries, each describing a possible exception thrown by this transform, in the
following format:
[
{
"type": "(type of error)",
"description": "(description of error)"
},
...
]
describe(cls)
• cls – The self class object.
359
AWS Glue Developer Guide
PySpark Transforms
{
"transform" : {
"name" : cls.name( ),
"args" : cls.describeArgs( ),
"returns" : cls.describeReturn( ),
"raises" : cls.describeErrors( ),
"location" : "internal"
}
}
ApplyMapping Class
Applies a mapping in a DynamicFrame.
Methods
• __call__ (p. 360)
• apply (p. 360)
• name (p. 361)
• describeArgs (p. 361)
• describeReturn (p. 361)
• describeTransform (p. 361)
• describeErrors (p. 361)
• describe (p. 361)
If the source column has dots in it, the mapping will not work unless you place back-ticks around
it (``). For example, to map this.old.name (string) to thisNewName (string), you would use the
following tuple:
Returns only the fields of the DynamicFrame specified in the "mapping" tuples.
360
AWS Glue Developer Guide
PySpark Transforms
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
DropFields Class
Drops fields within a DynamicFrame.
Methods
• __call__ (p. 361)
• apply (p. 362)
• name (p. 362)
• describeArgs (p. 362)
• describeReturn (p. 362)
• describeTransform (p. 362)
• describeErrors (p. 362)
• describe (p. 362)
361
AWS Glue Developer Guide
PySpark Transforms
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
DropNullFields Class
Drops all null fields in a DynamicFrame whose type is NullType. These are fields with missing or null
values in every record in the DynamicFrame data set.
Methods
• __call__ (p. 362)
• apply (p. 363)
• name (p. 363)
• describeArgs (p. 363)
• describeReturn (p. 363)
• describeTransform (p. 363)
• describeErrors (p. 363)
• describe (p. 363)
362
AWS Glue Developer Guide
PySpark Transforms
name(cls)
• cls – cls
describeArgs(cls)
• cls – cls
describeReturn(cls)
• cls – cls
describeTransform(cls)
• cls – cls
describeErrors(cls)
• cls – cls
describe(cls)
• cls – cls
ErrorsAsDynamicFrame Class
Returns a DynamicFrame that contains nested error records leading up to the creation of the source
DynamicFrame.
Methods
• __call__ (p. 364)
• apply (p. 364)
• name (p. 364)
• describeArgs (p. 364)
• describeReturn (p. 364)
• describeTransform (p. 364)
363
AWS Glue Developer Guide
PySpark Transforms
__call__(frame)
Returns a DynamicFrame that contains nested error records relating to the source DynamicFrame.
name(cls)
• cls – cls
describeArgs(cls)
• cls – cls
describeReturn(cls)
• cls – cls
describeTransform(cls)
• cls – cls
describeErrors(cls)
• cls – cls
describe(cls)
• cls – cls
Filter Class
Builds a new DynamicFrame by selecting records from the input DynamicFrame that satisfy a specified
predicate function.
Methods
• __call__ (p. 365)
• apply (p. 365)
• name (p. 365)
• describeArgs (p. 365)
• describeReturn (p. 365)
364
AWS Glue Developer Guide
PySpark Transforms
• frame – The source DynamicFrame to apply the specified filter function to (required).
• f – The predicate function to apply to each DynamicRecord in the DynamicFrame. The function
must take a DynamicRecord as its argument and return True if the DynamicRecord meets the filter
requirements, or False if it does not (required).
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
365
AWS Glue Developer Guide
PySpark Transforms
After downloading the sample data, we modified it to introduce a couple of erroneous records at
the end of the file. This modified file is located in a public Amazon S3 bucket at s3://awsglue-
datasets/examples/medicare/Medicare_Hospital_Provider.csv. For another example
that uses this dataset, see Code Example: Data Preparation Using ResolveChoice, Lambda, and
ApplyMapping (p. 328).
%pyspark
from awsglue.context import GlueContext
from awsglue.transforms import *
from pyspark.context import SparkContext
glueContext = GlueContext(SparkContext.getOrCreate())
dyF = glueContext.create_dynamic_frame.from_options(
's3',
{'paths': ['s3://awsglue-datasets/examples/medicare/
Medicare_Hospital_Provider.csv']},
'csv',
{'withHeader': True})
Next, use the Filter transform to condense the dataset, retaining only those entries that are from
Sacramento, California, or from Montgomery, Alabama. The filter transform works with any filter
function that takes a DynamicRecord as input and returns True if the DynamicRecord meets the filter
requirements, or False if not.
Note
You can use Python’s dot notation to access many fields in a DynamicRecord. For example, you
can access the column_A field in dynamic_record_X as: dynamic_record_X.column_A.
However, this technique doesn't work with field names that contain anything besides
alphanumeric characters and underscores. For fields that contain other characters, such as
spaces or periods, you must fall back to Python's dictionary notation. For example, to access a
field named col-B, use: dynamic_record_X["col-B"].
366
AWS Glue Developer Guide
PySpark Transforms
You can use a simple Lambda function with the Filter transform to remove all DynamicRecords that
don't originate in Sacramento or Montgomery. To confirm that this worked, print out the number of
records that remain:
FlatMap Class
Applies a transform to each DynamicFrame in a collection and flattens the results.
Methods
• __call__ (p. 367)
• apply (p. 367)
• name (p. 367)
• describeArgs (p. 367)
• describeReturn (p. 368)
• describeTransform (p. 368)
• describeErrors (p. 368)
• describe (p. 368)
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
367
AWS Glue Developer Guide
PySpark Transforms
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
Join Class
Performs an equality join on two DynamicFrames.
Methods
• __call__ (p. 368)
• apply (p. 368)
• name (p. 368)
• describeArgs (p. 369)
• describeReturn (p. 369)
• describeTransform (p. 369)
• describeErrors (p. 369)
• describe (p. 369)
name(cls)
Inherited from GlueTransform name (p. 358)
368
AWS Glue Developer Guide
PySpark Transforms
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358)
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359)
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359)
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359)
describe(cls)
Inherited from GlueTransform describe (p. 359)
Map Class
Builds a new DynamicFrame by applying a function to all records in the input DynamicFrame.
Methods
• __call__ (p. 369)
• apply (p. 370)
• name (p. 370)
• describeArgs (p. 370)
• describeReturn (p. 370)
• describeTransform (p. 370)
• describeErrors (p. 370)
• describe (p. 370)
• Example Code (p. 370)
• frame – The original DynamicFrame to which to apply the mapping function (required).
• f – The function to apply to all DynamicRecords in the DynamicFrame. The function must take
a DynamicRecord as an argument and return a new DynamicRecord produced by the mapping
(required).
369
AWS Glue Developer Guide
PySpark Transforms
• stageThreshold – The maximum number of errors that can occur in the transformation before it
errors out (optional; the default is zero).
• totalThreshold – The maximum number of errors that can occur overall before processing errors
out (optional; the default is zero).
Returns a new DynamicFrame that results from applying the specified function to all DynamicRecords
in the original DynamicFrame.
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
After downloading the sample data, we modified it to introduce a couple of erroneous records at
the end of the file. This modified file is located in a public Amazon S3 bucket at s3://awsglue-
datasets/examples/medicare/Medicare_Hospital_Provider.csv. For another example
that uses this dataset, see Code Example: Data Preparation Using ResolveChoice, Lambda, and
ApplyMapping (p. 328).
glueContext = GlueContext(SparkContext.getOrCreate())
370
AWS Glue Developer Guide
PySpark Transforms
dyF = glueContext.create_dynamic_frame.from_options(
's3',
{'paths': ['s3://awsglue-datasets/examples/medicare/
Medicare_Hospital_Provider.csv']},
'csv',
{'withHeader': True})
Next, create a mapping function to merge provider-address fields in a DynamicRecord into a struct,
and then delete the individual address fields:
def MergeAddress(rec):
rec["Address"] = {}
rec["Address"]["Street"] = rec["Provider Street Address"]
rec["Address"]["City"] = rec["Provider City"]
rec["Address"]["State"] = rec["Provider State"]
rec["Address"]["Zip.Code"] = rec["Provider Zip Code"]
rec["Address"]["Array"] = [rec["Provider Street Address"], rec["Provider City"],
rec["Provider State"], rec["Provider Zip Code"]]
del rec["Provider Street Address"]
del rec["Provider City"]
del rec["Provider State"]
del rec["Provider Zip Code"]
return rec
In this mapping function, the line rec["Address"] = {} creates a dictionary in the input
DynamicRecord that contains the new structure.
Note
Python map fields are not supported here. For example, you can't have a line like the following:
rec["Addresses"] = [] # ILLEGAL!
The lines that are like rec["Address"]["Street"] = rec["Provider Street Address"] add
fields to the new structure using Python dictionary syntax.
After the address lines are added to the new structure, the lines that are like del rec["Provider
Street Address"] remove the individual fields from the DynamicRecord.
Now you can use the Map transform to apply your mapping function to all DynamicRecords in the
DynamicFrame.
371
AWS Glue Developer Guide
PySpark Transforms
root
|-- Average Total Payments: string
|-- Average Covered Charges: string
|-- DRG Definition: string
|-- Average Medicare Payments: string
|-- Hospital Referral Region Description: string
|-- Address: struct
| |-- Zip.Code: string
| |-- City: string
| |-- Array: array
| | |-- element: string
| |-- State: string
| |-- Street: string
|-- Provider Id: string
|-- Total Discharges: string
|-- Provider Name: string
MapToCollection Class
Applies a transform to each DynamicFrame in the specified DynamicFrameCollection.
Methods
• __call__ (p. 372)
• apply (p. 372)
• name (p. 373)
• describeArgs (p. 373)
• describeReturn (p. 373)
• describeTransform (p. 373)
• describeErrors (p. 373)
• describe (p. 373)
• dfc – The DynamicFrameCollection over which to apply the transform function (required).
• callable – A callable transform function to apply to each member of the collection (required).
• transformation_ctx – A unique string that is used to identify state information (optional).
372
AWS Glue Developer Guide
PySpark Transforms
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
Relationalize Class
Flattens nested schema in a DynamicFrame and pivots out array columns from the flattened frame.
Methods
• __call__ (p. 373)
• apply (p. 374)
• name (p. 374)
• describeArgs (p. 374)
• describeReturn (p. 374)
• describeTransform (p. 374)
• describeErrors (p. 374)
• describe (p. 374)
373
AWS Glue Developer Guide
PySpark Transforms
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
RenameField Class
Renames a node within a DynamicFrame.
Methods
• __call__ (p. 375)
• apply (p. 375)
• name (p. 375)
• describeArgs (p. 375)
• describeReturn (p. 375)
• describeTransform (p. 375)
• describeErrors (p. 375)
• describe (p. 375)
374
AWS Glue Developer Guide
PySpark Transforms
If the old name has dots in it, RenameField will not work unless you place back-ticks around it (``). For
example, to replace this.old.name with thisNewName, you would call RenameField as follows:
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
ResolveChoice Class
Resolves a choice type within a DynamicFrame.
375
AWS Glue Developer Guide
PySpark Transforms
Methods
• __call__ (p. 376)
• apply (p. 377)
• name (p. 377)
• describeArgs (p. 377)
• describeReturn (p. 377)
• describeTransform (p. 377)
• describeErrors (p. 377)
• describe (p. 377)
The action portion of a specs tuple can specify one of four resolution strategies:
• cast: Allows you to specify a type to cast to (for example, cast:int).
• make_cols: Resolves a potential ambiguity by flattening the data. For example, if columnA
could be an int or a string, the resolution is to produce two columns named columnA_int and
columnA_string in the resulting DynamicFrame.
• make_struct: Resolves a potential ambiguity by using a struct to represent the data. For example,
if data in a column could be an int or a string, using the make_struct action produces a column
of structures in the resulting DynamicFrame with each containing both an int and a string.
• project: Resolves a potential ambiguity by retaining only values of a specified type in the resulting
DynamicFrame. For example, if data in a ChoiceType column could be an int or a string,
specifying a project:string action drops columns from the resulting DynamicFrame which are
not type string.
If the path identifies an array, place empty square brackets after the name of the array to avoid
ambiguity. For example, suppose you are working with data structured as follows:
"myList": [
{ "price": 100.00 },
{ "price": "$100.00" }
]
You can select the numeric rather than the string version of the price by setting the path to
"myList[].price", and the action to "cast:double".
• choice – The default resolution action if the specs parameter is None. If the specs parameter is not
None, then this must not be set to anything but an empty string.
• transformation_ctx – A unique string that is used to identify state information (optional).
• info – A string associated with errors in the transformation (optional).
376
AWS Glue Developer Guide
PySpark Transforms
• stageThreshold – The maximum number of errors that can occur in the transformation before it
errors out (optional; the default is zero).
• totalThreshold – The maximum number of errors that can occur overall before processing errors
out (optional; the default is zero).
Example
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
SelectFields Class
Gets fields in a DynamicFrame.
Methods
• __call__ (p. 378)
• apply (p. 378)
• name (p. 378)
• describeArgs (p. 378)
• describeReturn (p. 378)
• describeTransform (p. 378)
• describeErrors (p. 378)
377
AWS Glue Developer Guide
PySpark Transforms
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
SelectFromCollection Class
Selects one DynamicFrame in a DynamicFrameCollection.
Methods
• __call__ (p. 379)
378
AWS Glue Developer Guide
PySpark Transforms
• dfc – The DynamicFrameCollection from which the DynamicFrame should be selected (required).
• key – The key of the DynamicFrame to select (required).
• transformation_ctx – A unique string that is used to identify state information (optional).
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
Spigot Class
Writes sample records to a specified destination during a transformation.
Methods
• __call__ (p. 380)
379
AWS Glue Developer Guide
PySpark Transforms
name(cls)
Inherited from GlueTransform name (p. 358)
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358)
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359)
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359)
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359)
describe(cls)
Inherited from GlueTransform describe (p. 359)
SplitFields Class
Splits a DynamicFrame into two new ones, by specified fields.
380
AWS Glue Developer Guide
PySpark Transforms
Methods
• __call__ (p. 381)
• apply (p. 381)
• name (p. 381)
• describeArgs (p. 381)
• describeReturn (p. 381)
• describeTransform (p. 381)
• describeErrors (p. 382)
• describe (p. 382)
• frame – The source DynamicFrame to split into two new ones (required).
• paths – A list of full paths to the fields to be split (required).
• name1 – The name to assign to the DynamicFrame that will contain the fields to be split off
(optional). If no name is supplied, the name of the source frame is used with "1" appended.
• name2 – The name to assign to the DynamicFrame that will contain the fields that remain after the
specified fields are split off (optional). If no name is provided, the name of the source frame is used
with "2" appended.
• transformation_ctx – A unique string that is used to identify state information (optional).
• info – A string associated with errors in the transformation (optional).
• stageThreshold – The maximum number of errors that can occur in the transformation before it
errors out (optional; the default is zero).
• totalThreshold – The maximum number of errors that can occur overall before processing errors
out (optional; the default is zero).
Returns a DynamicFrameCollection containing two DynamicFrames: one contains only the specified
fields to split off, and the other contains the remaining fields.
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
381
AWS Glue Developer Guide
PySpark Transforms
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
SplitRows Class
Splits a DynamicFrame in two by specified rows.
Methods
• __call__ (p. 382)
• apply (p. 382)
• name (p. 382)
• describeArgs (p. 383)
• describeReturn (p. 383)
• describeTransform (p. 383)
• describeErrors (p. 383)
• describe (p. 383)
• frame – The source DynamicFrame to split into two new ones (required).
• comparison_dict – A dictionary where the key is the full path to a column, and the value is another
dictionary mapping comparators to the value to which the column values are compared. For example,
{"age": {">": 10, "<": 20}} splits rows where the value of "age" is between 10 and 20,
exclusive, from rows where "age" is outside that range (required).
• name1 – The name to assign to the DynamicFrame that will contain the rows to be split off (optional).
• name2 – The name to assign to the DynamicFrame that will contain the rows that remain after the
specified rows are split off (optional).
• transformation_ctx – A unique string that is used to identify state information (optional).
• info – A string associated with errors in the transformation (optional).
• stageThreshold – The maximum number of errors that can occur in the transformation before it
errors out (optional; the default is zero).
• totalThreshold – The maximum number of errors that can occur overall before processing errors
out (optional; the default is zero).
Returns a DynamicFrameCollection that contains two DynamicFrames: one contains only the
specified rows to be split, and the other contains all remaining rows.
name(cls)
Inherited from GlueTransform name (p. 358).
382
AWS Glue Developer Guide
PySpark Transforms
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
Unbox Class
Unboxes a string field in a DynamicFrame.
Methods
• __call__ (p. 383)
• apply (p. 384)
• name (p. 384)
• describeArgs (p. 384)
• describeReturn (p. 384)
• describeTransform (p. 384)
• describeErrors (p. 384)
• describe (p. 384)
383
AWS Glue Developer Guide
PySpark Transforms
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
UnnestFrame Class
Unnests a DynamicFrame, flattens nested objects to top-level elements, and generates joinkeys for
array objects.
Methods
• __call__ (p. 385)
• apply (p. 385)
• name (p. 385)
• describeArgs (p. 385)
• describeReturn (p. 385)
• describeTransform (p. 385)
• describeErrors (p. 385)
• describe (p. 385)
384
AWS Glue Developer Guide
ETL Programming in Scala
name(cls)
Inherited from GlueTransform name (p. 358).
describeArgs(cls)
Inherited from GlueTransform describeArgs (p. 358).
describeReturn(cls)
Inherited from GlueTransform describeReturn (p. 359).
describeTransform(cls)
Inherited from GlueTransform describeTransform (p. 359).
describeErrors(cls)
Inherited from GlueTransform describeErrors (p. 359).
describe(cls)
Inherited from GlueTransform describe (p. 359).
AWS Glue supports an extension of the PySpark Scala dialect for scripting extract, transform, and load
(ETL) jobs. The following sections describe how to use the AWS Glue Scala library and the AWS Glue API
in ETL scripts, and provide reference documentation for the library.
Contents
385
AWS Glue Developer Guide
ETL Programming in Scala
To ensure that your program compiles without errors and runs as expected, it's important that you load it
on a development endpoint in a REPL (Read-Eval-Print Loop) or an Apache Zeppelin Notebook and test it
there before running it in a job. Because the compile process occurs on the server, you will not have good
visibility into any problems that happen there.
Next, connect it to an Apache Zeppelin Notebook that is either running locally on your machine or
remotely on an Amazon EC2 notebook server. To install a local version of a Zeppelin Notebook, follow
the instructions in Tutorial: Local Zeppelin Notebook (p. 192).
The only difference between running Scala code and running PySpark code on your Notebook is that you
should start each paragraph on the Notebook with the the following:
%spark
This prevents the Notebook server from defaulting to the PySpark flavor of the Spark interpreter.
390
AWS Glue Developer Guide
Scala API List
com.amazonaws.services.glue
The com.amazonaws.services.glue package in the AWS Glue Scala library contains the following APIs:
com.amazonaws.services.glue.types
The com.amazonaws.services.glue.types package in the AWS Glue Scala library contains the following
APIs:
com.amazonaws.services.glue.util
The com.amazonaws.services.glue.util package in the AWS Glue Scala library contains the following
APIs:
391
AWS Glue Developer Guide
Scala API List
Package: com.amazonaws.services.glue
ChoiceOption Trait
ChoiceOption Object
ChoiceOption
object ChoiceOption
• val CAST
• val MAKE_COLS
• val MAKE_STRUCT
• val MATCH_CATALOG
• val PROJECT
def apply
392
AWS Glue Developer Guide
Scala API List
Package: com.amazonaws.services.glue
The writer analog to a DataSource. DataSink encapsulates a destination and a format that a
DynamicFrame can be written to.
def writeDynamicFrame
def pyWriteDynamicFrame
def supportsFormat
def setFormat
def withFormat
def setAccumulableSize
393
AWS Glue Developer Guide
Scala API List
def getOutputErrorRecordsAccumulable
def errorsAsDynamicFrame
DataSink Object
object DataSink
def recordMetrics
trait DataSource {
Contents
• AWS Glue Scala DynamicFrame Class (p. 395)
• val errorsCount (p. 396)
394
AWS Glue Developer Guide
Scala API List
395
AWS Glue Developer Guide
Scala API List
DynamicFrames are designed to provide a flexible data model for ETL (extract, transform, and load)
operations. They don't require a schema to create, and you can use them to read and transform data
that contains messy or inconsistent values and types. A schema can be computed on demand for those
operations that need one.
DynamicFrames provide a range of transformations for data cleaning and ETL. They also support
conversion to and from SparkSQL DataFrames to integrate with existing code and the many analytics
operations that DataFrames provide.
The following parameters are shared across many of the AWS Glue transformations that construct
DynamicFrames:
val errorsCount
val errorsCount
The number of error records in this DynamicFrame. This includes errors from previous operations.
def applyMapping
396
AWS Glue Developer Guide
Scala API List
Each mapping is made up of a source column and type and a target column and type. Mappings can
be specified as either a four-tuple (source_path, source_type, target_path, target_type) or a
MappingSpec (p. 417) object containing the same information.
In addition to using mappings for simple projections and casting, you can use them to nest or unnest
fields by separating components of the path with '.' (period).
For example, suppose that you have a DynamicFrame with the following schema:
{{{
root
|-- name: string
|-- age: int
|-- address: struct
| |-- state: string
| |-- zip: int
}}}
You can make the following call to unnest the state and zip fields:
{{{
df.applyMapping(
Seq(("name", "string", "name", "string"),
("age", "int", "age", "int"),
("address.state", "string", "state", "string"),
("address.zip", "int", "zip", "int")))
}}}
{{{
root
|-- name: string
|-- age: int
|-- state: string
|-- zip: int
}}}
You can also use applyMapping to re-nest columns. For example, the following inverts the previous
transformation and creates a struct named address in the target:
{{{
df.applyMapping(
Seq(("name", "string", "name", "string"),
("age", "int", "age", "int"),
("state", "string", "address.state", "string"),
("zip", "int", "address.zip", "int")))
}}}
Field names that contain '.' (period) characters can be quoted by using backticks ('').
Note
Currently, you can't use the applyMapping method to map columns that are nested under
arrays.
def assertErrorThreshold
397
AWS Glue Developer Guide
Scala API List
An action that forces computation and verifies that the number of error records falls below
stageThreshold and totalThreshold. Throws an exception if either condition fails.
def count
lazy
def count
def dropField
def dropFields
You can use this method to delete nested columns, including those inside of arrays, but not to drop
specific array elements.
def dropNulls
def errorsAsDynamicFrame
def errorsAsDynamicFrame
Returns a new DynamicFrame containing the error records from this DynamicFrame.
def filter
398
AWS Glue Developer Guide
Scala API List
Constructs a new DynamicFrame containing only those records for which the function 'f' returns true.
The filter function 'f' should not mutate the input record.
def getName
def getNumPartitions
def getNumPartitions
def getSchemaIfComputed
Returns the schema if it has already been computed. Does not scan the data if the schema has not
already been computed.
def isSchemaComputed
Returns true if the schema has been computed for this DynamicFrame, or false if not. If this
method returns false, then calling the schema method requires another pass over the records in this
DynamicFrame.
def javaToPython
def join
Returns the result of performing an equijoin with frame2 using the specified keys.
399
AWS Glue Developer Guide
Scala API List
def map
Returns a new DynamicFrame constructed by applying the specified function 'f' to each record in this
DynamicFrame.
This method copies each record before applying the specified function, so it is safe to mutate the
records. If the mapping function throws an exception on a given record, that record is marked as an error,
and the stack trace is saved as a column in the error record.
def printSchema
def recomputeSchema
Forces a schema recomputation. This requires a scan over the data, but it may "tighten" the schema if
there are some fields in the current schema that are not present in the data.
def relationalize
• rootTableName — The name to use for the base DynamicFrame in the output. DynamicFrames that
are created by pivoting arrays start with this as a prefix.
• stagingPath — The Amazon Simple Storage Service (Amazon S3) path for writing intermediate data.
• options — Relationalize options and configuration. Currently unused.
Flattens all nested structures and pivots arrays into separate tables.
You can use this operation to prepare deeply nested data for ingestion into a relational database. Nested
structs are flattened in the same manner as the unnest (p. 406) transform. Additionally, arrays are
pivoted into separate tables with each array element becoming a row. For example, suppose that you
have a DynamicFrame with the following data:
400
AWS Glue Developer Guide
Scala API List
{{{
df.relationalize("people", "s3:/my_bucket/my_path", JsonOptions.empty)
}}}
This produces two tables. The first table is named "people" and contains the following:
{{{
{"name": "Nancy", "age": 47, "friends": 1}
{"name": "Stephanie", "age": 28, "friends": 2}
{"name": "Nathan", "age": 54, "friends": 3)
}}}
Here, the friends array has been replaced with an auto-generated join key. A separate table named
people.friends is created with the following content:
{{{
{"id": 1, "index": 0, "val": "Fred"}
{"id": 1, "index": 1, "val": "Lakshmi"}
{"id": 2, "index": 0, "val": "Yao"}
{"id": 2, "index": 1, "val": "Phil"}
{"id": 2, "index": 2, "val": "Alvin"}
{"id": 3, "index": 0, "val": "Nicolai"}
{"id": 3, "index": 1, "val": "Karen"}
}}}
In this table, 'id' is a join key that identifies which record the array element came from, 'index' refers to
the position in the original array, and 'val' is the actual array entry.
The relationalize method returns the sequence of DynamicFrames created by applying this process
recursively to all arrays.
Note
The AWS Glue library automatically generates join keys for new tables. To ensure that join keys
are unique across job runs, you must enable job bookmarks.
def renameField
You can use this method to rename nested fields. For example, the following code would rename state
to state_code inside the address struct:
{{{
401
AWS Glue Developer Guide
Scala API List
df.renameField("address.state", "address.state_code")
}}}
def repartition
def resolveChoice
• choiceOption — An action to apply to all ChoiceType columns not listed in the specs sequence.
• database — The Data Catalog database to use with the match_catalog action.
• tableName — The Data Catalog table to use with the match_catalog action.
Returns a new DynamicFrame by replacing one or more ChoiceTypes with a more specific type.
There are two ways to use resolveChoice. The first is to specify a sequence of specific columns and
how to resolve them. These are specified as tuples made up of (column, action) pairs.
The other mode for resolveChoice is to specify a single resolution for all ChoiceTypes. You can use
this in cases where the complete list of ChoiceTypes is unknown before execution. In addition to the
actions listed preceding, this mode also supports the following action:
Examples:
Resolve the user.id column by casting to an int, and make the address field retain only structs:
{{{
df.resolveChoice(specs = Seq(("user.id", "cast:int"), ("address", "project:struct")))
402
AWS Glue Developer Guide
Scala API List
}}}
{{{
df.resolveChoice(choiceOption = Some(ChoiceOption("make_cols")))
}}}
Resolve all ChoiceTypes by casting to the types in the specified catalog table:
{{{
df.resolveChoice(choiceOption = Some(ChoiceOption("match_catalog")),
database = Some("my_database"),
tableName = Some("my_table"))
}}}
def schema
The returned schema is guaranteed to contain every field that is present in a record in this
DynamicFrame. But in a small number of cases, it might also contain additional fields. You can use the
unnest (p. 406) method to "tighten" the schema based on the records in this DynamicFrame.
def selectField
def selectFields
def show
403
AWS Glue Developer Guide
Scala API List
def spigot
Passthrough transformation that returns the same records but writes out a subset of records as a side
effect.
By default, writes 100 arbitrary records to the location specified by path. You can customize this
behavior by using the options map. Valid keys include the following:
• topk — Specifies the total number of records written out. The default is 100.
• prob — Specifies the probability (as a decimal) that an individual record is included. Default is 1.
For example, the following call would sample the dataset by selecting each record with a 20 percent
probability and stopping after 200 records have been written:
{{{
df.spigot("s3://my_bucket/my_path", JsonOptions(Map("topk" -> 200, "prob" -> 0.2)))
}}}
def splitFields
Returns a sequence of two DynamicFrames. The first DynamicFrame contains the specified paths, and
the second contains all other columns.
def splitRows
404
AWS Glue Developer Guide
Scala API List
callSite : CallSite,
stageThreshold : Long,
totalThreshold : Long
) : Seq[DynamicFrame]
Returns a sequence of two DynamicFrames. The first contains rows for which the predicate is true and
the second contains those for which it is false.
Predicates are specified using three sequences: 'paths' contains the (possibly nested) column names,
'values' contains the constant values to compare to, and 'operators' contains the operators to use for
comparison. All three sequences must be the same length: The nth operator is used to compare the nth
column with the nth value.
Each operator must be one of "!=", "=", "<=", "<", ">=", or ">".
As an example, the following call would split a DynamicFrame so that the first output frame would
contain records of people over 65 from the United States, and the second would contain all other
records:
{{{
df.splitRows(Seq("age", "address.country"), Seq(65, "USA"), Seq(">=", "="))
}}}
def stageErrorsCount
def stageErrorsCount
Returns the number of error records created while computing this DynamicFrame. This excludes errors
from previous operations that were passed into this DynamicFrame as input.
def toDF
Converts this DynamicFrame to an Apache Spark SQL DataFrame with the same schema and records.
Note
Because DataFrames don't support ChoiceTypes, this method automatically converts
ChoiceType columns into StructTypes. For more information and options for resolving
choice, see resolveChoice (p. 402).
def unbox
405
AWS Glue Developer Guide
Scala API List
) : DynamicFrame
Parses an embedded string or binary column according to the specified format. Parsed columns are
nested under a struct with the original column name.
For example, suppose that you have a CSV file with an embedded JSON column:
After an initial parse, you would get a DynamicFrame with the following schema:
{{{
root
|-- name: string
|-- age: int
|-- address: string
}}}
You can call unbox on the address column to parse the specific components:
{{{
df.unbox("address", "json")
}}}
{{{
root
|-- name: string
|-- age: int
|-- address: struct
| |-- state: string
| |-- city: string
}}}
def unnest
Returns a new DynamicFrame with all nested structures flattened. Names are constructed using the
'.' (period) character.
For example, suppose that you have a DynamicFrame with the following schema:
{{{
406
AWS Glue Developer Guide
Scala API List
root
|-- name: string
|-- age: int
|-- address: struct
| |-- state: string
| |-- city: string
}}}
{{{
df.unnest()
}}}
{{{
root
|-- name: string
|-- age: int
|-- address.state: string
|-- address.city: string
}}}
This method also unnests nested structs inside of arrays. But for historical reasons, the names of such
fields are prepended with the name of the enclosing array and ".val".
def withFrameSchema
• getSchema — A function that returns the schema to use. Specified as a zero-parameter function to
defer potentially expensive computation.
Sets the schema of this DynamicFrame to the specified value. This is primarily used internally to avoid
costly schema recomputation. The passed-in schema must contain all columns present in the data.
def withName
def withTransformationContext
407
AWS Glue Developer Guide
Scala API List
object DynamicFrame
def apply
def emptyDynamicFrame
def fromPythonRDD
def ignoreErrors
def inlineErrors
def newFrameWithErrors
408
AWS Glue Developer Guide
Scala API List
Package: com.amazonaws.services.glue
A DynamicRecord is a self-describing data structure that represents a row of data in the dataset that
is being processed. It is self-describing in the sense that you can get the schema of the row that is
represented by the DynamicRecord by inspecting the record itself. A DynamicRecord is similar to a
Row in Apache Spark.
def addField
def dropField
Drops a DynamicNode (p. 423) from the specified path and returns the dropped node if there is not an
array in the specified path.
def setError
409
AWS Glue Developer Guide
Scala API List
Returns a DynamicRecord.
def isError
def isError
def getError
def getError
Gets the Error if the record is an error record. Returns scala.Some Some (Error) if this record is an
error record, or otherwise scala.None .
def clearError
def clearError
def write
def readFields
def clone
def schema
def schema
def getRoot
def toJson
410
AWS Glue Developer Guide
Scala API List
def getFieldNode
Returns scala.Some Some (DynamicNode (p. 423)) if the field exists, or otherwise
scala.None.None .
def getField
def hashCode
def equals
DynamicRecord Object
object DynamicRecord
def apply
Apply method to convert an Apache Spark SQL Row to a DynamicRecord (p. 408).
Returns a DynamicRecord.
RecordTraverser Trait
trait RecordTraverser {
def nullValue(): Unit
def byteValue(value: Byte): Unit
def binaryValue(value: Array[Byte]): Unit
def booleanValue(value: Boolean): Unit
def shortValue(value: Short) : Unit
411
AWS Glue Developer Guide
Scala API List
GlueContext is the entry point for reading and writing a DynamicFrame (p. 394) from and to Amazon
Simple Storage Service (Amazon S3), the AWS Glue Data Catalog, JDBC, and so on. This class provides
utility functions to create DataSource trait (p. 394) and DataSink (p. 392) objects that can in turn be
used to read and write DynamicFrames.
You can also use GlueContext to set a target number of partitions (default 20) in the DynamicFrame if
the number of partitions created from the source is less than a minimum threshold for partitions (default
10).
def getCatalogSink
Creates a DataSink (p. 392) that writes to a location specified in a table that is defined in the Data
Catalog.
412
AWS Glue Developer Guide
Scala API List
def getCatalogSource
Creates a DataSource trait (p. 394) that reads data from a table definition in the Data Catalog.
def getJDBCSink
Creates a DataSink (p. 392) that writes to a JDBC database that is specified in a Connection object in
the Data Catalog. The Connection object has information to connect to a JDBC sink, including the URL,
user name, password, VPC, subnet, and security groups.
• catalogConnection — The name of the connection in the Data Catalog that contains the JDBC URL
to write to.
• options — A string of JSON name-value pairs that provide additional information that is required to
write to a JDBC data store. This includes:
• dbtable (required) — The name of the JDBC table. For JDBC data stores that support schemas within
a database, specify schema.table-name. If a schema is not provided, then the default "public"
schema is used. The following example shows an options parameter that points to a schema named
test and a table named test_table in database test_db.
413
AWS Glue Developer Guide
Scala API List
• Any additional options passed directly to the SparkSQL JDBC writer. For more information, see
Redshift data source for Spark.
• redshiftTmpDir — A temporary staging directory to be used with certain data sinks. Set to empty
by default.
• transformationContext — The transformation context that is associated with the sink to be used
by job bookmarks. Set to empty by default.
• catalogId — The catalog ID (account ID) of the Data Catalog being accessed. When null, the default
account ID of the caller is used.
Example code:
def getSink
Creates a DataSink (p. 392) that writes data to a destination like Amazon Simple Storage Service
(Amazon S3), JDBC, or the AWS Glue Data Catalog.
def getSinkWithFormat
Creates a DataSink (p. 392) that writes data to a destination like Amazon S3, JDBC, or the Data Catalog,
and also sets the format for the data to be written out to the destination.
• connectionType — The type of the connection. Refer to DataSink (p. 392) for a list of supported
connection types.
• options — A string of JSON name-value pairs that provide additional information to establish a
connection with the data sink.
• transformationContext — The transformation context that is associated with the sink to be used
by job bookmarks. Set to empty by default.
414
AWS Glue Developer Guide
Scala API List
def getSource
Creates a DataSource trait (p. 394) that reads data from a source like Amazon S3, JDBC, or the AWS
Glue Data Catalog.
• connectionType — The type of the data source. Can be one of “s3”, “mysql”, “redshift”, “oracle”,
“sqlserver”, “postgresql”, "dynamodb", “parquet”, or “orc”.
• connectionOptions — A string of JSON name-value pairs that provide additional information for
establishing a connection with the data source.
• connectionOptions when the connectionType is "s3":
• paths (required) — List of Amazon S3 paths to read.
• compressionType (optional) — Compression type of the data. This is generally not required if the
data has a standard file extension. Possible values are “gzip” and “bzip”.
• exclusions (optional) — A string containing a JSON list of glob patterns to exclude. For example
"[\"**.pdf\"]" excludes all PDF files.
• maxBand (optional) — This advanced option controls the duration in seconds after which AWS
Glue expects an Amazon S3 listing to be consistent. Files with modification timestamps falling
within the last maxBand seconds are tracked when using job bookmarks to account for Amazon S3
eventual consistency. It is rare to set this option. The default is 900 seconds.
• maxFilesInBand (optional) — This advanced option specifies the maximum number of files to save
from the last maxBand seconds. If this number is exceeded, extra files are skipped and processed
only in the next job run.
• groupFiles (optional) — Grouping files is enabled by default when the input contains more than
50,000 files. To disable grouping with fewer than 50,000 files, set this parameter to “inPartition”.
To disable grouping when there are more than 50,000 files, set this parameter to “none”.
• groupSize (optional) — The target group size in bytes. The default is computed based on the input
data size and the size of your cluster. When there are fewer than 50,000 input files, groupFiles
must be set to “inPartition” for this option to take effect.
• recurse (optional) — If set to true, recursively read files in any subdirectory of the specified paths.
• connectionOptions when the connectionType is "dynamodb":
• dynamodb.input.tableName (required) — The DynamoDB table from which to read.
• dynamodb.throughput.read.percent (optional) — The percentage of reserved capacity units (RCU)
to use. The default is set to "0.5". Acceptable values are from "0.1" to "1.5", inclusive.
• connectionOptions when the connectionType is "parquet" or "orc":
• paths (required) — List of Amazon S3 paths to read.
• Any additional options are passed directly to the SparkSQL DataSource. For more information, see
Redshift data source for Spark.
• connectionOptions when the connectionType is "redshift":
• url (required) — The JDBC URL for an Amazon Redshift database.
• dbtable (required) — The Amazon Redshift table to read.
415
AWS Glue Developer Guide
Scala API List
• redshiftTmpDir (required) — The Amazon S3 path where temporary data can be staged when
copying out of Amazon Redshift.
• user (required) — The username to use when connecting to the Amazon Redshift cluster.
• password (required) — The password to use when connecting to the Amazon Redshift cluster.
• transformationContext — The transformation context that is associated with the sink to be used
by job bookmarks. Set to empty by default.
• pushDownPredicate — Predicate on partition columns.
def getSourceWithFormat
Creates a DataSource trait (p. 394) that reads data from a source like Amazon S3, JDBC, or the AWS
Glue Data Catalog, and also sets the format of data stored in the source.
• connectionType — The type of the data source. Can be one of “s3”, “mysql”, “redshift”, “oracle”,
“sqlserver”, “postgresql”, "dynamodb", “parquet”, or “orc”.
• options — A string of JSON name-value pairs that provide additional information for establishing a
connection with the data source.
• transformationContext — The transformation context that is associated with the sink to be used
by job bookmarks. Set to empty by default.
• format — The format of the data that is stored at the source. When the connectionType is "s3", you
can also specify format. Can be one of “avro”, “csv”, “grokLog”, “ion”, “json”, “xml”, “parquet”, or “orc”.
• formatOptions — A string of JSON name-value pairs that provide additional options for parsing
data at the source. See Format Options (p. 300).
def getSparkSession
Gets the SparkSession object associated with this GlueContext. Use this SparkSession object to
register tables and UDFs for use with DataFrame created from DynamicFrames.
def this
Creates a GlueContext object using the specified SparkContext, minimum partitions, and target
partitions.
416
AWS Glue Developer Guide
Scala API List
• sc — The SparkContext.
• minPartitions — The minimum number of partitions.
• targetPartitions — The target number of partitions.
def this
Creates a GlueContext object with the provided SparkContext. Sets the minimum partitions to 10
and target partitions to 20.
• sc — The SparkContext.
def this
Creates a GlueContext object with the provided JavaSparkContext. Sets the minimum partitions to
10 and target partitions to 20.
• sparkContext — The JavaSparkContext.
MappingSpec
Package: com.amazonaws.services.glue
A MappingSpec specifies a mapping from a source path and a source data type to a target path and
a target data type. The value at the source path in the source frame appears in the target frame at the
target path. The source data type is cast to the target data type.
417
AWS Glue Developer Guide
Scala API List
It extends from Product4 so that you can handle any Product4 in your applyMapping interface.
MappingSpec Object
object MappingSpec
val orderingByTarget
def apply
Creates a MappingSpec.
Returns a MappingSpec.
def apply
Creates a MappingSpec.
Returns a MappingSpec.
def apply
Creates a MappingSpec.
418
AWS Glue Developer Guide
Scala API List
• product — The Product4 of the source path, source data type, target path, and target data type.
Returns a MappingSpec.
Package: com.amazonaws.services.glue
ResolveSpec Object
ResolveSpec
object ResolveSpec
def
Creates a ResolveSpec.
def
Creates a ResolveSpec.
Creates a ResolveSpec.
419
AWS Glue Developer Guide
Scala API List
def _1 : String
def _2 : String
def clone
def getValue
def nodeType
def this
420
AWS Glue Developer Guide
Scala API List
node : DynamicNode )
• ordering
def clone
• ordering
421
AWS Glue Developer Guide
Scala API List
• ordering
• ordering
• ordering
422
AWS Glue Developer Guide
Scala API List
• ordering
Package: com.amazonaws.services.glue.types
DynamicNode Class
DynamicNode
423
AWS Glue Developer Guide
Scala API List
DynamicNode Object
DynamicNode
object DynamicNode
• ordering
• ordering
424
AWS Glue Developer Guide
Scala API List
• ordering
MapLikeNode Class
MapLikeNode
def getValue
425
AWS Glue Developer Guide
Scala API List
) : Option[DynamicNode]
{"foo": "bar"}
If useQuotes == true, toJson yields {"foo": "bar"}. If useQuotes == false, toJson yields
{foo: bar} @return.
def clone
def nodeType
def this
Package: com.amazonaws.services.glue.types
426
AWS Glue Developer Guide
Scala API List
NullNode Class
NullNode
class NullNode
Package: com.amazonaws.services.glue.types
ObjectNode Object
ObjectNode
object ObjectNode
def clone
def nodeType
427
AWS Glue Developer Guide
Scala API List
def this
Package: com.amazonaws.services.glue.types
ScalarNode Class
ScalarNode
def getValue
def nodeType
def toJson
ScalarNode Object
ScalarNode
object ScalarNode
428
AWS Glue Developer Guide
Scala API List
o : String )
• ordering
• ordering
429
AWS Glue Developer Guide
Scala API List
• ordering
GlueArgParser Object
GlueArgParser
object GlueArgParser
Job Object
Job
object Job
def commit
430
AWS Glue Developer Guide
Scala API List
) : this.type
def isInitialized
def reset
def runId
431
AWS Glue Developer Guide
Types of Machine Learning Transforms
• Matching Customers: Linking customer records across different customer databases, even when
many customer fields do not match exactly across the databases (e.g. different name spelling, address
differences, missing or inaccurate data, etc).
• Matching Products: Matching products in your catalog against other product sources, such as product
catalog against a competitor's catalog, where entries are structured differently.
• Improving Fraud Detection: Identifying duplicate customer accounts, determining when a newly
created account is (or might be) a match for a previously known fraudulent user.
• Other Matching Problems: Match addresses, movies, parts lists, etc etc. In general, if a human being
could look at your database rows and determine that they were a match, there is a really good chance
that the FindMatches transform can help you.
You can create these transforms when you create a job. The transform that you create is based on a
source data store schema and example data that you label (we call this process “teaching” a transform).
In this process we generate a file which you label and then upload back which the transform would in a
manner learn from). After you teach your transform, you can call it from your Spark-based AWS Glue job
(PySpark or Scala Spark) and use it in other scripts with a compatible source data store.
After the transform is created, it is stored in AWS Glue. On the AWS Glue console, you can manage the
transforms that you create. On the AWS Glue ML transforms tab, you can edit and continue to teach
your machine learning transform. For more information about managing transforms on the console, see
Working with Machine Learning Transforms on the AWS Glue Console (p. 438).
Find matches
Finds duplicate records in the source data. You teach this machine learning transform by labeling
example datasets to indicate which rows match. The AWS Glue machine learning transform learns
which rows should be matches the more you teach it with example labeled data. Depending on how
you configure the transform, the output is one of the following:
432
AWS Glue Developer Guide
Find Matches Transform
• A copy of the input table plus a match_id column filled in with values that indicate matching
sets of records. The match_id column is an arbitrary identifier. Any records which have the same
match_id have been identified as matching to each other. Records with different match_id's do
not match.
• A copy of the input table with duplicate rows removed. If multiple duplicates are found, then the
record with the lowest primary key is kept.
1. Create a table in the AWS Glue Data Catalog for the source data that is to be cleaned. For information
about how to create a crawler, see Working with Crawlers on the AWS Glue Console.
If your source data is a text-based file such as a comma-separated values (CSV) file, consider the
following:
• Keep your input record CSV file and labeling file in separate folders. Otherwise, the AWS Glue
crawler might consider them as multiple parts of the same table and create tables in the Data
Catalog incorrectly.
• Unless your CSV file includes ASCII characters only, ensure that UTF-8 without BOM (byte order
mark) encoding is used for the CSV files. Microsoft Excel often adds a BOM in the beginning of
UTF-8 CSV files. To remove it, open the CSV file in a text editor, and resave the file as UTF-8 without
BOM.
2. On the AWS Glue console, create a job, and choose the Find matches transform type.
Important
The data source table that you choose for the job can't have more than 100 columns.
3. Tell AWS Glue to generate a labeling file by choosing Generate labeling file. AWS Glue takes the first
pass at grouping similar records for each labeling_set_id so that you can review those groupings.
You label matches in the label column.
• If you already have a labeling file, that is, an example of records that indicate matching rows, upload
the file to Amazon Simple Storage Service (Amazon S3). For information about the format of the
labeling file, see Labeling File Format (p. 434). Proceed to step 4.
4. Download the labeling file and label the file as described in the Labeling (p. 434) section.
5. Upload the corrected labelled file. AWS Glue runs tasks to teach the transform how to find matches.
On the Machine learning transforms list page, choose the History tab. This page indicates when AWS
Glue performs the following tasks:
• Import labels
• Export labels
• Generate labels
• Estimate quality
6. To create a better transform, you can iteratively download, label, and upload the labelled file. In the
initial runs, a lot more records might be mismatched. But AWS Glue learns as you continue to teach it
by verifying the labeling file.
7. Evaluate and tune your transform by evaluating performance and results of finding matches. For more
information, see Tuning Machine Learning Transforms in AWS Glue (p. 435).
433
AWS Glue Developer Guide
Find Matches Transform
Labeling
When AWS Glue generates a labeling file, records are selected from your source table. Based on previous
training, AWS Glue identifies the most valuable records to learn from.
The act of labeling is editing a labeling file (such as in a spreadsheet) and adding identifiers, or labels,
into the label column that identifies matching and nonmatching records. It is important to have a
clear and consistent definition of a match in your source data. AWS Glue learns from which records you
designate as matches (or not) and uses your decisions to learn how to find duplicate records.
When a labeling file is generated by AWS Glue, approximately 100 records are generated. There are
roughly 10 records per unique labeling_set_id generated. You label each set of records for each
labeling_set_id.
• The file might not open with column fields fully expanded. You might need to expand the
labeling_set_id and label columns to see content in those cells.
• If the primary key column is a number, such as a long data type, the spreadsheet might interpret it as
a number and change the value. This key value must be treated as text. To correct this problem, format
all the cells in the primary key column as Text data.
434
AWS Glue Developer Guide
Tuning Machine Learning Transforms
• The scope of the labels is limited to the labeling_set_id. So labels do not cross
labeling_set_id boundaries. For example, a label "A" in labeling_set_id 1 does not have any
relation to label "A" in labeling_set_id 2.
• Labels should include examples of both matching and nonmatching records for the
labeling_set_id.
• If a record does not have any matches, then assign it a unique label.
Important
Confirm that the IAM role that you pass to AWS Glue has access to the Amazon S3 bucket
that contains the labeling file. By convention, AWS Glue policies grant permission to Amazon
S3 buckets or folders whose names are prefixed with aws-glue-. If your labeling files are in a
different location, add permission to that location in the IAM role.
For more information about machine learning transforms, see Machine Learning Transforms in AWS
Glue (p. 432).
Topics
• Machine Learning Measurements (p. 435)
• Deciding Between Precision and Recall (p. 436)
• Deciding Between Accuracy and Cost (p. 437)
• Teaching the Find Matches Transform (p. 437)
A match in the data that the transform correctly found, sometimes called a hit.
True negative (TN)
A nonmatch in the data that the transform incorrectly classified as a match, sometimes called a false
alarm.
False negative (FN)
A match in the data that the transform didn't find, sometimes called a miss.
For more information about the terminology that is used in machine learning, see Confusion matrix in
Wikipedia.
435
AWS Glue Developer Guide
Deciding Between Precision and Recall
To tune your machine learning transforms, you can change the value of the following measurements in
the Advanced properties of the transform.
• Precision measures how well the transform finds true positives from the total true positives possible.
For more information, see Precision and recall in Wikipedia.
• Recall measures how well the transform finds true positives from the total records in the source data.
For more information, see Precision and recall in Wikipedia.
• Accuracy measures how well the transform finds true positives and true negatives. Increasing accuracy
requires more machine resources and cost. But it also results in increased recall. For more information,
see Accuracy and precision in Wikipedia.
• Cost measures how many compute resources (and thus money) are consumed to run the transform.
• If you are more concerned about the transform falsely reporting that two records match when they
actually don't match, then you should emphasize precision.
• If you are more concerned about the transform failing to detect records that really do match, then you
should emphasize recall.
You can make this trade-off on the AWS Glue console or by using the AWS Glue machine learning API
operations.
Favor precision if you are more concerned about the risk that FindMatches results in a pair of records
matching when they don't actually match. To favor precision, choose a higher precision-recall trade-off
value. With a higher value, the FindMatches transform requires more evidence to decide that a pair of
records should be matched. The transform is tuned to bias toward saying that records do not match.
For example, suppose that you're using FindMatches to detect duplicate items in a video catalog, and
you provide a higher precision-recall value to the transform. If your transform incorrectly detects that
Star Wars: A New Hope is the same as Star Wars: The Empire Strikes Back, a customer who wants A New
Hope might be shown The Empire Strikes Back. This would be a poor customer experience.
However, if the transform fails to detect that Star Wars: A New Hope and Star Wars: Episode IV—A New
Hope are the same item, the customer might be confused at first but might eventually recognize them as
the same. It would be a mistake, but not as bad as the previous scenario.
Favor recall if you are more concerned about the risk that the FindMatches transform results might fail
to detect a pair of records that actually do match. To favor recall, choose a lower precision-recall trade-
off value. With a lower value, the FindMatches transform requires less evidence to decide that a pair of
records should be matched. The transform is tuned to bias toward saying that records do match.
For example, this might be a priority for a security organization. Suppose that you are matching
customers against a list of known defrauders, and it is important to determine whether a customer is
a defrauder. You are using FindMatches to match the defrauder list against the customer list. Every
time FindMatches detects a match between the two lists, a human auditor is assigned to verify that
the person is, in fact, a defrauder. Your organization might prefer to choose recall over precision. In other
words, you would rather have the auditors manually review and reject some cases when the customer is
not a defrauder than fail to identify that a customer is, in fact, on the defrauder list.
436
AWS Glue Developer Guide
Deciding Between Accuracy and Cost
The best way to improve both precision and recall is to label more data. As you label more data, the
overall accuracy of the FindMatches transform improves, thus improving both precision and recall.
Nevertheless, even with the most accurate transform, there is always a gray area where you need to
experiment with favoring precision or recall, or choose a value in the middle.
• If you are more concerned with the transform accurately reporting that two records match, then you
should emphasize accuracy.
• If you are more concerned about the cost or speed of running the transform, then you should
emphasize lower cost.
You can make this trade-off on the AWS Glue console or by using the AWS Glue machine learning API
operations.
Favor accuracy if you are more concerned about the risk that the find matches results won't contain
matches. To favor accuracy, choose a higher accuracy-cost trade-off value. With a higher value, the
FindMatches transform requires more time to do a more thorough search for correctly matching
records. Note that this parameter doesn't make it less likely to falsely call a nonmatching record pair a
match. The transform is tuned to bias towards spending more time finding matches.
Favor cost if you are more concerned about the cost of running the find matches transform and less
about how many matches are found. To favor cost, choose a lower accuracy-cost trade-off value. With a
lower value, the FindMatches transform requires fewer resources to run. The transform is tuned to bias
towards finding fewer matches. If the results are acceptable when favoring lower cost, use this setting.
It takes more machine time to examine more pairs of records to determine whether they might be
matches. If you want to reduce cost without reducing quality, here are some steps you can take:
• Eliminate records in your data source that you aren't concerned about matching.
• Eliminate columns from your data source that you are sure aren't useful for making a match/no-match
decision. A good way of deciding this is to eliminate columns that you don't think affect your own
decision about whether a set of records is “the same.”
You can orchestrate this labeling on the AWS Glue console or by using the AWS Glue machine learning
API operations.
How Many Times Should I Add Labels? How Many Labels Do I Need?
The answers to these questions are mostly up to you. You must evaluate whether FindMatches is
delivering the level of accuracy that you need and whether you think the extra labeling effort is worth it
for you. The best way to decide this is to look at the “Precision,” “Recall,” and “Area under the precision
437
AWS Glue Developer Guide
Machine Learning Transforms on the Console
recall curve” metrics that you can generate when you choose Estimate quality on the AWS Glue console.
After you label more sets of tasks, rerun these metrics and verify whether they have improved. If, after
labeling a few sets of tasks, you don't see improvement on the metric that you are focusing on, the
transform quality might have reached a plateau.
Why Are Both True Positive and True Negative Labels Needed?
The FindMatches transform needs both positive and negative examples to learn what you think is a
match. If you are labeling FindMatches-generated training data (for example, using the I do not have
labels option), FindMatches tries to generate a set of “label set ids” for you. Within each task, you
give the same “label” to some records and different “labels” to other records. In other words, the tasks
generally are not either all the same or all different (but it's okay if a particular task is all “the same” or
all “not the same”).
If you are teaching your FindMatches transform using the Upload labels from S3 option, try to include
both examples of matching and nonmatching records. It's acceptable to have only one type. These labels
help you build a more accurate FindMatches transform, but you still need to label some records that
you generate using the Generate labeling file option.
How Can I Enforce That the Transform Matches Exactly as I Taught It?
The FindMatches transform learns from the labels that you provide, so it might generate records pairs
that don't respect the provided labels. To enforce that the FindMatches transform respects your labels,
select EnforceProvidedLabels in FindMatchesParameter.
What Techniques Can You Use When an ML Transform Identifies Items as Matches That Are Not True
Matches?
• Increase the precisionRecallTradeoff to a higher value. This eventually results in finding fewer
matches, but it should also break up your big cluster when it reaches a high enough value.
• Take the output rows corresponding to the incorrect results and reformat them as a labeling set
(removing the match_id column and adding a labeling_set_id and label column). If necessary,
break up (subdivide) into multiple labeling sets to ensure that the labeler can keep each labeling set
in mind while assigning labels. Then, correctly label the matching sets and upload the label file and
append it to your existing labels. This might teach your transformer enough about what it is looking
for to understand the pattern.
• (Advanced) Finally, look at that data to see if there is a pattern that you can detect that the system is
not noticing. Preprocess that data using standard AWS Glue functions to normalize the data. Highlight
what you want the algorithm to learn from by separating data that you know to be differently
important into their own columns. Or construct combined columns from columns whose data you
know to be related.
For information about how to create a machine learning transform, see Machine Learning Transforms in
AWS Glue (p. 432).
Topics
• Transform Properties (p. 439)
• Adding and Editing Machine Learning Transforms (p. 439)
438
AWS Glue Developer Guide
Transform Properties
Transform Properties
To view an existing machine learning transform, sign in to the AWS Management Console, and open the
AWS Glue console at https://console.aws.amazon.com/glue/. Then choose the ML transforms tab.
The Machine Learning Transforms list displays the following properties for each transform:
Transform name
The unique name you gave the transform when you created it.
Transform ID
The type of machine learning transform; for example, Find matching records.
Status
Indicates whether the transform is Ready or Needs teaching. To run a machine learning transform
successfully in a job, it must be Ready.
When you create a FindMatches transform, you specify the following configuration information:
Primary key
The name of a column that uniquely identifies rows in the source table.
Type
Indicates whether the transform is to remove duplicates in the target. The record with the lowest
primary key value is written to the output of the transform.
To add a new machine learning transform, choose the Jobs tab, and then choose Add job. Follow the
instructions in the Add job wizard to add a job with a machine learning transform such as FindMatches.
For more information, see Machine Learning Transforms in AWS Glue (p. 432).
• History
• Details
• Estimate quality
439
AWS Glue Developer Guide
Viewing Transform Details
History
The History tab shows your transform task run history. Several types of tasks are run to teach a
transform. For each task, the run metrics include the following:
• Run ID is an identifier created by AWS Glue for each run of this task.
• Task type shows the type of task run.
• Status shows the success of each task listed with the most recent run at the top.
• Error shows the details of an error message if the run was not successful.
• Start time shows the date and time (local time) that the task started.
• Execution time shows the length of time during which the job run consumed resources. The amount is
calculated from when the job run starts consuming resources until it finishes.
• Last modified shows the date and time (local time) that the task was last modified.
• Logs links to the logs written to stdout for this job run.
The Logs link takes you to Amazon CloudWatch Logs. There you can view the details about the tables
that were created in the AWS Glue Data Catalog and any errors that were encountered. You can
manage your log retention period on the CloudWatch console. The default log retention is Never
Expire. For more information about how to change the retention period, see Change Log Data
Retention in CloudWatch Logs in the Amazon CloudWatch Logs User Guide.
• Error logs links to the logs written to stderr for this task run.
This link takes you to CloudWatch Logs, where you can see details about any errors that were
encountered. You can manage your log retention period on the CloudWatch console. The default log
retention is Never Expire. For more information about how to change the retention period, see
Change Log Data Retention in CloudWatch Logs in the Amazon CloudWatch Logs User Guide.
• Download label file shows a link to Amazon S3 for a generated labeling file.
Details
The Details tab includes attributes of your transform. It shows you the details about the transform
definition, including the following:
Estimate quality
The Estimate quality tab shows the metrics that you use to measure the quality of the transform.
Estimates are calculated by comparing the transform match predictions using a subset of your labeled
data against the labels you have provided. These estimates are approximate.You can invoke an Estimate
quality task run from this tab.
The Estimate quality tab shows the metrics from the last Estimate quality run including the following
properties:
• Area under the Precision-Recall curve is a single number estimating the upper bound of the overall
quality of the transform. It is independent of the choice made for the precision-recall parameter.
Higher values indicate that you have a more attractive precision-recall tradeoff.
440
AWS Glue Developer Guide
Tutorial: Creating a Machine Learning Transform
• Precision estimates how often the transform is correct when it predicts a match.
• Recall upper limit estimates that for an actual match, how often the transform predicts the match.
• Max F1 estimates the transform's accuracy between 0 and 1, where 1 is the best accuracy. For more
information, see F1 score in Wikipedia.
For information about understanding quality estimates versus true quality, see Quality Estimates Versus
End-to-End (True) Quality (p. 441).
For more information about tuning your transform, see Tuning Machine Learning Transforms in AWS
Glue (p. 435).
You can tune this filtering method primarily by using the Lower Cost-Accuracy slider. As you move this
slider closer to the Accuracy end, the system does a more thorough and expensive search for pairs of
records that might be matches. More pairs of records are fed to your machine-learned model, and your
FindMatches transform's end-to-end or true recall gets closer to the estimated recall metric. As a
result, changes in the end-to-end quality of your matches as a result of changes in your matches's cost/
accuracy tradeoff will typically not be reflected in the quality estimate.
In this example, you create a FindMatches transform to find matching records, teach it how to identify
matching and nonmatching records, and use it in an AWS Glue job. The AWS Glue job writes a new
Amazon S3 file with an additional column named match_id.
The source data used by this tutorial is a file named dblp_acm_records.csv. This file is a modified
version of academic publications (DBLP and ACM) available from the original DBLP ACM dataset. The
dblp_acm_records.csv file is a comma-separated values (CSV) file in UTF-8 format with no byte-
order mark (BOM).
A second file, dblp_acm_labels.csv, is an example labeling file that contains both matching and
nonmatching records used to teach the transform as part of the tutorial.
Topics
• Step 1: Crawl the Source Data (p. 442)
• Step 2: Add a Machine Learning Transform (p. 442)
• Step 3: Teach Your Machine Learning Transform (p. 442)
• Step 4: Estimate the Quality of Your Machine Learning Transform (p. 443)
441
AWS Glue Developer Guide
Step 1: Crawl the Source Data
• Step 5: Add and Run a Job with Your Machine Learning Transform (p. 443)
• Step 6: Verify Output Data from Amazon S3 (p. 445)
1. Sign in to the AWS Management Console and open the AWS Glue console at https://
console.aws.amazon.com/glue/.
2. In the navigation pane, choose Crawlers, Add crawler.
3. Follow the wizard to create and run a crawler named demo-crawl-dblp-acm with output to
database demo-db-dblp-acm. When running the wizard, create the database demo-db-dblp-
acm if it doesn't already exist. Choose an Amazon S3 include path to sample data in the current AWS
Region. For example, for us-east-1, the Amazon S3 include path to the source file is s3://ml-
transforms-public-datasets-us-east-1/dblp-acm/records/dblp_acm_records.csv.
If successful, the crawler creates the table dblp_acm_records_csv with the following columns: id,
title, authors, venue, year, and source.
1. On the AWS Glue console, in the navigation pane, choose ML Transforms, Add transform. Then
follow the wizard to create a Find matches transform with the following properties.
a. For Transform name, enter demo-xform-dblp-acm. This is the name of the transform that is
used to find matches in the source data.
b. For IAM role, choose an IAM role that has permission to the Amazon S3 source data, labeling
file, and AWS Glue API operations. For more information, see Create an IAM Role for AWS Glue
in the AWS Glue Developer Guide.
c. For Data source, choose the table named dblp_acm_records_csv in database demo-db-dblp-
acm.
d. For Primary key, choose the primary key column for the table, id.
e. For Predictive columns, choose the title, authors, venue, year, and source columns in the data
source to act as predictive columns.
2. In the wizard, choose Finish and return to the ML transforms list.
You can't use a machine language transform in an extract, transform, and load (ETL) job until its
status is Ready for use. To get your transform ready, you must teach it how to identify matching and
nonmatching records by providing examples of matching and nonmatching records. To teach your
transform, you can Generate a label file, add labels, and then Upload label file. In this tutorial, you can
use the example labeling file named dblp_acm_labels.csv. For more information about the labeling
process, see Labeling (p. 434).
442
AWS Glue Developer Guide
Step 4: Estimate the Quality of
Your Machine Learning Transform
When you upload a labeling file, a task is started in AWS Glue to add or overwrite the labels used to
teach the transform how to process the data source.
4. On the final page of the wizard, choose Finish, and return to the ML transforms list.
443
AWS Glue Developer Guide
Step 5: Add and Run a Job with
Your Machine Learning Transform
g. Clear Remove duplicate records. You don't want to remove duplicate records because the
output records written have an additional match_id field added.
h. For Transform, choose demo-xform-dblp-acm, the machine learning transform used by the
job.
i. For Create tables in your data target, choose to create tables with the following properties:
import com.amazonaws.services.glue.GlueContext
import com.amazonaws.services.glue.errors.CallSite
import com.amazonaws.services.glue.ml.FindMatches
import com.amazonaws.services.glue.util.GlueArgParser
import com.amazonaws.services.glue.util.Job
import com.amazonaws.services.glue.util.JsonOptions
import org.apache.spark.SparkContext
import scala.collection.JavaConverters._
object GlueApp {
def main(sysArgs: Array[String]) {
val spark: SparkContext = new SparkContext()
val glueContext: GlueContext = new GlueContext(spark)
// @params: [JOB_NAME]
val args = GlueArgParser.getResolvedOptions(sysArgs, Seq("JOB_NAME").toArray)
Job.init(args("JOB_NAME"), glueContext, args.asJava)
// @type: DataSource
// @args: [database = "demo-db-dblp-acm", table_name = "dblp_acm_records_csv",
transformation_ctx = "datasource0"]
// @return: datasource0
// @inputs: []
val datasource0 = glueContext.getCatalogSource(database = "demo-db-dblp-acm",
tableName = "dblp_acm_records_csv", redshiftTmpDir = "", transformationContext =
"datasource0").getDynamicFrame()
// @type: FindMatches
// @args: [transformId = "tfm-123456789012", emitFusion = false,
survivorComparisonField = "<primary_id>", transformation_ctx = "findmatches1"]
// @return: findmatches1
// @inputs: [frame = datasource0]
val findmatches1 = FindMatches.apply(frame = datasource0, transformId =
"tfm-123456789012", transformationContext = "findmatches1")
444
AWS Glue Developer Guide
Step 6: Verify Output Data from Amazon S3
// @type: DataSink
// @args: [connection_type = "s3", connection_options = {"path": "s3://aws-glue-ml-
transforms-data/sal"}, format = "csv", transformation_ctx = "datasink2"]
// @return: datasink2
// @inputs: [frame = findmatches1]
val datasink2 = glueContext.getSinkWithFormat(connectionType =
"s3", options = JsonOptions("""{"path": "s3://aws-glue-ml-transforms-
data/sal"}"""), transformationContext = "datasink2", format =
"csv").writeDynamicFrame(single_partition)
Job.commit()
}
}
6. Choose Run job to start the job run. Check the status of the job in the jobs list. When the job
finishes, in the ML transform, History tab, there is a new Run ID row added of type ETL job.
7. Navigate to the Jobs, History tab. In this pane, job runs are listed. For more details about the run,
choose Logs. Check that the run status is Succeeded when it finishes.
The data source and target file both have 4,911 records. However, the Find matches transform
adds another column named match_id to identify matching records in the output. Rows with the
same match_id are considered matching records.
3. Sort the output file by match_id to easily see which records are matches. Compare the values in the
other columns to see if you agree with the results of the Find matches transform. If you don't, you
can continue to teach the transform by adding more labels.
You can also sort the file by another field, such as title, to see if records with similar titles have the
same match_id.
445
AWS Glue Developer Guide
446
AWS Glue Developer Guide
Data Types
• DataCatalogEncryptionSettings Structure (p. 453)
• EncryptionAtRest Structure (p. 454)
• ConnectionPasswordEncryption Structure (p. 454)
• EncryptionConfiguration Structure (p. 455)
• S3Encryption Structure (p. 455)
• CloudWatchEncryption Structure (p. 455)
• JobBookmarksEncryption Structure (p. 455)
• SecurityConfiguration Structure (p. 456)
DataCatalogEncryptionSettings Structure
Contains configuration information for maintaining Data Catalog security.
Fields
When connection password protection is enabled, the Data Catalog uses a customer-provided key
to encrypt the password as part of CreateConnection or UpdateConnection and store it in the
ENCRYPTED_PASSWORD field in the connection properties. You can enable catalog encryption or only
password encryption.
EncryptionAtRest Structure
Specifies the encryption-at-rest configuration for the Data Catalog.
Fields
ConnectionPasswordEncryption Structure
The data structure used by the Data Catalog to encrypt the password as part of CreateConnection or
UpdateConnection and store it in the ENCRYPTED_PASSWORD field in the connection properties. You
can enable catalog encryption or only password encryption.
When a CreationConnection request arrives containing a password, the Data Catalog first encrypts
the password using your AWS KMS key. It then encrypts the whole connection object again if catalog
encryption is also enabled.
This encryption requires that you set AWS KMS key permissions to enable or restrict access on the
password key according to your security requirements. For example, you might want only administrators
to have decrypt permission on the password key.
Fields
You can set the decrypt permission to enable or restrict access on the password key according to your
security requirements.
454
AWS Glue Developer Guide
EncryptionConfiguration
EncryptionConfiguration Structure
Specifies an encryption configuration.
Fields
The encryption configuration for Amazon Simple Storage Service (Amazon S3) data.
• CloudWatchEncryption – A CloudWatchEncryption (p. 455) object.
S3Encryption Structure
Specifies how Amazon Simple Storage Service (Amazon S3) data should be encrypted.
Fields
The Amazon Resource Name (ARN) of the KMS key to be used to encrypt the data.
CloudWatchEncryption Structure
Specifies how Amazon CloudWatch data should be encrypted.
Fields
The Amazon Resource Name (ARN) of the KMS key to be used to encrypt the data.
JobBookmarksEncryption Structure
Specifies how job bookmark data should be encrypted.
Fields
455
AWS Glue Developer Guide
SecurityConfiguration
The Amazon Resource Name (ARN) of the KMS key to be used to encrypt the data.
SecurityConfiguration Structure
Specifies a security configuration.
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Operations
• GetDataCatalogEncryptionSettings Action (Python: get_data_catalog_encryption_settings) (p. 456)
• PutDataCatalogEncryptionSettings Action (Python: put_data_catalog_encryption_settings) (p. 457)
• PutResourcePolicy Action (Python: put_resource_policy) (p. 457)
• GetResourcePolicy Action (Python: get_resource_policy) (p. 458)
• DeleteResourcePolicy Action (Python: delete_resource_policy) (p. 459)
• CreateSecurityConfiguration Action (Python: create_security_configuration) (p. 459)
• DeleteSecurityConfiguration Action (Python: delete_security_configuration) (p. 460)
• GetSecurityConfiguration Action (Python: get_security_configuration) (p. 460)
• GetSecurityConfigurations Action (Python: get_security_configurations) (p. 461)
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog to retrieve the security configuration for. If none is provided, the AWS
account ID is used by default.
Response
456
AWS Glue Developer Guide
PutDataCatalogEncryptionSettings
(put_data_catalog_encryption_settings)
Errors
• InternalServiceException
• InvalidInputException
• OperationTimeoutException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog to set the security configuration for. If none is provided, the AWS account
ID is used by default.
• DataCatalogEncryptionSettings – Required: A DataCatalogEncryptionSettings (p. 453) object.
Response
• No Response parameters.
Errors
• InternalServiceException
• InvalidInputException
• OperationTimeoutException
Request
• PolicyInJson – Required: UTF-8 string, not less than 2 or more than 10240 bytes long.
The hash value returned when the previous policy was set using PutResourcePolicy. Its purpose
is to prevent concurrent modifications of a policy. Do not use this parameter if no previous policy has
been set.
• PolicyExistsCondition – UTF-8 string (valid values: MUST_EXIST | NOT_EXIST | NONE).
457
AWS Glue Developer Guide
GetResourcePolicy (get_resource_policy)
A value of MUST_EXIST is used to update a policy. A value of NOT_EXIST is used to create a new
policy. If a value of NONE or a null value is used, the call will not depend on the existence of a policy.
Response
• PolicyHash – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
A hash of the policy that has just been set. This must be included in a subsequent call that overwrites
or updates this policy.
Errors
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
• ConditionCheckFailureException
Request
• No Request parameters.
Response
• PolicyInJson – UTF-8 string, not less than 2 or more than 10240 bytes long.
The date and time at which the policy was last updated.
Errors
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
458
AWS Glue Developer Guide
DeleteResourcePolicy (delete_resource_policy)
• InvalidInputException
Request
• PolicyHashCondition – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
• ConditionCheckFailureException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
459
AWS Glue Developer Guide
DeleteSecurityConfiguration
(delete_security_configuration)
Errors
• AlreadyExistsException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• ResourceNumberLimitExceededException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
460
AWS Glue Developer Guide
GetSecurityConfigurations (get_security_configurations)
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
Response
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Catalog API
The Catalog API describes the data types and API related to working with catalogs in AWS Glue.
Topics
• Database API (p. 462)
• Table API (p. 467)
• Partition API (p. 482)
• Connection API (p. 493)
461
AWS Glue Developer Guide
Databases
Database API
The Database API describes database data types, and includes the API for creating, deleting, locating,
updating, and listing databases.
Data Types
• Database Structure (p. 462)
• DatabaseInput Structure (p. 462)
• PrincipalPermissions Structure (p. 463)
• DataLakePrincipal Structure (p. 463)
Database Structure
The Database object represents a logical grouping of tables that might reside in a Hive metastore or an
RDBMS.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name of the database. For Hive compatibility, this is folded to lowercase when it is stored.
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
Each key is a Key string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each value is a UTF-8 string, not more than 512000 bytes long.
The time at which the metadata database was created in the catalog.
• CreateTableDefaultPermissions – An array of PrincipalPermissions (p. 463) objects.
DatabaseInput Structure
The structure used to create or update a database.
462
AWS Glue Developer Guide
Databases
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name of the database. For Hive compatibility, this is folded to lowercase when it is stored.
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
Optionally specify an Amazon S3 location. This enables you to create catalog tables under the
database without having to grant data location permissions. For more information, see see the Data
Location topic in the AWS Lake Formation Developer Guide.
• Parameters – A map array of key-value pairs.
Each key is a Key string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each value is a UTF-8 string, not more than 512000 bytes long.
PrincipalPermissions Structure
Permissions granted to a principal.
Fields
DataLakePrincipal Structure
The AWS Lake Formation principal.
Fields
• DataLakePrincipalIdentifier – UTF-8 string, not less than 1 or more than 255 bytes long.
463
AWS Glue Developer Guide
Databases
Operations
• CreateDatabase Action (Python: create_database) (p. 464)
• UpdateDatabase Action (Python: update_database) (p. 464)
• DeleteDatabase Action (Python: delete_database) (p. 465)
• GetDatabase Action (Python: get_database) (p. 466)
• GetDatabases Action (Python: get_databases) (p. 466)
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which to create the database. If none is provided, the AWS account ID is
used by default.
• DatabaseInput – Required: A DatabaseInput (p. 462) object.
Response
• No Response parameters.
Errors
• InvalidInputException
• AlreadyExistsException
• ResourceNumberLimitExceededException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which the metadata database resides. If none is provided, the AWS
account ID is used by default.
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name of the database to update in the catalog. For Hive compatibility, this is folded to lowercase.
464
AWS Glue Developer Guide
Databases
A DatabaseInput object specifying the new definition of the metadata database in the catalog.
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which the database resides. If none is provided, the AWS account ID is
used by default.
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name of the database to delete. For Hive compatibility, this must be all lowercase.
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
465
AWS Glue Developer Guide
Databases
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which the database resides. If none is provided, the AWS account ID is
used by default.
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name of the database to retrieve. For Hive compatibility, this should be all lowercase.
Response
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog from which to retrieve Databases. If none is provided, the AWS account ID
is used by default.
• NextToken – UTF-8 string.
Response
466
AWS Glue Developer Guide
Tables
A continuation token for paginating the returned list of tokens, returned if the current segment of the
list is not the last.
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Table API
The Table API describes data types and operations associated with tables.
Data Types
• Table Structure (p. 467)
• TableInput Structure (p. 469)
• Column Structure (p. 470)
• StorageDescriptor Structure (p. 470)
• SerDeInfo Structure (p. 471)
• Order Structure (p. 471)
• SkewedInfo Structure (p. 472)
• TableVersion Structure (p. 472)
• TableError Structure (p. 472)
• TableVersionError Structure (p. 473)
• SortCriterion Structure (p. 473)
Table Structure
Represents a collection of related data organized in columns and rows.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The table name. For Hive compatibility, this must be entirely lowercase.
• DatabaseName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name of the database where the table metadata resides. For Hive compatibility, this must be all
lowercase.
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
467
AWS Glue Developer Guide
Tables
• Owner – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The time when the table definition was created in the Data Catalog.
• UpdateTime – Timestamp.
The last time that the table was accessed. This is usually taken from HDFS, and might not be reliable.
• LastAnalyzedTime – Timestamp.
The last time that column statistics were computed for this table.
• Retention – Number (integer), not more than None.
A storage descriptor containing information about the physical storage of this table.
• PartitionKeys – An array of Column (p. 470) objects.
A list of columns by which the table is partitioned. Only primitive types are supported as partition
keys.
When you create a table used by Amazon Athena, and you do not specify any partitionKeys, you
must at least set the value of partitionKeys to an empty list. For example:
"PartitionKeys": []
• ViewOriginalText – UTF-8 string, not more than 409600 bytes long.
If the table is a view, the original text of the view; otherwise null.
• ViewExpandedText – UTF-8 string, not more than 409600 bytes long.
If the table is a view, the expanded text of the view; otherwise null.
• TableType – UTF-8 string, not more than 255 bytes long.
Each key is a Key string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each value is a UTF-8 string, not more than 512000 bytes long.
TableInput Structure
A structure used to define a table.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The table name. For Hive compatibility, this is folded to lowercase when it is stored.
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
The last time that column statistics were computed for this table.
• Retention – Number (integer), not more than None.
A storage descriptor containing information about the physical storage of this table.
• PartitionKeys – An array of Column (p. 470) objects.
A list of columns by which the table is partitioned. Only primitive types are supported as partition
keys.
When you create a table used by Amazon Athena, and you do not specify any partitionKeys, you
must at least set the value of partitionKeys to an empty list. For example:
"PartitionKeys": []
• ViewOriginalText – UTF-8 string, not more than 409600 bytes long.
If the table is a view, the original text of the view; otherwise null.
• ViewExpandedText – UTF-8 string, not more than 409600 bytes long.
If the table is a view, the expanded text of the view; otherwise null.
• TableType – UTF-8 string, not more than 255 bytes long.
Each key is a Key string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each value is a UTF-8 string, not more than 512000 bytes long.
469
AWS Glue Developer Guide
Tables
Column Structure
A column in a Table.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Each key is a Key string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each value is a UTF-8 string, not more than 512000 bytes long.
StorageDescriptor Structure
Describes the physical storage of table data.
Fields
The physical location of the table. By default, this takes the form of the warehouse location, followed
by the database location in the warehouse, followed by the table name.
• InputFormat – Format string, not more than 128 bytes long, matching the Single-line string
pattern (p. 612).
470
AWS Glue Developer Guide
Tables
A list of reducer grouping columns, clustering columns, and bucketing columns in the table.
• SortColumns – An array of Order (p. 471) objects.
Each key is a Key string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each value is a UTF-8 string, not more than 512000 bytes long.
The information about values that appear frequently in a column (skewed values).
• StoredAsSubDirectories – Boolean.
SerDeInfo Structure
Information about a serialization/deserialization program (SerDe) that serves as an extractor and loader.
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each key is a Key string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each value is a UTF-8 string, not more than 512000 bytes long.
Order Structure
Specifies the sort order of a sorted column.
Fields
• Column – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-
line string pattern (p. 612).
471
AWS Glue Developer Guide
Tables
Indicates that the column is sorted in ascending order (== 1), or in descending order (==0).
SkewedInfo Structure
Specifies skewed values in a table. Skewed values are those that occur with very high frequency.
Fields
TableVersion Structure
Specifies a version of a table.
Fields
The ID value that identifies this table version. A VersionId is a string representation of an integer.
Each version is incremented by 1.
TableError Structure
An error record for table operations.
Fields
• TableName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name of the table. For Hive compatibility, this must be entirely lowercase.
• ErrorDetail – An ErrorDetail (p. 611) object.
472
AWS Glue Developer Guide
Tables
TableVersionError Structure
An error record for table-version operations.
Fields
• TableName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID value of the version in question. A VersionID is a string representation of an integer. Each
version is incremented by 1.
• ErrorDetail – An ErrorDetail (p. 611) object.
SortCriterion Structure
Specifies a field to sort by and a sort order.
Fields
Operations
• CreateTable Action (Python: create_table) (p. 473)
• UpdateTable Action (Python: update_table) (p. 474)
• DeleteTable Action (Python: delete_table) (p. 475)
• BatchDeleteTable Action (Python: batch_delete_table) (p. 476)
• GetTable Action (Python: get_table) (p. 476)
• GetTables Action (Python: get_tables) (p. 477)
• GetTableVersion Action (Python: get_table_version) (p. 478)
• GetTableVersions Action (Python: get_table_versions) (p. 479)
• DeleteTableVersion Action (Python: delete_table_version) (p. 479)
• BatchDeleteTableVersion Action (Python: batch_delete_table_version) (p. 480)
• SearchTables Action (Python: search_tables) (p. 481)
473
AWS Glue Developer Guide
Tables
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which to create the Table. If none is supplied, the AWS account ID is
used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The catalog database in which to create the new table. For Hive compatibility, this name is entirely
lowercase.
• TableInput – Required: A TableInput (p. 469) object.
The TableInput object that defines the metadata table to create in the catalog.
Response
• No Response parameters.
Errors
• AlreadyExistsException
• InvalidInputException
• EntityNotFoundException
• ResourceNumberLimitExceededException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the table resides. If none is provided, the AWS account ID is used by
default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the catalog database in which the table resides. For Hive compatibility, this name is
entirely lowercase.
• TableInput – Required: A TableInput (p. 469) object.
By default, UpdateTable always creates an archived version of the table before updating it. However,
if skipArchive is set to true, UpdateTable does not create the archived version.
474
AWS Glue Developer Guide
Tables
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• ConcurrentModificationException
• ResourceNumberLimitExceededException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the table resides. If none is provided, the AWS account ID is used by
default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the catalog database in which the table resides. For Hive compatibility, this name is
entirely lowercase.
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name of the table to be deleted. For Hive compatibility, this name is entirely lowercase.
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
475
AWS Glue Developer Guide
Tables
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the table resides. If none is provided, the AWS account ID is used by
default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the catalog database in which the tables to delete reside. For Hive compatibility, this
name is entirely lowercase.
• TablesToDelete – Required: An array of UTF-8 strings, not more than 100 strings.
Response
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the table resides. If none is provided, the AWS account ID is used by
default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
476
AWS Glue Developer Guide
Tables
The name of the database in the catalog in which the table resides. For Hive compatibility, this name is
entirely lowercase.
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name of the table for which to retrieve the definition. For Hive compatibility, this name is entirely
lowercase.
Response
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the tables reside. If none is provided, the AWS account ID is used by
default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The database in the catalog whose tables to list. For Hive compatibility, this name is entirely lowercase.
• Expression – UTF-8 string, not more than 2048 bytes long, matching the Single-line string
pattern (p. 612).
A regular expression pattern. If present, only those tables whose names match the pattern are
returned.
• NextToken – UTF-8 string.
Response
477
AWS Glue Developer Guide
Tables
A continuation token, present if the current list segment is not the last.
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the tables reside. If none is provided, the AWS account ID is used by
default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The database in the catalog in which the table resides. For Hive compatibility, this name is entirely
lowercase.
• TableName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the table. For Hive compatibility, this name is entirely lowercase.
• VersionId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID value of the table version to be retrieved. A VersionID is a string representation of an integer.
Each version is incremented by 1.
Response
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
478
AWS Glue Developer Guide
Tables
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the tables reside. If none is provided, the AWS account ID is used by
default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The database in the catalog in which the table resides. For Hive compatibility, this name is entirely
lowercase.
• TableName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the table. For Hive compatibility, this name is entirely lowercase.
• NextToken – UTF-8 string.
Response
A continuation token, if the list of available versions does not include the last one.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
479
AWS Glue Developer Guide
Tables
The ID of the Data Catalog where the tables reside. If none is provided, the AWS account ID is used by
default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The database in the catalog in which the table resides. For Hive compatibility, this name is entirely
lowercase.
• TableName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the table. For Hive compatibility, this name is entirely lowercase.
• VersionId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The ID of the table version to be deleted. A VersionID is a string representation of an integer. Each
version is incremented by 1.
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the tables reside. If none is provided, the AWS account ID is used by
default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The database in the catalog in which the table resides. For Hive compatibility, this name is entirely
lowercase.
• TableName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the table. For Hive compatibility, this name is entirely lowercase.
• VersionIds – Required: An array of UTF-8 strings, not more than 100 strings.
A list of the IDs of versions to be deleted. A VersionId is a string representation of an integer. Each
version is incremented by 1.
480
AWS Glue Developer Guide
Tables
Response
A list of errors encountered while trying to delete the specified table versions.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
You can only get tables that you have access to based on the security policies defined in Lake Formation.
You need at least a read-only access to the table for it to be returned. If you do not have access to all
the columns in the table, these columns will not be searched against when returning the list of tables
back to you. If you have access to the columns but not the data in the columns, those columns and the
associated metadata for those columns will be included in the search.
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
A list of key-value pairs, and a comparator used to filter the search results. Returns all entities
matching the predicate.
• SearchText – Value string, not more than 1024 bytes long.
A list of criteria for sorting the results by a field name, in an ascending or descending order.
• MaxResults – Number (integer), not less than 1 or more than 1000.
Response
A continuation token, present if the current list segment is not the last.
481
AWS Glue Developer Guide
Partitions
A list of the requested Table objects. The SearchTables response returns only the tables that you
have access to.
Errors
• InternalServiceException
• InvalidInputException
• OperationTimeoutException
Partition API
The Partition API describes data types and operations used to work with partitions.
Data Types
• Partition Structure (p. 482)
• PartitionInput Structure (p. 483)
• PartitionSpecWithSharedStorageDescriptor Structure (p. 483)
• PartitionListComposingSpec Structure (p. 484)
• PartitionSpecProxy Structure (p. 484)
• PartitionValueList Structure (p. 484)
• Segment Structure (p. 484)
• PartitionError Structure (p. 485)
Partition Structure
Represents a slice of table data.
Fields
482
AWS Glue Developer Guide
Partitions
Provides information about the physical location where the partition is stored.
• Parameters – A map array of key-value pairs.
Each key is a Key string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each value is a UTF-8 string, not more than 512000 bytes long.
The last time at which column statistics were computed for this partition.
PartitionInput Structure
The structure used to create and update a partition.
Fields
The values of the partition. Although this parameter is not required by the SDK, you must specify this
parameter for a valid input.
The values for the keys for the new partition must be passed as an array of String objects that must
be ordered in the same order as the partition keys appearing in the Amazon S3 prefix. Otherwise AWS
Glue will add the values to the wrong keys.
• LastAccessTime – Timestamp.
Provides information about the physical location where the partition is stored.
• Parameters – A map array of key-value pairs.
Each key is a Key string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each value is a UTF-8 string, not more than 512000 bytes long.
The last time at which column statistics were computed for this partition.
PartitionSpecWithSharedStorageDescriptor Structure
A partition specification for partitions that share a physical location.
Fields
483
AWS Glue Developer Guide
Partitions
PartitionListComposingSpec Structure
Lists the related partitions.
Fields
PartitionSpecProxy Structure
Provides a root path to specified partitions.
Fields
• DatabaseName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
PartitionValueList Structure
Contains a list of values defining partitions.
Fields
Segment Structure
Defines a non-overlapping region of a table's partitions, allowing multiple requests to be executed in
parallel.
484
AWS Glue Developer Guide
Partitions
Fields
The zero-based index number of the segment. For example, if the total number of segments is 4,
SegmentNumber values range from 0 through 3.
• TotalSegments – Required: Number (integer), not less than 1 or more than 10.
PartitionError Structure
Contains information about a partition error.
Fields
Operations
• CreatePartition Action (Python: create_partition) (p. 485)
• BatchCreatePartition Action (Python: batch_create_partition) (p. 486)
• UpdatePartition Action (Python: update_partition) (p. 487)
• DeletePartition Action (Python: delete_partition) (p. 487)
• BatchDeletePartition Action (Python: batch_delete_partition) (p. 488)
• GetPartition Action (Python: get_partition) (p. 489)
• GetPartitions Action (Python: get_partitions) (p. 489)
• BatchGetPartition Action (Python: batch_get_partition) (p. 492)
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
485
AWS Glue Developer Guide
Partitions
Response
• No Response parameters.
Errors
• InvalidInputException
• AlreadyExistsException
• ResourceNumberLimitExceededException
• InternalServiceException
• EntityNotFoundException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the catalog in which the partition is to be created. Currently, this should be the AWS account
ID.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
Errors
• InvalidInputException
• AlreadyExistsException
486
AWS Glue Developer Guide
Partitions
• ResourceNumberLimitExceededException
• InternalServiceException
• EntityNotFoundException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the partition to be updated resides. If none is provided, the AWS
account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the catalog database in which the table in question resides.
• TableName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
487
AWS Glue Developer Guide
Partitions
The ID of the Data Catalog where the partition to be deleted resides. If none is provided, the AWS
account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the catalog database in which the table in question resides.
• TableName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the partition to be deleted resides. If none is provided, the AWS
account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the catalog database in which the table in question resides.
• TableName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
488
AWS Glue Developer Guide
Partitions
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the partition in question resides. If none is provided, the AWS
account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
489
AWS Glue Developer Guide
Partitions
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the partitions in question reside. If none is provided, the AWS
account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The expression uses SQL syntax similar to the SQL WHERE filter clause. The SQL statement parser
JSQLParser parses the expression.
Operators: The following are the operators that you can use in the Expression API call:
=
Checks whether the values of the two operands are equal; if yes, then the condition becomes true.
Example: Assume 'variable a' holds 10 and 'variable b' holds 20.
(a = b) is not true.
<>
Checks whether the values of two operands are equal; if the values are not equal, then the
condition becomes true.
Checks whether the value of the left operand is greater than the value of the right operand; if yes,
then the condition becomes true.
Checks whether the value of the left operand is less than the value of the right operand; if yes,
then the condition becomes true.
Checks whether the value of the left operand is greater than or equal to the value of the right
operand; if yes, then the condition becomes true.
490
AWS Glue Developer Guide
Partitions
<=
Checks whether the value of the left operand is less than or equal to the value of the right
operand; if yes, then the condition becomes true.
Logical operators.
Supported Partition Key Types: The following are the supported partition keys.
• string
• date
• timestamp
• int
• bigint
• long
• tinyint
• smallint
• decimal
The following list shows the valid operators on each type. When you define a crawler, the
partitionKey type is created as a STRING, to be compatible with the catalog partitions.
Example
year = 2015
year = 2016
year = 2017
Example
Example
Example
Get partition year between 2015 and 2018 (inclusive). The following API calls are equivalent to each
491
other:
AWS Glue Developer Guide
Partitions
Example
A wildcard partition filter, where the following call output is partition year=2017. A regular expression
is not supported in LIKE.
A continuation token, if this is not the first call to retrieve these partitions.
• Segment – A Segment (p. 484) object.
Response
A continuation token, if the returned list of partitions does not include the last one.
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
492
AWS Glue Developer Guide
Connections
The ID of the Data Catalog where the partitions in question reside. If none is supplied, the AWS
account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
A list of the partition values in the request for which partitions were not returned.
Errors
• InvalidInputException
• EntityNotFoundException
• OperationTimeoutException
• InternalServiceException
• GlueEncryptionException
Connection API
The Connection API describes AWS Glue connection data types, and the API for creating, deleting,
updating, and listing connections.
Data Types
• Connection Structure (p. 493)
• ConnectionInput Structure (p. 495)
• PhysicalConnectionRequirements Structure (p. 496)
• GetConnectionsFilter Structure (p. 496)
Connection Structure
Defines a connection to a data source.
493
AWS Glue Developer Guide
Connections
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The type of the connection. Currently, only JDBC is supported; SFTP is not supported.
• MatchCriteria – An array of UTF-8 strings, not more than 10 strings.
Each key is a UTF-8 string (valid values: HOST | PORT | USERNAME="USER_NAME" | PASSWORD |
ENCRYPTED_PASSWORD | JDBC_DRIVER_JAR_URI | JDBC_DRIVER_CLASS_NAME | JDBC_ENGINE
| JDBC_ENGINE_VERSION | CONFIG_FILES | INSTANCE_ID | JDBC_CONNECTION_URL |
JDBC_ENFORCE_SSL | CUSTOM_JDBC_CERT | SKIP_CUSTOM_JDBC_CERT_VALIDATION |
CUSTOM_JDBC_CERT_STRING).
Each value is a Value string, not more than 1024 bytes long.
A map of physical connection requirements, such as virtual private cloud (VPC) and SecurityGroup,
that are needed to make this connection successfully.
• CreationTime – Timestamp.
The user, group, or role that last updated this connection definition.
ConnectionInput Structure
A structure that is used to specify a connection to create or update.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The type of the connection. Currently, only JDBC is supported; SFTP is not supported.
• MatchCriteria – An array of UTF-8 strings, not more than 10 strings.
Each key is a UTF-8 string (valid values: HOST | PORT | USERNAME="USER_NAME" | PASSWORD |
ENCRYPTED_PASSWORD | JDBC_DRIVER_JAR_URI | JDBC_DRIVER_CLASS_NAME | JDBC_ENGINE
| JDBC_ENGINE_VERSION | CONFIG_FILES | INSTANCE_ID | JDBC_CONNECTION_URL |
JDBC_ENFORCE_SSL | CUSTOM_JDBC_CERT | SKIP_CUSTOM_JDBC_CERT_VALIDATION |
CUSTOM_JDBC_CERT_STRING).
Each value is a Value string, not more than 1024 bytes long.
A map of physical connection requirements, such as virtual private cloud (VPC) and SecurityGroup,
that are needed to successfully make this connection.
495
AWS Glue Developer Guide
Connections
PhysicalConnectionRequirements Structure
Specifies the physical requirements for a connection.
Fields
• SubnetId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The connection's Availability Zone. This field is redundant because the specified subnet implies the
Availability Zone to be used. Currently the field must be populated, but it will be deprecated in the
future.
GetConnectionsFilter Structure
Filters the connection definitions that are returned by the GetConnections API operation.
Fields
A criteria string that must match the criteria recorded in the connection definition for that connection
definition to be returned.
• ConnectionType – UTF-8 string (valid values: JDBC | SFTP).
The type of connections to return. Currently, only JDBC is supported; SFTP is not supported.
Operations
• CreateConnection Action (Python: create_connection) (p. 496)
• DeleteConnection Action (Python: delete_connection) (p. 497)
• GetConnection Action (Python: get_connection) (p. 497)
• GetConnections Action (Python: get_connections) (p. 498)
• UpdateConnection Action (Python: update_connection) (p. 499)
• BatchDeleteConnection Action (Python: batch_delete_connection) (p. 499)
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which to create the connection. If none is provided, the AWS account ID
is used by default.
496
AWS Glue Developer Guide
Connections
Response
• No Response parameters.
Errors
• AlreadyExistsException
• InvalidInputException
• OperationTimeoutException
• ResourceNumberLimitExceededException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which the connection resides. If none is provided, the AWS account ID is
used by default.
• ConnectionName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• OperationTimeoutException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which the connection resides. If none is provided, the AWS account ID is
used by default.
497
AWS Glue Developer Guide
Connections
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Allows you to retrieve the connection metadata without returning the password. For instance, the
AWS Glue console uses this flag to retrieve the connection, and does not display the password. Set
this parameter when the caller might not have permission to use the AWS KMS key to decrypt the
password, but it does have permission to access the rest of the connection properties.
Response
Errors
• EntityNotFoundException
• OperationTimeoutException
• InvalidInputException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which the connections reside. If none is provided, the AWS account ID is
used by default.
• Filter – A GetConnectionsFilter (p. 496) object.
Allows you to retrieve the connection metadata without returning the password. For instance, the
AWS Glue console uses this flag to retrieve the connection, and does not display the password. Set
this parameter when the caller might not have permission to use the AWS KMS key to decrypt the
password, but it does have permission to access the rest of the connection properties.
• NextToken – UTF-8 string.
Response
498
AWS Glue Developer Guide
Connections
A continuation token, if the list of connections returned does not include the last of the filtered
connections.
Errors
• EntityNotFoundException
• OperationTimeoutException
• InvalidInputException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which the connection resides. If none is provided, the AWS account ID is
used by default.
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• No Response parameters.
Errors
• InvalidInputException
• EntityNotFoundException
• OperationTimeoutException
• InvalidInputException
• GlueEncryptionException
499
AWS Glue Developer Guide
User-Defined Functions
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which the connections reside. If none is provided, the AWS account ID is
used by default.
• ConnectionNameList – Required: An array of UTF-8 strings, not more than 25 strings.
Response
Each key is a UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
A map of the names of connections that were not successfully deleted to error details.
Errors
• InternalServiceException
• OperationTimeoutException
Data Types
• UserDefinedFunction Structure (p. 500)
• UserDefinedFunctionInput Structure (p. 501)
UserDefinedFunction Structure
Represents the equivalent of a Hive user-defined function (UDF) definition.
Fields
• FunctionName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
500
AWS Glue Developer Guide
User-Defined Functions
• OwnerName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
UserDefinedFunctionInput Structure
A structure used to create or update a user-defined function.
Fields
• FunctionName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Operations
• CreateUserDefinedFunction Action (Python: create_user_defined_function) (p. 501)
• UpdateUserDefinedFunction Action (Python: update_user_defined_function) (p. 502)
• DeleteUserDefinedFunction Action (Python: delete_user_defined_function) (p. 503)
• GetUserDefinedFunction Action (Python: get_user_defined_function) (p. 503)
• GetUserDefinedFunctions Action (Python: get_user_defined_functions) (p. 504)
501
AWS Glue Developer Guide
User-Defined Functions
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog in which to create the function. If none is provided, the AWS account ID is
used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
A FunctionInput object that defines the function to create in the Data Catalog.
Response
• No Response parameters.
Errors
• AlreadyExistsException
• InvalidInputException
• InternalServiceException
• EntityNotFoundException
• OperationTimeoutException
• ResourceNumberLimitExceededException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the function to be updated is located. If none is provided, the AWS
account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the catalog database where the function to be updated is located.
• FunctionName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
502
AWS Glue Developer Guide
User-Defined Functions
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the function to be deleted is located. If none is supplied, the AWS
account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
503
AWS Glue Developer Guide
User-Defined Functions
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the function to be retrieved is located. If none is provided, the AWS
account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• GlueEncryptionException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the Data Catalog where the functions to be retrieved are located. If none is provided, the
AWS account ID is used by default.
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the catalog database where the functions are located.
• Pattern – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-
line string pattern (p. 612).
An optional function-name pattern string that filters the function definitions returned.
• NextToken – UTF-8 string.
504
AWS Glue Developer Guide
Importing an Athena Catalog
Response
A continuation token, if the list of functions returned does not include the last requested function.
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
• GlueEncryptionException
Data Types
• CatalogImportStatus Structure (p. 505)
CatalogImportStatus Structure
A structure containing migration status information.
Fields
• ImportCompleted – Boolean.
Operations
• ImportCatalogToGlue Action (Python: import_catalog_to_glue) (p. 506)
• GetCatalogImportStatus Action (Python: get_catalog_import_status) (p. 506)
505
AWS Glue Developer Guide
Crawlers and Classifiers
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the catalog to import. Currently, this should be the AWS account ID.
Response
• No Response parameters.
Errors
• InternalServiceException
• OperationTimeoutException
Request
• CatalogId – Catalog id string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the catalog to migrate. Currently, this should be the AWS account ID.
Response
Errors
• InternalServiceException
• OperationTimeoutException
Topics
• Classifier API (p. 507)
506
AWS Glue Developer Guide
Classifiers
Classifier API
The Classifier API describes AWS Glue classifier data types, and includes the API for creating, deleting,
updating, and listing classifiers.
Data Types
• Classifier Structure (p. 507)
• GrokClassifier Structure (p. 508)
• XMLClassifier Structure (p. 508)
• JsonClassifier Structure (p. 509)
• CsvClassifier Structure (p. 509)
• CreateGrokClassifierRequest Structure (p. 510)
• UpdateGrokClassifierRequest Structure (p. 510)
• CreateXMLClassifierRequest Structure (p. 511)
• UpdateXMLClassifierRequest Structure (p. 511)
• CreateJsonClassifierRequest Structure (p. 511)
• UpdateJsonClassifierRequest Structure (p. 512)
• CreateCsvClassifierRequest Structure (p. 512)
• UpdateCsvClassifierRequest Structure (p. 513)
Classifier Structure
Classifiers are triggered during a crawl task. A classifier checks whether a given file is in a format it can
handle. If it is, the classifier creates a schema in the form of a StructType object that matches that data
format.
You can use the standard classifiers that AWS Glue provides, or you can write your own classifiers to best
categorize your data sources and specify the appropriate schemas to use for them. A classifier can be a
grok classifier, an XML classifier, a JSON classifier, or a custom CSV classifier, as specified in one of the
fields in the Classifier object.
Fields
507
AWS Glue Developer Guide
Classifiers
GrokClassifier Structure
A classifier that uses grok patterns.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
An identifier of the data format that the classifier matches, such as Twitter, JSON, Omniture logs, and
so on.
• CreationTime – Timestamp.
The grok pattern applied to a data store by this classifier. For more information, see built-in patterns in
Writing Custom Classifiers.
• CustomPatterns – UTF-8 string, not more than 16000 bytes long, matching the URI address multi-
line string pattern (p. 612).
Optional custom grok patterns defined by this classifier. For more information, see custom patterns in
Writing Custom Classifiers.
XMLClassifier Structure
A classifier for XML content.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
508
AWS Glue Developer Guide
Classifiers
The XML tag designating the element that contains each record in an XML document being parsed.
This can't identify a self-closing element (closed by />). An empty row element that contains only
attributes can be parsed as long as it ends with a closing tag (for example, <row item_a="A"
item_b="B"></row> is okay, but <row item_a="A" item_b="B" /> is not).
JsonClassifier Structure
A classifier for JSON content.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
A JsonPath string defining the JSON data for the classifier to classify. AWS Glue supports a subset of
JsonPath, as described in Writing JsonPath Custom Classifiers.
CsvClassifier Structure
A classifier for custom CSV content.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
509
AWS Glue Developer Guide
Classifiers
A custom symbol to denote what separates each column entry in the row.
• QuoteSymbol – UTF-8 string, not less than 1 or more than 1 bytes long, matching the Custom string
pattern #10 (p. 612).
A custom symbol to denote what combines content into a single column value. It must be different
from the column delimiter.
• ContainsHeader – UTF-8 string (valid values: UNKNOWN | PRESENT | ABSENT).
Specifies not to trim values before identifying the type of column values. The default value is true.
• AllowSingleColumn – Boolean.
CreateGrokClassifierRequest Structure
Specifies a grok classifier for CreateClassifier to create.
Fields
An identifier of the data format that the classifier matches, such as Twitter, JSON, Omniture logs,
Amazon CloudWatch Logs, and so on.
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
UpdateGrokClassifierRequest Structure
Specifies a grok classifier to update when passed to UpdateClassifier.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
510
AWS Glue Developer Guide
Classifiers
An identifier of the data format that the classifier matches, such as Twitter, JSON, Omniture logs,
Amazon CloudWatch Logs, and so on.
• GrokPattern – UTF-8 string, not less than 1 or more than 2048 bytes long, matching the A Logstash
Grok string pattern (p. 612).
CreateXMLClassifierRequest Structure
Specifies an XML classifier for CreateClassifier to create.
Fields
The XML tag designating the element that contains each record in an XML document being parsed.
This can't identify a self-closing element (closed by />). An empty row element that contains only
attributes can be parsed as long as it ends with a closing tag (for example, <row item_a="A"
item_b="B"></row> is okay, but <row item_a="A" item_b="B" /> is not).
UpdateXMLClassifierRequest Structure
Specifies an XML classifier to be updated.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The XML tag designating the element that contains each record in an XML document being parsed.
This cannot identify a self-closing element (closed by />). An empty row element that contains
only attributes can be parsed as long as it ends with a closing tag (for example, <row item_a="A"
item_b="B"></row> is okay, but <row item_a="A" item_b="B" /> is not).
CreateJsonClassifierRequest Structure
Specifies a JSON classifier for CreateClassifier to create.
511
AWS Glue Developer Guide
Classifiers
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
A JsonPath string defining the JSON data for the classifier to classify. AWS Glue supports a subset of
JsonPath, as described in Writing JsonPath Custom Classifiers.
UpdateJsonClassifierRequest Structure
Specifies a JSON classifier to be updated.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
A JsonPath string defining the JSON data for the classifier to classify. AWS Glue supports a subset of
JsonPath, as described in Writing JsonPath Custom Classifiers.
CreateCsvClassifierRequest Structure
Specifies a custom CSV classifier for CreateClassifier to create.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
A custom symbol to denote what separates each column entry in the row.
• QuoteSymbol – UTF-8 string, not less than 1 or more than 1 bytes long, matching the Custom string
pattern #10 (p. 612).
A custom symbol to denote what combines content into a single column value. Must be different from
the column delimiter.
• ContainsHeader – UTF-8 string (valid values: UNKNOWN | PRESENT | ABSENT).
Specifies not to trim values before identifying the type of column values. The default value is true.
512
AWS Glue Developer Guide
Classifiers
• AllowSingleColumn – Boolean.
UpdateCsvClassifierRequest Structure
Specifies a custom CSV classifier to be updated.
Fields
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
A custom symbol to denote what separates each column entry in the row.
• QuoteSymbol – UTF-8 string, not less than 1 or more than 1 bytes long, matching the Custom string
pattern #10 (p. 612).
A custom symbol to denote what combines content into a single column value. It must be different
from the column delimiter.
• ContainsHeader – UTF-8 string (valid values: UNKNOWN | PRESENT | ABSENT).
Specifies not to trim values before identifying the type of column values. The default value is true.
• AllowSingleColumn – Boolean.
Operations
• CreateClassifier Action (Python: create_classifier) (p. 513)
• DeleteClassifier Action (Python: delete_classifier) (p. 514)
• GetClassifier Action (Python: get_classifier) (p. 514)
• GetClassifiers Action (Python: get_classifiers) (p. 515)
• UpdateClassifier Action (Python: update_classifier) (p. 515)
Request
513
AWS Glue Developer Guide
Classifiers
Response
• No Response parameters.
Errors
• AlreadyExistsException
• InvalidInputException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
514
AWS Glue Developer Guide
Classifiers
Response
Errors
• EntityNotFoundException
• OperationTimeoutException
Request
Response
A continuation token.
Errors
• OperationTimeoutException
Request
515
AWS Glue Developer Guide
Crawlers
Response
• No Response parameters.
Errors
• InvalidInputException
• VersionMismatchException
• EntityNotFoundException
• OperationTimeoutException
Crawler API
The Crawler API describes AWS Glue crawler data types, along with the API for creating, deleting,
updating, and listing crawlers.
Data Types
• Crawler Structure (p. 516)
• Schedule Structure (p. 517)
• CrawlerTargets Structure (p. 518)
• S3Target Structure (p. 518)
• JdbcTarget Structure (p. 518)
• DynamoDBTarget Structure (p. 519)
• CatalogTarget Structure (p. 519)
• CrawlerMetrics Structure (p. 519)
• SchemaChangePolicy Structure (p. 520)
• LastCrawlInfo Structure (p. 520)
Crawler Structure
Specifies a crawler program that examines a data source and uses classifiers to try to determine its
schema. If successful, the crawler records metadata concerning the data source in the AWS Glue Data
Catalog.
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The Amazon Resource Name (ARN) of an IAM role that's used to access customer resources, such as
Amazon Simple Storage Service (Amazon S3) data.
• Targets – A CrawlerTargets (p. 518) object.
516
AWS Glue Developer Guide
Crawlers
A list of UTF-8 strings that specify the custom classifiers that are associated with the crawler.
• SchemaChangePolicy – A SchemaChangePolicy (p. 520) object.
The policy that specifies update and delete behaviors for the crawler.
• State – UTF-8 string (valid values: READY | RUNNING | STOPPING).
If the crawler is running, contains the total time elapsed since the last crawl began.
• CreationTime – Timestamp.
The status of the last crawl, and potentially error information if an error occurred.
• Version – Number (long).
Crawler configuration information. This versioned JSON string allows users to specify aspects of a
crawler's behavior. For more information, see Configuring a Crawler.
• CrawlerSecurityConfiguration – UTF-8 string, not more than 128 bytes long.
Schedule Structure
A scheduling object using a cron statement to schedule an event.
Fields
517
AWS Glue Developer Guide
Crawlers
A cron expression used to specify the schedule (see Time-Based Schedules for Jobs and Crawlers. For
example, to run something every day at 12:15 UTC, you would specify: cron(15 12 * * ? *).
• State – UTF-8 string (valid values: SCHEDULED | NOT_SCHEDULED | TRANSITIONING).
CrawlerTargets Structure
Specifies data stores to crawl.
Fields
S3Target Structure
Specifies a data store in Amazon Simple Storage Service (Amazon S3).
Fields
A list of glob patterns used to exclude from the crawl. For more information, see Catalog Tables with a
Crawler.
JdbcTarget Structure
Specifies a JDBC data store to crawl.
Fields
518
AWS Glue Developer Guide
Crawlers
A list of glob patterns used to exclude from the crawl. For more information, see Catalog Tables with a
Crawler.
DynamoDBTarget Structure
Specifies an Amazon DynamoDB table to crawl.
Fields
CatalogTarget Structure
Specifies an AWS Glue Data Catalog target.
Fields
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
CrawlerMetrics Structure
Metrics for a specified crawler.
Fields
• CrawlerName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
True if the crawler is still estimating how long it will take to complete this run.
• LastRuntimeSeconds – Number (double), not more than None.
519
AWS Glue Developer Guide
Crawlers
SchemaChangePolicy Structure
A policy that specifies update and deletion behaviors for the crawler.
Fields
LastCrawlInfo Structure
Status and error information about the most recent crawl.
Fields
Operations
• CreateCrawler Action (Python: create_crawler) (p. 521)
• DeleteCrawler Action (Python: delete_crawler) (p. 522)
• GetCrawler Action (Python: get_crawler) (p. 522)
520
AWS Glue Developer Guide
Crawlers
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The IAM role or Amazon Resource Name (ARN) of an IAM role used by the new crawler to access
customer resources.
• DatabaseName – UTF-8 string.
The AWS Glue database where results are written, such as: arn:aws:daylight:us-
east-1::database/sometable/*.
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
A cron expression used to specify the schedule (see Time-Based Schedules for Jobs and Crawlers. For
example, to run something every day at 12:15 UTC, you would specify: cron(15 12 * * ? *).
• Classifiers – An array of UTF-8 strings.
A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in
a crawl, but these custom classifiers always override the default classifiers for a given classification.
• TablePrefix – UTF-8 string, not more than 128 bytes long.
The table prefix used for catalog tables that are created.
• SchemaChangePolicy – A SchemaChangePolicy (p. 520) object.
Crawler configuration information. This versioned JSON string allows users to specify aspects of a
crawler's behavior. For more information, see Configuring a Crawler.
• CrawlerSecurityConfiguration – UTF-8 string, not more than 128 bytes long.
521
AWS Glue Developer Guide
Crawlers
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
The tags to use with this crawler request. You may use tags to limit access to the crawler. For more
information about tags in AWS Glue, see AWS Tags in AWS Glue in the developer guide.
Response
• No Response parameters.
Errors
• InvalidInputException
• AlreadyExistsException
• OperationTimeoutException
• ResourceNumberLimitExceededException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• CrawlerRunningException
• SchedulerTransitioningException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
522
AWS Glue Developer Guide
Crawlers
Response
Errors
• EntityNotFoundException
• OperationTimeoutException
Request
Response
A continuation token, if the returned list has not reached the end of those defined in this customer
account.
Errors
• OperationTimeoutException
Request
523
AWS Glue Developer Guide
Crawlers
Response
A continuation token, if the returned list does not contain the last metric available.
Errors
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The IAM role or Amazon Resource Name (ARN) of an IAM role that is used by the new crawler to access
customer resources.
• DatabaseName – UTF-8 string.
The AWS Glue database where results are stored, such as: arn:aws:daylight:us-
east-1::database/sometable/*.
• Description – UTF-8 string, not more than 2048 bytes long, matching the URI address multi-line
string pattern (p. 612).
A cron expression used to specify the schedule (see Time-Based Schedules for Jobs and Crawlers. For
example, to run something every day at 12:15 UTC, you would specify: cron(15 12 * * ? *).
• Classifiers – An array of UTF-8 strings.
A list of custom classifiers that the user has registered. By default, all built-in classifiers are included in
a crawl, but these custom classifiers always override the default classifiers for a given classification.
• TablePrefix – UTF-8 string, not more than 128 bytes long.
The table prefix used for catalog tables that are created.
• SchemaChangePolicy – A SchemaChangePolicy (p. 520) object.
524
AWS Glue Developer Guide
Crawlers
Crawler configuration information. This versioned JSON string allows users to specify aspects of a
crawler's behavior. For more information, see Configuring a Crawler.
• CrawlerSecurityConfiguration – UTF-8 string, not more than 128 bytes long.
Response
• No Response parameters.
Errors
• InvalidInputException
• VersionMismatchException
• EntityNotFoundException
• CrawlerRunningException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• CrawlerRunningException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
525
AWS Glue Developer Guide
Crawlers
Response
• No Response parameters.
Errors
• EntityNotFoundException
• CrawlerNotRunningException
• CrawlerStoppingException
• OperationTimeoutException
Request
• CrawlerNames – Required: An array of UTF-8 strings, not more than 100 strings.
A list of crawler names, which might be the names returned from the ListCrawlers operation.
Response
Errors
• InvalidInputException
• OperationTimeoutException
This operation takes the optional Tags field, which you can use as a filter on the response so that tagged
resources can be retrieved as a group. If you choose to use tags filtering, only resources with the tag are
retrieved.
Request
526
AWS Glue Developer Guide
Scheduler
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
Response
The names of all crawlers in the account, or the crawlers with the specified tags.
• NextToken – UTF-8 string.
A continuation token, if the returned list does not contain the last metric available.
Errors
• OperationTimeoutException
Data Types
• Schedule Structure (p. 527)
Schedule Structure
A scheduling object using a cron statement to schedule an event.
Fields
A cron expression used to specify the schedule (see Time-Based Schedules for Jobs and Crawlers. For
example, to run something every day at 12:15 UTC, you would specify: cron(15 12 * * ? *).
• State – UTF-8 string (valid values: SCHEDULED | NOT_SCHEDULED | TRANSITIONING).
Operations
• UpdateCrawlerSchedule Action (Python: update_crawler_schedule) (p. 528)
• StartCrawlerSchedule Action (Python: start_crawler_schedule) (p. 528)
527
AWS Glue Developer Guide
Scheduler
Request
• CrawlerName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The updated cron expression used to specify the schedule (see Time-Based Schedules for Jobs and
Crawlers. For example, to run something every day at 12:15 UTC, you would specify: cron(15 12 *
* ? *).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InvalidInputException
• VersionMismatchException
• SchedulerTransitioningException
• OperationTimeoutException
Request
• CrawlerName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• SchedulerRunningException
528
AWS Glue Developer Guide
Autogenerating ETL Scripts
• SchedulerTransitioningException
• NoScheduleException
• OperationTimeoutException
Request
• CrawlerName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• No Response parameters.
Errors
• EntityNotFoundException
• SchedulerNotRunningException
• SchedulerTransitioningException
• OperationTimeoutException
Data Types
• CodeGenNode Structure (p. 529)
• CodeGenNodeArg Structure (p. 530)
• CodeGenEdge Structure (p. 530)
• Location Structure (p. 530)
• CatalogEntry Structure (p. 531)
• MappingEntry Structure (p. 531)
CodeGenNode Structure
Represents a node in a directed acyclic graph (DAG)
Fields
• Id – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Identifier string
pattern (p. 612).
529
AWS Glue Developer Guide
CodeGenNodeArg
CodeGenNodeArg Structure
An argument or property of a node.
Fields
CodeGenEdge Structure
Represents a directional edge in a directed acyclic graph (DAG).
Fields
• Source – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Identifier
string pattern (p. 612).
Location Structure
The location of resources.
Fields
• Jdbc – An array of CodeGenNodeArg (p. 530) objects, not more than 50 structures.
A JDBC location.
530
AWS Glue Developer Guide
CatalogEntry
CatalogEntry Structure
Specifies a table definition in the AWS Glue Data Catalog.
Fields
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
MappingEntry Structure
Defines a mapping.
Fields
Operations
• CreateScript Action (Python: create_script) (p. 532)
• GetDataflowGraph Action (Python: get_dataflow_graph) (p. 532)
• GetMapping Action (Python: get_mapping) (p. 533)
531
AWS Glue Developer Guide
CreateScript (create_script)
Request
Response
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
Response
532
AWS Glue Developer Guide
GetMapping (get_mapping)
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
Response
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• EntityNotFoundException
Request
533
AWS Glue Developer Guide
Jobs
Response
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Jobs API
The Jobs API describes jobs data types and contains APIs for working with jobs, job runs, and triggers in
AWS Glue.
Topics
• Jobs (p. 534)
• Job Runs (p. 545)
• Triggers (p. 555)
Jobs
The Jobs API describes the data types and API related to creating, updating, deleting, or viewing jobs in
AWS Glue.
Data Types
• Job Structure (p. 534)
• ExecutionProperty Structure (p. 537)
• NotificationProperty Structure (p. 537)
• JobCommand Structure (p. 537)
• ConnectionsList Structure (p. 537)
• JobUpdate Structure (p. 537)
Job Structure
Specifies a job definition.
534
AWS Glue Developer Guide
Jobs
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The name or Amazon Resource Name (ARN) of the IAM role associated with this job.
• CreatedOn – Timestamp.
The time and date that this job definition was created.
• LastModifiedOn – Timestamp.
The last point in time when this job definition was modified.
• ExecutionProperty – An ExecutionProperty (p. 537) object.
An ExecutionProperty specifying the maximum number of concurrent runs allowed for this job.
• Command – A JobCommand (p. 537) object.
You can specify arguments here that your own job-execution script consumes, as well as arguments
that AWS Glue itself consumes.
For information about how to specify and consume your own Job arguments, see the Calling AWS Glue
APIs in Python topic in the developer guide.
For information about the key-value pairs that AWS Glue consumes to set up your job, see the Special
Parameters Used by AWS Glue topic in the developer guide.
• Connections – A ConnectionsList (p. 537) object.
The maximum number of times to retry this job after a JobRun fails.
• AllocatedCapacity – Number (integer).
The number of AWS Glue data processing units (DPUs) allocated to runs of this job. You can allocate
from 2 to 100 DPUs; the default is 10. A DPU is a relative measure of processing power that consists of
535
AWS Glue Developer Guide
Jobs
4 vCPUs of compute capacity and 16 GB of memory. For more information, see the AWS Glue pricing
page.
• Timeout – Number (integer), at least 1.
The job timeout in minutes. This is the maximum time that a job run can consume resources before it is
terminated and enters TIMEOUT status. The default is 2,880 minutes (48 hours).
• MaxCapacity – Number (double).
The number of AWS Glue data processing units (DPUs) that can be allocated when this job runs. A DPU
is a relative measure of processing power that consists of 4 vCPUs of compute capacity and 16 GB of
memory. For more information, see the AWS Glue pricing page.
The value that can be allocated for MaxCapacity depends on whether you are running a Python shell
job or an Apache Spark ETL job:
• When you specify a Python shell job (JobCommand.Name="pythonshell"), you can allocate either
0.0625 or 1 DPU. The default is 0.0625 DPU.
• When you specify an Apache Spark ETL job (JobCommand.Name="glueetl"), you can allocate from 2
to 100 DPUs. The default is 10 DPUs. This job type cannot have a fractional DPU allocation.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated when a job runs. Accepts a value of Standard, G.1X, or
G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker maps to 1 DPU (4 vCPU, 16 GB of memory, 64 GB disk), and
provides 1 executor per worker. We recommend this worker type for memory-intensive jobs.
• For the G.2X worker type, each worker maps to 2 DPU (8 vCPU, 32 GB of memory, 128 GB disk), and
provides 1 executor per worker. We recommend this worker type for memory-intensive jobs.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated when a job runs.
The maximum number of workers you can define are 299 for G.1X, and 149 for G.2X.
• SecurityConfiguration – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Glue version determines the versions of Apache Spark and Python that AWS Glue supports. The
Python version indicates the version supported for jobs of type Spark.
For more information about the available AWS Glue versions and corresponding Spark and Python
versions, see Glue version in the developer guide.
Jobs that are created without specifying a Glue version default to Glue 0.9.
536
AWS Glue Developer Guide
Jobs
ExecutionProperty Structure
An execution property of a job.
Fields
The maximum number of concurrent runs allowed for the job. The default is 1. An error is returned
when this threshold is reached. The maximum value you can specify is controlled by a service limit.
NotificationProperty Structure
Specifies configuration properties of a notification.
Fields
After a job run starts, the number of minutes to wait before sending a job run delay notification.
JobCommand Structure
Specifies code executed when a job is run.
Fields
The name of the job command. For an Apache Spark ETL job, this must be glueetl. For a Python shell
job, it must be pythonshell.
• ScriptLocation – UTF-8 string.
Specifies the Amazon Simple Storage Service (Amazon S3) path to a script that executes a job.
• PythonVersion – UTF-8 string, matching the Custom string pattern #11 (p. 612).
The Python version being used to execute a Python shell job. Allowed values are 2 or 3.
ConnectionsList Structure
Specifies the connections used by a job.
Fields
JobUpdate Structure
Specifies information used to update an existing job definition. The previous job definition is completely
overwritten by this information.
537
AWS Glue Developer Guide
Jobs
Fields
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
The name or Amazon Resource Name (ARN) of the IAM role associated with this job (required).
• ExecutionProperty – An ExecutionProperty (p. 537) object.
An ExecutionProperty specifying the maximum number of concurrent runs allowed for this job.
• Command – A JobCommand (p. 537) object.
You can specify arguments here that your own job-execution script consumes, as well as arguments
that AWS Glue itself consumes.
For information about how to specify and consume your own Job arguments, see the Calling AWS Glue
APIs in Python topic in the developer guide.
For information about the key-value pairs that AWS Glue consumes to set up your job, see the Special
Parameters Used by AWS Glue topic in the developer guide.
• Connections – A ConnectionsList (p. 537) object.
The number of AWS Glue data processing units (DPUs) to allocate to this job. You can allocate from
2 to 100 DPUs; the default is 10. A DPU is a relative measure of processing power that consists of 4
vCPUs of compute capacity and 16 GB of memory. For more information, see the AWS Glue pricing
page.
• Timeout – Number (integer), at least 1.
The job timeout in minutes. This is the maximum time that a job run can consume resources before it is
terminated and enters TIMEOUT status. The default is 2,880 minutes (48 hours).
• MaxCapacity – Number (double).
The number of AWS Glue data processing units (DPUs) that can be allocated when this job runs. A DPU
is a relative measure of processing power that consists of 4 vCPUs of compute capacity and 16 GB of
memory. For more information, see the AWS Glue pricing page.
538
AWS Glue Developer Guide
Jobs
The value that can be allocated for MaxCapacity depends on whether you are running a Python shell
job or an Apache Spark ETL job:
• When you specify a Python shell job (JobCommand.Name="pythonshell"), you can allocate either
0.0625 or 1 DPU. The default is 0.0625 DPU.
• When you specify an Apache Spark ETL job (JobCommand.Name="glueetl"), you can allocate from 2
to 100 DPUs. The default is 10 DPUs. This job type cannot have a fractional DPU allocation.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated when a job runs. Accepts a value of Standard, G.1X, or
G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker maps to 1 DPU (4 vCPU, 16 GB of memory, 64 GB disk), and
provides 1 executor per worker. We recommend this worker type for memory-intensive jobs.
• For the G.2X worker type, each worker maps to 2 DPU (8 vCPU, 32 GB of memory, 128 GB disk), and
provides 1 executor per worker. We recommend this worker type for memory-intensive jobs.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated when a job runs.
The maximum number of workers you can define are 299 for G.1X, and 149 for G.2X.
• SecurityConfiguration – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Glue version determines the versions of Apache Spark and Python that AWS Glue supports. The
Python version indicates the version supported for jobs of type Spark.
For more information about the available AWS Glue versions and corresponding Spark and Python
versions, see Glue version in the developer guide.
Operations
• CreateJob Action (Python: create_job) (p. 540)
• UpdateJob Action (Python: update_job) (p. 542)
• GetJob Action (Python: get_job) (p. 543)
• GetJobs Action (Python: get_jobs) (p. 543)
• DeleteJob Action (Python: delete_job) (p. 544)
• ListJobs Action (Python: list_jobs) (p. 544)
• BatchGetJobs Action (Python: batch_get_jobs) (p. 545)
539
AWS Glue Developer Guide
Jobs
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name you assign to this job definition. It must be unique in your account.
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
The name or Amazon Resource Name (ARN) of the IAM role associated with this job.
• ExecutionProperty – An ExecutionProperty (p. 537) object.
An ExecutionProperty specifying the maximum number of concurrent runs allowed for this job.
• Command – Required: A JobCommand (p. 537) object.
You can specify arguments here that your own job-execution script consumes, as well as arguments
that AWS Glue itself consumes.
For information about how to specify and consume your own Job arguments, see the Calling AWS Glue
APIs in Python topic in the developer guide.
For information about the key-value pairs that AWS Glue consumes to set up your job, see the Special
Parameters Used by AWS Glue topic in the developer guide.
• Connections – A ConnectionsList (p. 537) object.
The number of AWS Glue data processing units (DPUs) to allocate to this Job. You can allocate from
2 to 100 DPUs; the default is 10. A DPU is a relative measure of processing power that consists of 4
vCPUs of compute capacity and 16 GB of memory. For more information, see the AWS Glue pricing
page.
540
AWS Glue Developer Guide
Jobs
The job timeout in minutes. This is the maximum time that a job run can consume resources before it is
terminated and enters TIMEOUT status. The default is 2,880 minutes (48 hours).
• MaxCapacity – Number (double).
The number of AWS Glue data processing units (DPUs) that can be allocated when this job runs. A DPU
is a relative measure of processing power that consists of 4 vCPUs of compute capacity and 16 GB of
memory. For more information, see the AWS Glue pricing page.
The value that can be allocated for MaxCapacity depends on whether you are running a Python shell
job or an Apache Spark ETL job:
• When you specify a Python shell job (JobCommand.Name="pythonshell"), you can allocate either
0.0625 or 1 DPU. The default is 0.0625 DPU.
• When you specify an Apache Spark ETL job (JobCommand.Name="glueetl"), you can allocate from 2
to 100 DPUs. The default is 10 DPUs. This job type cannot have a fractional DPU allocation.
• SecurityConfiguration – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
The tags to use with this job. You may use tags to limit access to the job. For more information about
tags in AWS Glue, see AWS Tags in AWS Glue in the developer guide.
• NotificationProperty – A NotificationProperty (p. 537) object.
Glue version determines the versions of Apache Spark and Python that AWS Glue supports. The
Python version indicates the version supported for jobs of type Spark.
For more information about the available AWS Glue versions and corresponding Spark and Python
versions, see Glue version in the developer guide.
Jobs that are created without specifying a Glue version default to Glue 0.9.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated when a job runs.
The maximum number of workers you can define are 299 for G.1X, and 149 for G.2X.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated when a job runs. Accepts a value of Standard, G.1X, or
G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker maps to 1 DPU (4 vCPU, 16 GB of memory, 64 GB disk), and
provides 1 executor per worker. We recommend
541 this worker type for memory-intensive jobs.
AWS Glue Developer Guide
Jobs
• For the G.2X worker type, each worker maps to 2 DPU (8 vCPU, 32 GB of memory, 128 GB disk), and
provides 1 executor per worker. We recommend this worker type for memory-intensive jobs.
Response
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The unique name that was provided for this job definition.
Errors
• InvalidInputException
• IdempotentParameterMismatchException
• AlreadyExistsException
• InternalServiceException
• OperationTimeoutException
• ResourceNumberLimitExceededException
• ConcurrentModificationException
Request
• JobName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-
line string pattern (p. 612).
Response
• JobName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• ConcurrentModificationException
542
AWS Glue Developer Guide
Jobs
Request
• JobName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-
line string pattern (p. 612).
Response
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
Request
Response
A continuation token, if not all job definitions have yet been returned.
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
543
AWS Glue Developer Guide
Jobs
Request
• JobName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-
line string pattern (p. 612).
Response
• JobName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
This operation takes the optional Tags field, which you can use as a filter on the response so that tagged
resources can be retrieved as a group. If you choose to use tags filtering, only resources with the tag are
retrieved.
Request
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
Response
The names of all jobs in the account, or the jobs with the specified tags.
544
AWS Glue Developer Guide
Job Runs
A continuation token, if the returned list does not contain the last metric available.
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
Request
A list of job names, which might be the names returned from the ListJobs operation.
Response
Errors
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
Job Runs
The Jobs Runs API describes the data types and API related to starting, stopping, or viewing job runs, and
resetting job bookmarks, in AWS Glue.
Data Types
• JobRun Structure (p. 546)
• Predecessor Structure (p. 548)
• JobBookmarkEntry Structure (p. 548)
• BatchStopJobRunSuccessfulSubmission Structure (p. 549)
• BatchStopJobRunError Structure (p. 549)
545
AWS Glue Developer Guide
Job Runs
JobRun Structure
Contains information about a job run.
Fields
• Id – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The ID of the previous run of this job. For example, the JobRunId specified in the StartJobRun
action.
• TriggerName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The date and time at which this job run was started.
• LastModifiedOn – Timestamp.
The job arguments associated with this run. For this job run, they replace the default arguments set in
the job definition itself.
You can specify arguments here that your own job-execution script consumes, as well as arguments
that AWS Glue itself consumes.
For information about how to specify and consume your own job arguments, see the Calling AWS Glue
APIs in Python topic in the developer guide.
For information about the key-value pairs that AWS Glue consumes to set up your job, see the Special
Parameters Used by AWS Glue topic in the developer guide.
• ErrorMessage – UTF-8 string.
546
AWS Glue Developer Guide
Job Runs
The number of AWS Glue data processing units (DPUs) allocated to this JobRun. From 2 to 100 DPUs
can be allocated; the default is 10. A DPU is a relative measure of processing power that consists of
4 vCPUs of compute capacity and 16 GB of memory. For more information, see the AWS Glue pricing
page.
• ExecutionTime – Number (integer).
The amount of time (in seconds) that the job run consumed resources.
• Timeout – Number (integer), at least 1.
The JobRun timeout in minutes. This is the maximum time that a job run can consume resources
before it is terminated and enters TIMEOUT status. The default is 2,880 minutes (48 hours). This
overrides the timeout value set in the parent job.
• MaxCapacity – Number (double).
The number of AWS Glue data processing units (DPUs) that can be allocated when this job runs. A DPU
is a relative measure of processing power that consists of 4 vCPUs of compute capacity and 16 GB of
memory. For more information, see the AWS Glue pricing page.
The value that can be allocated for MaxCapacity depends on whether you are running a Python shell
job or an Apache Spark ETL job:
• When you specify a Python shell job (JobCommand.Name="pythonshell"), you can allocate either
0.0625 or 1 DPU. The default is 0.0625 DPU.
• When you specify an Apache Spark ETL job (JobCommand.Name="glueetl"), you can allocate from 2
to 100 DPUs. The default is 10 DPUs. This job type cannot have a fractional DPU allocation.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated when a job runs. Accepts a value of Standard, G.1X, or
G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker provides 4 vCPU, 16 GB of memory and a 64GB disk, and 1
executor per worker.
• For the G.2X worker type, each worker provides 8 vCPU, 32 GB of memory and a 128GB disk, and 1
executor per worker.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated when a job runs.
The maximum number of workers you can define are 299 for G.1X, and 149 for G.2X.
• SecurityConfiguration – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the SecurityConfiguration structure to be used with this job run.
• LogGroupName – UTF-8 string.
547
AWS Glue Developer Guide
Job Runs
The name of the log group for secure logging that can be server-side encrypted in Amazon
CloudWatch using AWS KMS. This name can be /aws-glue/jobs/, in which case the default
encryption is NONE. If you add a role name and SecurityConfiguration name (in other words,
/aws-glue/jobs-yourRoleName-yourSecurityConfigurationName/), then that security
configuration is used to encrypt the log group.
• NotificationProperty – A NotificationProperty (p. 537) object.
Glue version determines the versions of Apache Spark and Python that AWS Glue supports. The
Python version indicates the version supported for jobs of type Spark.
For more information about the available AWS Glue versions and corresponding Spark and Python
versions, see Glue version in the developer guide.
Jobs that are created without specifying a Glue version default to Glue 0.9.
Predecessor Structure
A job run that was used in the predicate of a conditional trigger that triggered this job run.
Fields
• JobName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The name of the job definition used by the predecessor job run.
• RunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
JobBookmarkEntry Structure
Defines a point that a job can resume processing.
Fields
548
AWS Glue Developer Guide
Job Runs
The unique run identifier associated with the previous job run.
• RunId – UTF-8 string.
BatchStopJobRunSuccessfulSubmission Structure
Records a successful request to stop a specified JobRun.
Fields
• JobName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The name of the job definition used in the job run that was stopped.
• JobRunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
BatchStopJobRunError Structure
Records an error that occurred when attempting to stop a specified job run.
Fields
• JobName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The name of the job definition that is used in the job run in question.
• JobRunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Operations
• StartJobRun Action (Python: start_job_run) (p. 550)
• BatchStopJobRun Action (Python: batch_stop_job_run) (p. 551)
• GetJobRun Action (Python: get_job_run) (p. 552)
• GetJobRuns Action (Python: get_job_runs) (p. 552)
• GetJobBookmark Action (Python: get_job_bookmark) (p. 553)
• GetJobBookmarks Action (Python: get_job_bookmarks) (p. 554)
• ResetJobBookmark Action (Python: reset_job_bookmark) (p. 554)
549
AWS Glue Developer Guide
Job Runs
Request
• JobName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-
line string pattern (p. 612).
The job arguments specifically for this run. For this job run, they replace the default arguments set in
the job definition itself.
You can specify arguments here that your own job-execution script consumes, as well as arguments
that AWS Glue itself consumes.
For information about how to specify and consume your own Job arguments, see the Calling AWS Glue
APIs in Python topic in the developer guide.
For information about the key-value pairs that AWS Glue consumes to set up your job, see the Special
Parameters Used by AWS Glue topic in the developer guide.
• AllocatedCapacity – Number (integer).
The number of AWS Glue data processing units (DPUs) to allocate to this JobRun. From 2 to 100 DPUs
can be allocated; the default is 10. A DPU is a relative measure of processing power that consists of
4 vCPUs of compute capacity and 16 GB of memory. For more information, see the AWS Glue pricing
page.
• Timeout – Number (integer), at least 1.
The JobRun timeout in minutes. This is the maximum time that a job run can consume resources
before it is terminated and enters TIMEOUT status. The default is 2,880 minutes (48 hours). This
overrides the timeout value set in the parent job.
• MaxCapacity – Number (double).
The number of AWS Glue data processing units (DPUs) that can be allocated when this job runs. A DPU
is a relative measure of processing power that consists of 4 vCPUs of compute capacity and 16 GB of
memory. For more information, see the AWS Glue pricing page.
The value that can be allocated for MaxCapacity depends on whether you are running a Python shell
job, or an Apache Spark ETL job:
• When you specify a Python shell job (JobCommand.Name="pythonshell"), you can allocate either
0.0625 or 1 DPU. The default is 0.0625 DPU.
• When you specify an Apache Spark ETL job (JobCommand.Name="glueetl"), you can allocate from 2
to 100 DPUs. The default is 10 DPUs. This job type cannot have a fractional DPU allocation.
550
AWS Glue Developer Guide
Job Runs
• SecurityConfiguration – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the SecurityConfiguration structure to be used with this job run.
• NotificationProperty – A NotificationProperty (p. 537) object.
The type of predefined worker that is allocated when a job runs. Accepts a value of Standard, G.1X, or
G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker provides 4 vCPU, 16 GB of memory and a 64GB disk, and 1
executor per worker.
• For the G.2X worker type, each worker provides 8 vCPU, 32 GB of memory and a 128GB disk, and 1
executor per worker.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated when a job runs.
The maximum number of workers you can define are 299 for G.1X, and 149 for G.2X.
Response
• JobRunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• ResourceNumberLimitExceededException
• ConcurrentRunsExceededException
Request
• JobName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-
line string pattern (p. 612).
The name of the job definition for which to stop job runs.
• JobRunIds – Required: An array of UTF-8 strings, not less than 1 or more than 25 strings.
A list of the JobRunIds that should be stopped for that job definition.
551
AWS Glue Developer Guide
Job Runs
Response
A list of the errors that were encountered in trying to stop JobRuns, including the JobRunId for
which each error was encountered and details about the error.
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
• JobName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-
line string pattern (p. 612).
Response
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
552
AWS Glue Developer Guide
Job Runs
Request
• JobName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-
line string pattern (p. 612).
The name of the job definition for which to retrieve all job runs.
• NextToken – UTF-8 string.
Response
A continuation token, if not all requested job runs have been returned.
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
Request
Response
Errors
• EntityNotFoundException
553
AWS Glue Developer Guide
Job Runs
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• ValidationException
Request
Response
A list of job bookmark entries that defines a point that a job can resume processing.
• NextToken – Number (integer).
A continuation token, which has a value of 1 if all the entries are returned, or > 1 if not all requested
job runs have been returned.
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
Request
554
AWS Glue Developer Guide
Triggers
Response
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Triggers
The Triggers API describes the data types and API related to creating, updating, or deleting, and starting
and stopping job triggers in AWS Glue.
Data Types
• Trigger Structure (p. 555)
• TriggerUpdate Structure (p. 556)
• Predicate Structure (p. 556)
• Condition Structure (p. 557)
• Action Structure (p. 557)
Trigger Structure
Information about a specific trigger.
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
555
AWS Glue Developer Guide
Triggers
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
A cron expression used to specify the schedule (see Time-Based Schedules for Jobs and Crawlers. For
example, to run something every day at 12:15 UTC, you would specify: cron(15 12 * * ? *).
• Actions – An array of Action (p. 557) objects.
TriggerUpdate Structure
A structure used to provide information used to update a trigger. This object updates the previous trigger
definition by overwriting it completely.
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
A cron expression used to specify the schedule (see Time-Based Schedules for Jobs and Crawlers. For
example, to run something every day at 12:15 UTC, you would specify: cron(15 12 * * ? *).
• Actions – An array of Action (p. 557) objects.
Predicate Structure
Defines the predicate of the trigger, which determines when it fires.
Fields
An optional field if only one condition is listed. If multiple conditions are listed, then this field is
required.
• Conditions – An array of Condition (p. 557) objects.
A list of the conditions that determine when the trigger will fire.
556
AWS Glue Developer Guide
Triggers
Condition Structure
Defines a condition under which a trigger fires.
Fields
A logical operator.
• JobName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The name of the job whose JobRuns this condition applies to, and on which this trigger waits.
• State – UTF-8 string (valid values: STARTING | RUNNING | STOPPING | STOPPED | SUCCEEDED |
FAILED | TIMEOUT).
The condition state. Currently, the values supported are SUCCEEDED, STOPPED, TIMEOUT, and FAILED.
• CrawlerName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Action Structure
Defines an action to be initiated by a trigger.
Fields
• JobName – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The job arguments used when this trigger fires. For this job run, they replace the default arguments set
in the job definition itself.
You can specify arguments here that your own job-execution script consumes, as well as arguments
that AWS Glue itself consumes.
For information about how to specify and consume your own Job arguments, see the Calling AWS Glue
APIs in Python topic in the developer guide.
For information about the key-value pairs that AWS Glue consumes to set up your job, see the Special
Parameters Used by AWS Glue topic in the developer guide.
• Timeout – Number (integer), at least 1.
The JobRun timeout in minutes. This is the maximum time that a job run can consume resources
before it is terminated and enters TIMEOUT status. The default is 2,880 minutes (48 hours). This
overrides the timeout value set in the parent job.
557
AWS Glue Developer Guide
Triggers
• SecurityConfiguration – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Operations
• CreateTrigger Action (Python: create_trigger) (p. 558)
• StartTrigger Action (Python: start_trigger) (p. 559)
• GetTrigger Action (Python: get_trigger) (p. 560)
• GetTriggers Action (Python: get_triggers) (p. 560)
• UpdateTrigger Action (Python: update_trigger) (p. 561)
• StopTrigger Action (Python: stop_trigger) (p. 561)
• DeleteTrigger Action (Python: delete_trigger) (p. 562)
• ListTriggers Action (Python: list_triggers) (p. 562)
• BatchGetTriggers Action (Python: batch_get_triggers) (p. 563)
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
A cron expression used to specify the schedule (see Time-Based Schedules for Jobs and Crawlers. For
example, to run something every day at 12:15 UTC, you would specify: cron(15 12 * * ? *).
558
AWS Glue Developer Guide
Triggers
Set to true to start SCHEDULED and CONDITIONAL triggers when created. True is not supported for
ON_DEMAND triggers.
• Tags – A map array of key-value pairs, not more than 50 pairs.
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
The tags to use with this trigger. You may use tags to limit access to the trigger. For more information
about tags in AWS Glue, see AWS Tags in AWS Glue in the developer guide.
Response
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Errors
• AlreadyExistsException
• EntityNotFoundException
• InvalidInputException
• IdempotentParameterMismatchException
• InternalServiceException
• OperationTimeoutException
• ResourceNumberLimitExceededException
• ConcurrentModificationException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
559
AWS Glue Developer Guide
Triggers
Errors
• InvalidInputException
• InternalServiceException
• EntityNotFoundException
• OperationTimeoutException
• ResourceNumberLimitExceededException
• ConcurrentRunsExceededException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
The name of the job to retrieve triggers for. The trigger that can start this job is returned, and if there
is no such trigger, all triggers are returned.
• MaxResults – Number (integer), not less than 1 or more than 1000.
560
AWS Glue Developer Guide
Triggers
Response
A continuation token, if not all the requested triggers have yet been returned.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
Errors
• InvalidInputException
• InternalServiceException
• EntityNotFoundException
• OperationTimeoutException
• ConcurrentModificationException
561
AWS Glue Developer Guide
Triggers
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Errors
• InvalidInputException
• InternalServiceException
• EntityNotFoundException
• OperationTimeoutException
• ConcurrentModificationException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• ConcurrentModificationException
562
AWS Glue Developer Guide
Triggers
This operation takes the optional Tags field, which you can use as a filter on the response so that tagged
resources can be retrieved as a group. If you choose to use tags filtering, only resources with the tag are
retrieved.
Request
The name of the job for which to retrieve triggers. The trigger that can start this job is returned. If
there is no such trigger, all triggers are returned.
• MaxResults – Number (integer), not less than 1 or more than 1000.
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
Response
The names of all triggers in the account, or the triggers with the specified tags.
• NextToken – UTF-8 string.
A continuation token, if the returned list does not contain the last metric available.
Errors
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
A list of trigger names, which may be the names returned from the ListTriggers operation.
563
AWS Glue Developer Guide
Workflows
Response
Errors
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
Workflows
The Workflows API describes the data types and API related to creating, updating, or viewing workflows
in AWS Glue.
Data Types
• JobNodeDetails Structure (p. 564)
• CrawlerNodeDetails Structure (p. 564)
• TriggerNodeDetails Structure (p. 565)
• Crawl Structure (p. 565)
• Node Structure (p. 565)
• Edge Structure (p. 566)
• WorkflowGraph Structure (p. 566)
• WorkflowRun Structure (p. 566)
• WorkflowRunStatistics Structure (p. 567)
• Workflow Structure (p. 568)
JobNodeDetails Structure
The details of a Job node present in the workflow.
Fields
The information for the job runs represented by the job node.
CrawlerNodeDetails Structure
The details of a Crawler node present in the workflow.
Fields
564
AWS Glue Developer Guide
TriggerNodeDetails
TriggerNodeDetails Structure
The details of a Trigger node present in the workflow.
Fields
Crawl Structure
The details of a crawl in the workflow.
Fields
Node Structure
A node represents an AWS Glue component like Trigger, Job etc. which is part of a workflow.
Fields
565
AWS Glue Developer Guide
Edge
Edge Structure
An edge represents a directed connection between two AWS Glue components which are part of the
workflow the edge belongs to.
Fields
• SourceId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The unique of the node within the workflow where the edge starts.
• DestinationId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The unique of the node within the workflow where the edge ends.
WorkflowGraph Structure
A workflow graph represents the complete workflow containing all the AWS Glue components present in
the workflow and all the directed connections between them.
Fields
A list of the the AWS Glue components belong to the workflow represented as nodes.
• Edges – An array of Edge (p. 566) objects.
A list of all the directed connections between the nodes belonging to the workflow.
WorkflowRun Structure
A workflow run is an execution of a workflow providing all the runtime information.
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
566
AWS Glue Developer Guide
WorkflowRunStatistics
Each key is a UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The workflow run properties which were set during the run.
• StartedOn – Timestamp.
The date and time when the workflow run was started.
• CompletedOn – Timestamp.
The graph representing all the AWS Glue components that belong to the workflow as nodes and
directed connections between them as edges.
WorkflowRunStatistics Structure
Workflow run statistics provides statistics about the workflow run.
Fields
567
AWS Glue Developer Guide
Workflow
Workflow Structure
A workflow represents a flow in which AWS Glue components should be executed to complete a logical
task.
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each key is a UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The date and time when the workflow was last modified.
• LastRun – A WorkflowRun (p. 566) object.
The graph representing all the AWS Glue components that belong to the workflow as nodes and
directed connections between them as edges.
• CreationStatus – UTF-8 string (valid values: CREATING | CREATED | CREATION_FAILED).
Operations
• CreateWorkflow Action (Python: create_workflow) (p. 569)
• UpdateWorkflow Action (Python: update_workflow) (p. 569)
• DeleteWorkflow Action (Python: delete_workflow) (p. 570)
• ListWorkflows Action (Python: list_workflows) (p. 571)
• BatchGetWorkflows Action (Python: batch_get_workflows) (p. 571)
• GetWorkflowRun Action (Python: get_workflow_run) (p. 572)
• GetWorkflowRuns Action (Python: get_workflow_runs) (p. 572)
• GetWorkflowRunProperties Action (Python: get_workflow_run_properties) (p. 573)
• PutWorkflowRunProperties Action (Python: put_workflow_run_properties) (p. 574)
568
AWS Glue Developer Guide
CreateWorkflow (create_workflow)
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The name to be assigned to the workflow. It should be unique within your account.
• Description – UTF-8 string.
Each key is a UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
Response
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The name of the workflow which was provided as part of the request.
Errors
• AlreadyExistsException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• ResourceNumberLimitExceededException
• ConcurrentModificationException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
569
AWS Glue Developer Guide
DeleteWorkflow (delete_workflow)
Each key is a UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Response
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• ConcurrentModificationException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
570
AWS Glue Developer Guide
ListWorkflows (list_workflows)
• ConcurrentModificationException
Request
Response
• Workflows – An array of UTF-8 strings, not less than 1 or more than 25 strings.
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
Request
• Names – Required: An array of UTF-8 strings, not less than 1 or more than 25 strings.
A list of workflow names, which may be the names returned from the ListWorkflows operation.
• IncludeGraph – Boolean.
Specifies whether to include a graph when returning the workflow resource metadata.
Response
• Workflows – An array of Workflow (p. 568) objects, not less than 1 or more than 25 structures.
571
AWS Glue Developer Guide
GetWorkflowRun (get_workflow_run)
Errors
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
572
AWS Glue Developer Guide
GetWorkflowRunProperties (get_workflow_run_properties)
• IncludeGraph – Boolean.
Response
• Runs – An array of WorkflowRun (p. 566) objects, not less than 1 or more than 1000 structures.
A continuation token, if not all requested workflow runs have been returned.
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Response
Each key is a UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The workflow run properties which were set during the specified run.
573
AWS Glue Developer Guide
PutWorkflowRunProperties (put_workflow_run_properties)
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The ID of the workflow run for which the run properties should be updated.
• RunProperties – Required: A map array of key-value pairs.
Each key is a UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
Response
• No Response parameters.
Errors
• AlreadyExistsException
• EntityNotFoundException
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• ResourceNumberLimitExceededException
• ConcurrentModificationException
574
AWS Glue Developer Guide
— data types —
Data Types
• DevEndpoint Structure (p. 575)
• DevEndpointCustomLibraries Structure (p. 577)
DevEndpoint Structure
A development endpoint where a developer can remotely debug extract, transform, and load (ETL)
scripts.
Fields
The Amazon Resource Name (ARN) of the IAM role used in this DevEndpoint.
• SecurityGroupIds – An array of UTF-8 strings.
A private IP address to access the DevEndpoint within a VPC if the DevEndpoint is created within
one. The PrivateAddress field is present only when you create the DevEndpoint within your VPC.
• ZeppelinRemoteSparkInterpreterPort – Number (integer).
The Apache Zeppelin port for the remote Apache Spark interpreter.
• PublicAddress – UTF-8 string.
The public IP address used by this DevEndpoint. The PublicAddress field is present only when you
create a non-virtual private cloud (VPC) DevEndpoint.
• Status – UTF-8 string.
The type of predefined worker that is allocated to the development endpoint. Accepts a value of
Standard, G.1X, or G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker maps to 1 DPU (4 vCPU, 16 GB of memory, 64 GB disk), and
provides 1 executor per worker. We recommend this worker type for memory-intensive jobs.
• For the G.2X worker type, each worker maps to 2 DPU (8 vCPU, 32 GB of memory, 128 GB disk), and
provides 1 executor per worker. We recommend this worker type for memory-intensive jobs.
Known issue: when a development endpoint is created with the G.2X WorkerType configuration, the
Spark drivers for the development endpoint will run on 4 vCPU, 16 GB of memory, and a 64 GB disk.
575
AWS Glue Developer Guide
DevEndpoint
• GlueVersion – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Custom
string pattern #13 (p. 612).
Glue version determines the versions of Apache Spark and Python that AWS Glue supports. The
Python version indicates the version supported for running your ETL scripts on development
endpoints.
For more information about the available AWS Glue versions and corresponding Spark and Python
versions, see Glue version in the developer guide.
Development endpoints that are created without specifying a Glue version default to Glue 0.9.
You can specify a version of Python support for development endpoints by using the Arguments
parameter in the CreateDevEndpoint or UpdateDevEndpoint APIs. If no arguments are provided,
the version defaults to Python 2.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated to the development endpoint.
The maximum number of workers you can define are 299 for G.1X, and 149 for G.2X.
• NumberOfNodes – Number (integer).
The number of AWS Glue Data Processing Units (DPUs) allocated to this DevEndpoint.
• AvailabilityZone – UTF-8 string.
The paths to one or more Python libraries in an Amazon S3 bucket that should be loaded in your
DevEndpoint. Multiple values must be complete paths separated by a comma.
Note
You can only use pure Python libraries with a DevEndpoint. Libraries that rely on C
extensions, such as the pandas Python data analysis library, are not currently supported.
• ExtraJarsS3Path – UTF-8 string.
The path to one or more Java .jar files in an S3 bucket that should be loaded in your DevEndpoint.
Note
You can only use pure Java/Scala libraries with a DevEndpoint.
• FailureReason – UTF-8 string.
The public key to be used by this DevEndpoint for authentication. This attribute is provided for
backward compatibility because the recommended attribute to use is public keys.
• PublicKeys – An array of UTF-8 strings, not more than 5 strings.
A list of public keys to be used by the DevEndpoints for authentication. Using this attribute is
preferred over a single public key because the public keys allow you to have a different private key per
client.
Note
If you previously created an endpoint with a public key, you must remove that key to be able
to set a list of public keys. Call the UpdateDevEndpoint API operation with the public key
content in the deletePublicKeys attribute, and the list of new keys in the addPublicKeys
attribute.
• SecurityConfiguration – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
You can specify a version of Python support for development endpoints by using the Arguments
parameter in the CreateDevEndpoint or UpdateDevEndpoint APIs. If no arguments are provided,
the version defaults to Python 2.
DevEndpointCustomLibraries Structure
Custom libraries to be loaded into a development endpoint.
Fields
The paths to one or more Python libraries in an Amazon Simple Storage Service (Amazon S3) bucket
that should be loaded in your DevEndpoint. Multiple values must be complete paths separated by a
comma.
Note
You can only use pure Python libraries with a DevEndpoint. Libraries that rely on C
extensions, such as the pandas Python data analysis library, are not currently supported.
• ExtraJarsS3Path – UTF-8 string.
The path to one or more Java .jar files in an S3 bucket that should be loaded in your DevEndpoint.
Note
You can only use pure Java/Scala libraries with a DevEndpoint.
577
AWS Glue Developer Guide
— operations —
Operations
• CreateDevEndpoint Action (Python: create_dev_endpoint) (p. 578)
• UpdateDevEndpoint Action (Python: update_dev_endpoint) (p. 581)
• DeleteDevEndpoint Action (Python: delete_dev_endpoint) (p. 582)
• GetDevEndpoint Action (Python: get_dev_endpoint) (p. 583)
• GetDevEndpoints Action (Python: get_dev_endpoints) (p. 583)
• BatchGetDevEndpoints Action (Python: batch_get_dev_endpoints) (p. 584)
• ListDevEndpoints Action (Python: list_dev_endpoints) (p. 585)
Request
Security group IDs for the security groups to be used by the new DevEndpoint.
• SubnetId – UTF-8 string.
The public key to be used by this DevEndpoint for authentication. This attribute is provided for
backward compatibility because the recommended attribute to use is public keys.
• PublicKeys – An array of UTF-8 strings, not more than 5 strings.
A list of public keys to be used by the development endpoints for authentication. The use of this
attribute is preferred over a single public key because the public keys allow you to have a different
private key per client.
Note
If you previously created an endpoint with a public key, you must remove that key to be able
to set a list of public keys. Call the UpdateDevEndpoint API with the public key content in
the deletePublicKeys attribute, and the list of new keys in the addPublicKeys attribute.
• NumberOfNodes – Number (integer).
The number of AWS Glue Data Processing Units (DPUs) to allocate to this DevEndpoint.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated to the development endpoint. Accepts a value of
Standard, G.1X, or G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
578
AWS Glue Developer Guide
CreateDevEndpoint (create_dev_endpoint)
• For the G.1X worker type, each worker maps to 1 DPU (4 vCPU, 16 GB of memory, 64 GB disk), and
provides 1 executor per worker. We recommend this worker type for memory-intensive jobs.
• For the G.2X worker type, each worker maps to 2 DPU (8 vCPU, 32 GB of memory, 128 GB disk), and
provides 1 executor per worker. We recommend this worker type for memory-intensive jobs.
Known issue: when a development endpoint is created with the G.2X WorkerType configuration, the
Spark drivers for the development endpoint will run on 4 vCPU, 16 GB of memory, and a 64 GB disk.
• GlueVersion – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Custom
string pattern #13 (p. 612).
Glue version determines the versions of Apache Spark and Python that AWS Glue supports. The
Python version indicates the version supported for running your ETL scripts on development
endpoints.
For more information about the available AWS Glue versions and corresponding Spark and Python
versions, see Glue version in the developer guide.
Development endpoints that are created without specifying a Glue version default to Glue 0.9.
You can specify a version of Python support for development endpoints by using the Arguments
parameter in the CreateDevEndpoint or UpdateDevEndpoint APIs. If no arguments are provided,
the version defaults to Python 2.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated to the development endpoint.
The maximum number of workers you can define are 299 for G.1X, and 149 for G.2X.
• ExtraPythonLibsS3Path – UTF-8 string.
The paths to one or more Python libraries in an Amazon S3 bucket that should be loaded in your
DevEndpoint. Multiple values must be complete paths separated by a comma.
Note
You can only use pure Python libraries with a DevEndpoint. Libraries that rely on C
extensions, such as the pandas Python data analysis library, are not yet supported.
• ExtraJarsS3Path – UTF-8 string.
The path to one or more Java .jar files in an S3 bucket that should be loaded in your DevEndpoint.
• SecurityConfiguration – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
The tags to use with this DevEndpoint. You may use tags to limit access to the DevEndpoint. For more
information about tags in AWS Glue, see AWS Tags in AWS Glue in the developer guide.
• Arguments – A map array of key-value pairs, not more than 100 pairs.
Response
The Amazon Resource Name (ARN) of the role assigned to the new DevEndpoint.
• YarnEndpointAddress – UTF-8 string.
The Apache Zeppelin port for the remote Apache Spark interpreter.
• NumberOfNodes – Number (integer).
The number of AWS Glue Data Processing Units (DPUs) allocated to this DevEndpoint.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated to the development endpoint. May be a value of
Standard, G.1X, or G.2X.
• GlueVersion – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Custom
string pattern #13 (p. 612).
Glue version determines the versions of Apache Spark and Python that AWS Glue supports. The
Python version indicates the version supported for running your ETL scripts on development
endpoints.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated to the development endpoint.
• AvailabilityZone – UTF-8 string.
The paths to one or more Python libraries in an S3 bucket that will be loaded in your DevEndpoint.
• ExtraJarsS3Path – UTF-8 string.
Path to one or more Java .jar files in an S3 bucket that will be loaded in your DevEndpoint.
• FailureReason – UTF-8 string.
• SecurityConfiguration – UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The name of the SecurityConfiguration structure being used with this DevEndpoint.
• CreatedTimestamp – Timestamp.
You can specify a version of Python support for development endpoints by using the Arguments
parameter in the CreateDevEndpoint or UpdateDevEndpoint APIs. If no arguments are provided,
the version defaults to Python 2.
Errors
• AccessDeniedException
• AlreadyExistsException
• IdempotentParameterMismatchException
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
• ValidationException
• ResourceNumberLimitExceededException
Request
581
AWS Glue Developer Guide
DeleteDevEndpoint (delete_dev_endpoint)
True if the list of custom libraries to be loaded in the development endpoint needs to be updated, or
False if otherwise.
• DeleteArguments – An array of UTF-8 strings.
The list of argument keys to be deleted from the map of arguments used to configure the
DevEndpoint.
• AddArguments – A map array of key-value pairs, not more than 100 pairs.
The map of arguments to add the map of arguments used to configure the DevEndpoint.
You can specify a version of Python support for development endpoints by using the Arguments
parameter in the CreateDevEndpoint or UpdateDevEndpoint APIs. If no arguments are provided,
the version defaults to Python 2.
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
• ValidationException
Request
582
AWS Glue Developer Guide
GetDevEndpoint (get_dev_endpoint)
Response
• No Response parameters.
Errors
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
Request
Response
A DevEndpoint definition.
Errors
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
Request
583
AWS Glue Developer Guide
BatchGetDevEndpoints (batch_get_dev_endpoints)
Response
A continuation token, if not all DevEndpoint definitions have yet been returned.
Errors
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
Request
The list of DevEndpoint names, which might be the names returned from the ListDevEndpoint
operation.
Response
Errors
• AccessDeniedException
584
AWS Glue Developer Guide
ListDevEndpoints (list_dev_endpoints)
• InternalServiceException
• OperationTimeoutException
• InvalidInputException
This operation takes the optional Tags field, which you can use as a filter on the response so that tagged
resources can be retrieved as a group. If you choose to use tags filtering, only resources with the tag are
retrieved.
Request
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
Response
The names of all the DevEndpoints in the account, or the DevEndpoints with the specified tags.
• NextToken – UTF-8 string.
A continuation token, if the returned list does not contain the last metric available.
Errors
• InvalidInputException
• EntityNotFoundException
• InternalServiceException
• OperationTimeoutException
585
AWS Glue Developer Guide
— data types —
Data Types
• TransformParameters Structure (p. 586)
• EvaluationMetrics Structure (p. 586)
• MLTransform Structure (p. 587)
• FindMatchesParameters Structure (p. 588)
• FindMatchesMetrics Structure (p. 589)
• ConfusionMatrix Structure (p. 590)
• GlueTable Structure (p. 590)
• TaskRun Structure (p. 591)
• TransformFilterCriteria Structure (p. 592)
• TransformSortCriteria Structure (p. 592)
• TaskRunFilterCriteria Structure (p. 593)
• TaskRunSortCriteria Structure (p. 593)
• TaskRunProperties Structure (p. 593)
• FindMatchesTaskRunProperties Structure (p. 594)
• ImportLabelsTaskRunProperties Structure (p. 594)
• ExportLabelsTaskRunProperties Structure (p. 594)
• LabelingSetGenerationTaskRunProperties Structure (p. 594)
• SchemaColumn Structure (p. 595)
TransformParameters Structure
The algorithm-specific parameters that are associated with the machine learning transform.
Fields
For information about the types of machine learning transforms, see Creating Machine Learning
Transforms.
• FindMatchesParameters – A FindMatchesParameters (p. 588) object.
EvaluationMetrics Structure
Evaluation metrics provide an estimate of the quality of your machine learning transform.
Fields
586
AWS Glue Developer Guide
MLTransform
MLTransform Structure
A structure for a machine learning transform.
Fields
• TransformId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The unique transform ID that is generated for the machine learning transform. The ID is guaranteed to
be unique and does not change.
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
A user-defined name for the machine learning transform. Names are not guaranteed unique and can
be changed at any time.
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
A user-defined, long-form description text for the machine learning transform. Descriptions are not
guaranteed to be unique and can be changed at any time.
• Status – UTF-8 string (valid values: NOT_READY | READY | DELETING).
A timestamp. The time and date that this machine learning transform was created.
• LastModifiedOn – Timestamp.
A timestamp. The last point in time when this machine learning transform was modified.
• InputRecordTables – An array of GlueTable (p. 590) objects, not more than 10 structures.
A TransformParameters object. You can use parameters to tune (customize) the behavior of the
machine learning transform by specifying what data it learns from and your preference on various
tradeoffs (such as precious vs. recall, or accuracy vs. cost).
• EvaluationMetrics – An EvaluationMetrics (p. 586) object.
A count identifier for the labeling files generated by AWS Glue for this transform. As you create a
better transform, you can iteratively download, label, and upload the labeling file.
• Schema – An array of SchemaColumn (p. 595) objects, not more than 100 structures.
A map of key-value pairs representing the columns and data types that this transform can run against.
Has an upper bound of 100 columns.
• Role – UTF-8 string.
The name or Amazon Resource Name (ARN) of the IAM role with the required permissions. The
required permissions include both AWS Glue service role permissions to AWS Glue resources, and
Amazon S3 permissions required by the transform.
587
AWS Glue Developer Guide
FindMatchesParameters
• This role needs AWS Glue service role permissions to allow access to resources in AWS Glue. See
Attach a Policy to IAM Users That Access AWS Glue.
• This role needs permission to your Amazon Simple Storage Service (Amazon S3) sources, targets,
temporary directory, scripts, and any libraries used by the task run for this transform.
• MaxCapacity – Number (double).
The number of AWS Glue data processing units (DPUs) that are allocated to task runs for this
transform. You can allocate from 2 to 100 DPUs; the default is 10. A DPU is a relative measure of
processing power that consists of 4 vCPUs of compute capacity and 16 GB of memory. For more
information, see the AWS Glue pricing page.
When the WorkerType field is set to a value other than Standard, the MaxCapacity field is set
automatically and becomes read-only.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated when a task of this transform runs. Accepts a value of
Standard, G.1X, or G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker provides 4 vCPU, 16 GB of memory and a 64GB disk, and 1
executor per worker.
• For the G.2X worker type, each worker provides 8 vCPU, 32 GB of memory and a 128GB disk, and 1
executor per worker.
The number of workers of a defined workerType that are allocated when a task of the transform
runs.
The maximum number of times to retry after an MLTaskRun of the machine learning transform fails.
FindMatchesParameters Structure
The parameters to configure the find matches transform.
588
AWS Glue Developer Guide
FindMatchesMetrics
Fields
• PrimaryKeyColumnName – UTF-8 string, not less than 1 or more than 1024 bytes long, matching the
Single-line string pattern (p. 612).
The name of a column that uniquely identifies rows in the source table. Used to help identify matching
records.
• PrecisionRecallTradeoff – Number (double), not more than 1.0.
The value selected when tuning your transform for a balance between precision and recall. A value of
0.5 means no preference; a value of 1.0 means a bias purely for precision, and a value of 0.0 means
a bias for recall. Because this is a tradeoff, choosing values close to 1.0 means very low recall, and
choosing values close to 0.0 results in very low precision.
The precision metric indicates how often your model is correct when it predicts a match.
The recall metric indicates that for an actual match, how often your model predicts the match.
• AccuracyCostTradeoff – Number (double), not more than 1.0.
The value that is selected when tuning your transform for a balance between accuracy and cost. A
value of 0.5 means that the system balances accuracy and cost concerns. A value of 1.0 means a bias
purely for accuracy, which typically results in a higher cost, sometimes substantially higher. A value of
0.0 means a bias purely for cost, which results in a less accurate FindMatches transform, sometimes
with unacceptable accuracy.
Accuracy measures how well the transform finds true positives and true negatives. Increasing accuracy
requires more machine resources and cost. But it also results in increased recall.
Cost measures how many compute resources, and thus money, are consumed to run the transform.
• EnforceProvidedLabels – Boolean.
The value to switch on or off to force the output to match the provided labels from users. If the value
is True, the find matches transform forces the output to match the provided labels. The results
override the normal conflation results. If the value is False, the find matches transform does not
ensure all the labels provided are respected, and the results rely on the trained model.
Note that setting this value to true may increase the conflation execution time.
FindMatchesMetrics Structure
The evaluation metrics for the find matches algorithm. The quality of your machine learning transform
is measured by getting your transform to predict some matches and comparing the results to known
matches from the same dataset. The quality metrics are based on a subset of your data, so they are not
precise.
Fields
The area under the precision/recall curve (AUPRC) is a single number measuring the overall quality of
the transform, that is independent of the choice made for precision vs. recall. Higher values indicate
that you have a more attractive precision vs. recall tradeoff.
589
AWS Glue Developer Guide
ConfusionMatrix
The precision metric indicates when often your transform is correct when it predicts a match.
Specifically, it measures how well the transform finds true positives from the total true positives
possible.
The recall metric indicates that for an actual match, how often your transform predicts the match.
Specifically, it measures how well the transform finds true positives from the total records in the
source data.
The maximum F1 metric indicates the transform's accuracy between 0 and 1, where 1 is the best
accuracy.
The confusion matrix shows you what your transform is predicting accurately and what types of errors
it is making.
ConfusionMatrix Structure
The confusion matrix shows you what your transform is predicting accurately and what types of errors it
is making.
Fields
The number of matches in the data that the transform correctly found, in the confusion matrix for
your transform.
• NumFalsePositives – Number (long).
The number of nonmatches in the data that the transform incorrectly classified as a match, in the
confusion matrix for your transform.
• NumTrueNegatives – Number (long).
The number of nonmatches in the data that the transform correctly rejected, in the confusion matrix
for your transform.
• NumFalseNegatives – Number (long).
The number of matches in the data that the transform didn't find, in the confusion matrix for your
transform.
GlueTable Structure
The database and table in the AWS Glue Data Catalog that is used for input or output data.
590
AWS Glue Developer Guide
TaskRun
Fields
• DatabaseName – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
TaskRun Structure
The sampling parameters that are associated with the machine learning transform.
Fields
• TransformId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The names of the log group for secure logging, associated with this task run.
• Properties – A TaskRunProperties (p. 593) object.
The last point in time that the requested task run was updated.
• CompletedOn – Timestamp.
The last point in time that the requested task run was completed.
591
AWS Glue Developer Guide
TransformFilterCriteria
The amount of time (in seconds) that the task run consumed resources.
TransformFilterCriteria Structure
The criteria used to filter the machine learning transforms.
Fields
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
A unique transform name that is used to filter the machine learning transforms.
• TransformType – UTF-8 string (valid values: FIND_MATCHES).
The type of machine learning transform that is used to filter the machine learning transforms.
• Status – UTF-8 string (valid values: NOT_READY | READY | DELETING).
Filters the list of machine learning transforms by the last known status of the transforms (to indicate
whether a transform can be used or not). One of "NOT_READY", "READY", or "DELETING".
• CreatedBefore – Timestamp.
The time and date before which the transforms were created.
• CreatedAfter – Timestamp.
The time and date after which the transforms were created.
• LastModifiedBefore – Timestamp.
Filters on datasets with a specific schema. The Map<Column, Type> object is an array of key-value
pairs representing the schema this transform accepts, where Column is the name of a column, and
Type is the type of the data such as an integer or string. Has an upper bound of 100 columns.
TransformSortCriteria Structure
The sorting criteria that are associated with the machine learning transform.
Fields
• Column – Required: UTF-8 string (valid values: NAME | TRANSFORM_TYPE | STATUS | CREATED |
LAST_MODIFIED).
The column to be used in the sorting criteria that are associated with the machine learning transform.
• SortDirection – Required: UTF-8 string (valid values: DESCENDING | ASCENDING).
The sort direction to be used in the sorting criteria that are associated with the machine learning
transform.
592
AWS Glue Developer Guide
TaskRunFilterCriteria
TaskRunFilterCriteria Structure
The criteria that are used to filter the task runs for the machine learning transform.
Fields
TaskRunSortCriteria Structure
The sorting criteria that are used to sort the list of task runs for the machine learning transform.
Fields
The column to be used to sort the list of task runs for the machine learning transform.
• SortDirection – Required: UTF-8 string (valid values: DESCENDING | ASCENDING).
The sort direction to be used to sort the list of task runs for the machine learning transform.
TaskRunProperties Structure
The configuration properties for the task run.
Fields
593
AWS Glue Developer Guide
FindMatchesTaskRunProperties
FindMatchesTaskRunProperties Structure
Specifies configuration properties for a Find Matches task run.
Fields
• JobId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The name assigned to the job for the Find Matches task run.
• JobRunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
ImportLabelsTaskRunProperties Structure
Specifies configuration properties for an importing labels task run.
Fields
The Amazon Simple Storage Service (Amazon S3) path from where you will import the labels.
• Replace – Boolean.
ExportLabelsTaskRunProperties Structure
Specifies configuration properties for an exporting labels task run.
Fields
The Amazon Simple Storage Service (Amazon S3) path where you will export the labels.
LabelingSetGenerationTaskRunProperties Structure
Specifies configuration properties for a labeling set generation task run.
Fields
594
AWS Glue Developer Guide
SchemaColumn
The Amazon Simple Storage Service (Amazon S3) path where you will generate the labeling set.
SchemaColumn Structure
A key-value pair representing a column and data type that this transform can run against. The Schema
parameter of the MLTransform may contain up to 100 of these structures.
Fields
• Name – UTF-8 string, not less than 1 or more than 1024 bytes long, matching the Single-line string
pattern (p. 612).
Operations
• CreateMLTransform Action (Python: create_ml_transform) (p. 595)
• UpdateMLTransform Action (Python: update_ml_transform) (p. 597)
• DeleteMLTransform Action (Python: delete_ml_transform) (p. 599)
• GetMLTransform Action (Python: get_ml_transform) (p. 599)
• GetMLTransforms Action (Python: get_ml_transforms) (p. 601)
• StartMLEvaluationTaskRun Action (Python: start_ml_evaluation_task_run) (p. 602)
• StartMLLabelingSetGenerationTaskRun Action (Python:
start_ml_labeling_set_generation_task_run) (p. 603)
• GetMLTaskRun Action (Python: get_ml_task_run) (p. 603)
• GetMLTaskRuns Action (Python: get_ml_task_runs) (p. 605)
• CancelMLTaskRun Action (Python: cancel_ml_task_run) (p. 605)
• StartExportLabelsTaskRun Action (Python: start_export_labels_task_run) (p. 606)
• StartImportLabelsTaskRun Action (Python: start_import_labels_task_run) (p. 607)
Call this operation as the first step in the process of using a machine learning transform (such as the
FindMatches transform) for deduplicating data. You can provide an optional Description, in addition
to the parameters that you want to use for your algorithm.
You must also specify certain parameters for the tasks that AWS Glue runs on your behalf as part of
learning from your data and creating a high-quality machine learning transform. These parameters
include Role, and optionally, AllocatedCapacity, Timeout, and MaxRetries. For more information,
see Jobs.
595
AWS Glue Developer Guide
CreateMLTransform (create_ml_transform)
Request
• Name – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The unique name that you give the transform when you create it.
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
A description of the machine learning transform that is being defined. The default is an empty string.
• InputRecordTables – Required: An array of GlueTable (p. 590) objects, not more than 10
structures.
The algorithmic parameters that are specific to the transform type used. Conditionally dependent on
the transform type.
• Role – Required: UTF-8 string.
The name or Amazon Resource Name (ARN) of the IAM role with the required permissions. The
required permissions include both AWS Glue service role permissions to AWS Glue resources, and
Amazon S3 permissions required by the transform.
• This role needs AWS Glue service role permissions to allow access to resources in AWS Glue. See
Attach a Policy to IAM Users That Access AWS Glue.
• This role needs permission to your Amazon Simple Storage Service (Amazon S3) sources, targets,
temporary directory, scripts, and any libraries used by the task run for this transform.
• MaxCapacity – Number (double).
The number of AWS Glue data processing units (DPUs) that are allocated to task runs for this
transform. You can allocate from 2 to 100 DPUs; the default is 10. A DPU is a relative measure of
processing power that consists of 4 vCPUs of compute capacity and 16 GB of memory. For more
information, see the AWS Glue pricing page.
When the WorkerType field is set to a value other than Standard, the MaxCapacity field is set
automatically and becomes read-only.
When the WorkerType field is set to a value other than Standard, the MaxCapacity field is set
automatically and becomes read-only.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated when this task runs. Accepts a value of Standard, G.1X,
or G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker provides 4 vCPU, 16 GB of memory and a 64GB disk, and 1
executor per worker.
• For the G.2X worker type, each worker provides 8 vCPU, 32 GB of memory and a 128GB disk, and 1
executor per worker.
596
AWS Glue Developer Guide
UpdateMLTransform (update_ml_transform)
The number of workers of a defined workerType that are allocated when this task runs.
The timeout of the task run for this transform in minutes. This is the maximum time that a task run for
this transform can consume resources before it is terminated and enters TIMEOUT status. The default
is 2,880 minutes (48 hours).
• MaxRetries – Number (integer).
The maximum number of times to retry a task for this transform after a task run fails.
Response
• TransformId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Errors
• AlreadyExistsException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
• AccessDeniedException
• ResourceNumberLimitExceededException
• IdempotentParameterMismatchException
After calling this operation, you can call the StartMLEvaluationTaskRun operation to assess how
well your new parameters achieved your goals (such as improving the quality of your machine learning
transform, or making it more cost-effective).
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
597
AWS Glue Developer Guide
UpdateMLTransform (update_ml_transform)
A unique identifier that was generated when the transform was created.
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The unique name that you gave the transform when you created it.
• Description – Description string, not more than 2048 bytes long, matching the URI address multi-
line string pattern (p. 612).
The configuration parameters that are specific to the transform type (algorithm) used. Conditionally
dependent on the transform type.
• Role – UTF-8 string.
The name or Amazon Resource Name (ARN) of the IAM role with the required permissions.
• MaxCapacity – Number (double).
The number of AWS Glue data processing units (DPUs) that are allocated to task runs for this
transform. You can allocate from 2 to 100 DPUs; the default is 10. A DPU is a relative measure of
processing power that consists of 4 vCPUs of compute capacity and 16 GB of memory. For more
information, see the AWS Glue pricing page.
When the WorkerType field is set to a value other than Standard, the MaxCapacity field is set
automatically and becomes read-only.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated when this task runs. Accepts a value of Standard, G.1X,
or G.2X.
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker provides 4 vCPU, 16 GB of memory and a 64GB disk, and 1
executor per worker.
• For the G.2X worker type, each worker provides 8 vCPU, 32 GB of memory and a 128GB disk, and 1
executor per worker.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated when this task runs.
• Timeout – Number (integer), at least 1.
The timeout for a task run for this transform in minutes. This is the maximum time that a task run for
this transform can consume resources before it is terminated and enters TIMEOUT status. The default
is 2,880 minutes (48 hours).
• MaxRetries – Number (integer).
The maximum number of times to retry a task for this transform after a task run fails.
Response
• TransformId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
598
AWS Glue Developer Guide
DeleteMLTransform (delete_ml_transform)
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
• AccessDeniedException
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• TransformId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The unique identifier of the transform, generated at the time that the transform was created.
599
AWS Glue Developer Guide
GetMLTransform (get_ml_transform)
Response
• TransformId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The unique identifier of the transform, generated at the time that the transform was created.
• Name – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
The last known status of the transform (to indicate whether it can be used or not). One of
"NOT_READY", "READY", or "DELETING".
• CreatedOn – Timestamp.
The date and time when the transform was last modified.
• InputRecordTables – An array of GlueTable (p. 590) objects, not more than 10 structures.
The Map<Column, Type> object that represents the schema that this transform accepts. Has an
upper bound of 100 columns.
• Role – UTF-8 string.
The name or Amazon Resource Name (ARN) of the IAM role with the required permissions.
• MaxCapacity – Number (double).
The number of AWS Glue data processing units (DPUs) that are allocated to task runs for this
transform. You can allocate from 2 to 100 DPUs; the default is 10. A DPU is a relative measure of
processing power that consists of 4 vCPUs of compute capacity and 16 GB of memory. For more
information, see the AWS Glue pricing page.
When the WorkerType field is set to a value other than Standard, the MaxCapacity field is set
automatically and becomes read-only.
• WorkerType – UTF-8 string (valid values: Standard="" | G.1X="" | G.2X="").
The type of predefined worker that is allocated when this task runs. Accepts a value of Standard, G.1X,
or G.2X.
600
AWS Glue Developer Guide
GetMLTransforms (get_ml_transforms)
• For the Standard worker type, each worker provides 4 vCPU, 16 GB of memory and a 50GB disk,
and 2 executors per worker.
• For the G.1X worker type, each worker provides 4 vCPU, 16 GB of memory and a 64GB disk, and 1
executor per worker.
• For the G.2X worker type, each worker provides 8 vCPU, 32 GB of memory and a 128GB disk, and 1
executor per worker.
• NumberOfWorkers – Number (integer).
The number of workers of a defined workerType that are allocated when this task runs.
• Timeout – Number (integer), at least 1.
The timeout for a task run for this transform in minutes. This is the maximum time that a task run for
this transform can consume resources before it is terminated and enters TIMEOUT status. The default
is 2,880 minutes (48 hours).
• MaxRetries – Number (integer).
The maximum number of times to retry a task for this transform after a task run fails.
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
Request
Response
601
AWS Glue Developer Guide
StartMLEvaluationTaskRun (start_ml_evaluation_task_run)
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
When you provide label sets as examples of truth, AWS Glue machine learning uses some of those
examples to learn from them. The rest of the labels are used as a test to estimate quality.
Returns a unique identifier for the run. You can call GetMLTaskRun to get more information about the
stats of the EvaluationTaskRun.
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• TaskRunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
• ConcurrentRunsExceededException
• MLTransformNotReadyException
602
AWS Glue Developer Guide
StartMLLabelingSetGenerationTaskRun
(start_ml_labeling_set_generation_task_run)
StartMLLabelingSetGenerationTaskRun Action
(Python: start_ml_labeling_set_generation_task_run)
Starts the active learning workflow for your machine learning transform to improve the transform's
quality by generating label sets and adding labels.
In the case of the FindMatches transform, these questions are of the form, "What is the correct way to
group these rows together into groups composed entirely of matching records?"
After the labeling process is finished, you can upload your labels with a call to
StartImportLabelsTaskRun. After StartImportLabelsTaskRun finishes, all future runs of
the machine learning transform will use the new and improved labels and perform a higher-quality
transformation.
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The Amazon Simple Storage Service (Amazon S3) path where you generate the labeling set.
Response
• TaskRunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The unique run identifier that is associated with this task run.
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
• ConcurrentRunsExceededException
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
603
AWS Glue Developer Guide
GetMLTaskRun (get_ml_task_run)
Response
• TransformId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
The names of the log groups that are associated with the task run.
• Properties – A TaskRunProperties (p. 593) object.
The list of properties that are associated with the task run.
• ErrorString – UTF-8 string.
The error strings that are associated with the task run.
• StartedOn – Timestamp.
The date and time when this task run was last modified.
• CompletedOn – Timestamp.
The date and time when this task run was completed.
• ExecutionTime – Number (integer).
The amount of time (in seconds) that the task run consumed resources.
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
604
AWS Glue Developer Guide
GetMLTaskRuns (get_ml_task_runs)
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The filter criteria, in the TaskRunFilterCriteria structure, for the task run.
• Sort – A TaskRunSortCriteria (p. 593) object.
The sorting criteria, in the TaskRunSortCriteria structure, for the task run.
Response
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
605
AWS Glue Developer Guide
StartExportLabelsTaskRun (start_export_labels_task_run)
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
Response
• TransformId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
606
AWS Glue Developer Guide
StartImportLabelsTaskRun (start_import_labels_task_run)
Response
• TaskRunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• InternalServiceException
You can check on the status of your task run by calling the GetMLTaskRun operation.
Request
• TransformId – Required: UTF-8 string, not less than 1 or more than 255 bytes long, matching the
Single-line string pattern (p. 612).
The Amazon Simple Storage Service (Amazon S3) path from where you import the labels.
• ReplaceAllLabels – Boolean.
607
AWS Glue Developer Guide
Tagging APIs
Response
• TaskRunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
Errors
• EntityNotFoundException
• InvalidInputException
• OperationTimeoutException
• ResourceNumberLimitExceededException
• InternalServiceException
Tag Structure
The Tag object represents a label that you can assign to an AWS resource. Each tag consists of a key and
an optional value, both of which you define.
For more information about tags, and controlling access to resources in AWS Glue, see AWS Tags in AWS
Glue and Specifying AWS Glue Resource ARNs in the developer guide.
Fields
• key – UTF-8 string, not less than 1 or more than 128 bytes long.
The tag key. The key is required when you create a tag on an object. The key is case-sensitive, and must
not contain the prefix aws.
• value – UTF-8 string, not more than 256 bytes long.
The tag value. The value is optional when you create a tag on an object. The value is case-sensitive,
and must not contain the prefix aws.
Operations
• TagResource Action (Python: tag_resource) (p. 608)
• UntagResource Action (Python: untag_resource) (p. 609)
• GetTags Action (Python: get_tags) (p. 610)
608
AWS Glue Developer Guide
UntagResource (untag_resource)
Request
• ResourceArn – Required: UTF-8 string, not less than 1 or more than 10240 bytes long, matching the
AWS Glue ARN string pattern (p. 612).
The ARN of the AWS Glue resource to which to add the tags. For more information about AWS Glue
resource ARNs, see the AWS Glue ARN string pattern.
• TagsToAdd – Required: A map array of key-value pairs, not more than 50 pairs.
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
Response
• No Response parameters.
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• EntityNotFoundException
Request
• ResourceArn – Required: UTF-8 string, not less than 1 or more than 10240 bytes long, matching the
AWS Glue ARN string pattern (p. 612).
The Amazon Resource Name (ARN) of the resource from which to remove the tags.
• TagsToRemove – Required: An array of UTF-8 strings, not more than 50 strings.
Response
• No Response parameters.
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• EntityNotFoundException
609
AWS Glue Developer Guide
GetTags (get_tags)
Request
• ResourceArn – Required: UTF-8 string, not less than 1 or more than 10240 bytes long, matching the
AWS Glue ARN string pattern (p. 612).
The Amazon Resource Name (ARN) of the resource for which to retrieve tags.
Response
Each key is a UTF-8 string, not less than 1 or more than 128 bytes long.
Each value is a UTF-8 string, not more than 256 bytes long.
Errors
• InvalidInputException
• InternalServiceException
• OperationTimeoutException
• EntityNotFoundException
Tag Structure
The Tag object represents a label that you can assign to an AWS resource. Each tag consists of a key and
an optional value, both of which you define.
For more information about tags, and controlling access to resources in AWS Glue, see AWS Tags in AWS
Glue and Specifying AWS Glue Resource ARNs in the developer guide.
Fields
• key – UTF-8 string, not less than 1 or more than 128 bytes long.
The tag key. The key is required when you create a tag on an object. The key is case-sensitive, and must
not contain the prefix aws.
• value – UTF-8 string, not more than 256 bytes long.
The tag value. The value is optional when you create a tag on an object. The value is case-sensitive,
and must not contain the prefix aws.
610
AWS Glue Developer Guide
DecimalNumber
DecimalNumber Structure
Contains a numeric value in decimal format.
Fields
• UnscaledValue – Blob.
The scale that determines where the decimal point falls in the unscaled value.
ErrorDetail Structure
Contains details about an error.
Fields
• ErrorCode – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line
string pattern (p. 612).
PropertyPredicate Structure
Defines a property predicate.
Fields
ResourceUri Structure
The URIs for function resources.
Fields
611
AWS Glue Developer Guide
String Patterns
String Patterns
The API uses the following regular expressions to define what is valid content for various string
parameters and members:
Exceptions
This section describes AWS Glue exceptions that you can use to find the source of problems and fix them.
AccessDeniedException Structure
Access to a resource was denied.
Fields
AlreadyExistsException Structure
A resource to be created or added already exists.
612
AWS Glue Developer Guide
ConcurrentModificationException
Fields
ConcurrentModificationException Structure
Two processes are trying to modify a resource simultaneously.
Fields
ConcurrentRunsExceededException Structure
Too many jobs are being run concurrently.
Fields
CrawlerNotRunningException Structure
The specified crawler is not running.
Fields
CrawlerRunningException Structure
The operation cannot be performed because the crawler is already running.
Fields
CrawlerStoppingException Structure
The specified crawler is stopping.
Fields
613
AWS Glue Developer Guide
EntityNotFoundException
EntityNotFoundException Structure
A specified entity does not exist
Fields
GlueEncryptionException Structure
An encryption operation failed.
Fields
IdempotentParameterMismatchException Structure
The same unique identifier was associated with two different records.
Fields
InternalServiceException Structure
An internal service error occurred.
Fields
InvalidExecutionEngineException Structure
An unknown or invalid execution engine was specified.
Fields
614
AWS Glue Developer Guide
InvalidInputException
InvalidInputException Structure
The input provided was not valid.
Fields
InvalidTaskStatusTransitionException Structure
Proper transition from one task to the next failed.
Fields
JobDefinitionErrorException Structure
A job definition is not valid.
Fields
JobRunInTerminalStateException Structure
The terminal state of a job run signals a failure.
Fields
JobRunInvalidStateTransitionException Structure
A job run encountered an invalid transition from source state to target state.
Fields
• jobRunId – UTF-8 string, not less than 1 or more than 255 bytes long, matching the Single-line string
pattern (p. 612).
615
AWS Glue Developer Guide
JobRunNotInTerminalStateException
• sourceState – UTF-8 string (valid values: STARTING | RUNNING | STOPPING | STOPPED | SUCCEEDED
| FAILED | TIMEOUT).
JobRunNotInTerminalStateException Structure
A job run is not in a terminal state.
Fields
LateRunnerException Structure
A job runner is late.
Fields
NoScheduleException Structure
There is no applicable schedule.
Fields
OperationTimeoutException Structure
The operation timed out.
Fields
ResourceNumberLimitExceededException Structure
A resource numerical limit was exceeded.
616
AWS Glue Developer Guide
SchedulerNotRunningException
Fields
SchedulerNotRunningException Structure
The specified scheduler is not running.
Fields
SchedulerRunningException Structure
The specified scheduler is already running.
Fields
SchedulerTransitioningException Structure
The specified scheduler is transitioning.
Fields
UnrecognizedRunnerException Structure
The job runner was not recognized.
Fields
ValidationException Structure
A value could not be validated.
Fields
617
AWS Glue Developer Guide
VersionMismatchException
VersionMismatchException Structure
There was a version conflict.
Fields
618
AWS Glue Developer Guide
Preventing Cross-Job Data Access
Topics
• Preventing Cross-Job Data Access (p. 619)
• Issues with Development Endpoints Created with AWS Glue Version 1.0 (p. 620)
In the diagram, AWS Glue Job-1 is running in Cluster-1, and Job-2 is running in Cluster-2. Both
jobs are working with the same instance of Amazon Redshift, which resides in Subnet-1 of a VPC.
Subnet-1 could be a public or private subnet.
619
AWS Glue Developer Guide
Issues with Development Endpoints
Created with AWS Glue Version 1.0
Job-1 is transforming data from Amazon Simple Storage Service (Amazon S3) Bucket-1 and writing
the data to Amazon Redshift. Job-2 is doing the same with data in Bucket-2. Job-1 uses the AWS
Identity and Access Management (IAM) role Role-1 (not shown), which gives access to Bucket-1.
Job-2 uses Role-2 (not shown), which gives access to Bucket-2.
These jobs have network paths that enable them to communicate with each other's clusters and thus
access each other's data. For example, Job-2 could access data in Bucket-1. In the diagram, this is
shown as the path in red.
To prevent this situation, we recommend that you attach different security configurations to Job-1
and Job-2. By attaching the security configurations, cross-job access to data is blocked by virtue of
certificates that AWS Glue creates. The security configurations can be dummy configurations. That is,
you can create the security configurations without enabling encryption of Amazon S3 data, Amazon
CloudWatch data, or job bookmarks. All three encryption options can be disabled.
For information about security configurations, see the section called “Encrypting Data Written by AWS
Glue” (p. 43).
If you specify AWS Glue 1.0 when creating a development endpoint and then attempt to use the AWS
Glue Scala REPL (the glue-spark-shell command), the REPL fails with the following error:
You can use the PySpark REPL with AWS Glue 1.0, or for your Scala scripts, you can create a development
endpoint specifying AWS Glue 0.9.
If you specify AWS Glue 1.0 when creating a development endpoint and then attempt to use the
gluepython command to test your script, you might encounter the following error:
As an alternative, you can test your script with the AWS Glue PySpark REPL. For more information, see
the section called “Tutorial: Use a REPL Shell” (p. 197).
620
AWS Glue Developer Guide
AWS Glue Versions
621
AWS Glue Developer Guide
Support for rewinding your job Added information about October 22, 2019
bookmarks (p. 622) rewinding your job bookmarks
to any previous job run, resulting
in the subsequent job run
reprocessing data only from the
bookmarked job run. Described
two new sub-options for the
job-bookmark-pause option
that allow you to run a job
between two bookmarks.
For more information see
Tracking Processed Data Using
Job Bookmarks and Special
Parameters Used by AWS Glue.
Support for Custom JDBC Added information about AWS October 10, 2019
certificates for connecting to a Glue support of custom JDBC
data store (p. 622) certificates for SSL connections
to AWS Glue data sources or
targets. For more information,
see Working with Connections
on the AWS Glue Console.
Support for monitoring AWS Added information about using September 19, 2019
Glue using Spark UI (p. 622) Spark UI to monitor and debug
AWS Glue ETL jobs running
on the AWS Glue job system,
and Spark applications on AWS
622
AWS Glue Developer Guide
Enhancement of support for Updated the AWS Glue ETL September 18, 2019
local ETL script development library content to reflect
using the public AWS Glue ETL that Glue version 1.0 is
library (p. 622) now supported. For more
information, see Developing and
Testing ETL Scripts Locally Using
the AWS Glue ETL Library.
Support for excluding Amazon Added information about August 29, 2019
S3 storage classes when running excluding Amazon S3 storage
jobs (p. 622) classes when running AWS
Glue ETL jobs that read files or
partitions from Amazon S3. For
more information, see Excluding
Amazon S3 Storage Classes.
Support for local ETL script Added information about August 28, 2019
development using the public how to develop and test
AWS Glue ETL library (p. 622) Python and Scala ETL scripts
locally without the need for a
network connection. For more
information, see Developing and
Testing ETL Scripts Locally Using
the AWS Glue ETL Library.
Known Issues (p. 622) Added information about known August 28, 2019
issues in AWS Glue. For more
information, see Known Issues
for AWS Glue.
Support for shared Amazon Added information about AWS August 6, 2019
Virtual Private Cloud (p. 622) Glue support for shared Amazon
Virtual Private Cloud. For more
information see Shared Amazon
VPCs.
623
AWS Glue Developer Guide
Support for versioning in AWS Added information about July 24, 2019
Glue (p. 622) defining the Glue version in
job properties. Glue version
determines the versions of
Apache Spark and Python that
AWS Glue supports. For more
information, see Adding Jobs in
AWS Glue.
Support for performing extract, Added information about using a June 20, 2019
transfer, and load (ETL) activities new construct called a workflow
using workflows (p. 622) to design a complex multi-job
extract, transform, and load
(ETL) activity that AWS Glue
can execute and track as single
entity. For more information
see Performing Complex ETL
Activities Using Workflows in
AWS Glue.
Support for virtual private cloud Added information about June 4, 2019
(VPC) endpoints (p. 622) connecting directly to AWS Glue
through an interface endpoint in
your Virtual Private Cloud (VPC).
When you use a VPC interface
endpoint, communication
between your VPC and AWS
Glue is conducted entirely
and securely within the AWS
network. For more information,
see Using AWS Glue with VPC
Endpoints.
624
AWS Glue Developer Guide
Support for existing Data Added information about May 10, 2019
Catalog tables as crawler specifying a list of existing
sources (p. 622) Data Catalog tables as
crawler sources. Crawlers
can then detect changes to
table schemas, update table
definitions, and register new
partitions as new data becomes
available. For more information,
see Crawler Properties.
Support for CSV custom Added information about using a March 26, 2019
classifiers (p. 622) custom CSV classifier to infer the
schema of various types of CSV
data. For more information, see
Writing Custom Classifiers.
Support for AWS Resource Added information about using March 20, 2019
Tags (p. 622) AWS resource tags to help you
manage and control access to
your AWS Glue resources. You
can assign AWS resource tags
to jobs, triggers, endpoints, and
crawlers in AWS Glue. For more
information, see AWS Tags in
AWS Glue.
625
AWS Glue Developer Guide
Support of AWS Glue Data Added information about March 14, 2019
Catalog for Spark SQL configuring your AWS Glue jobs
jobs (p. 622) and development endpoints to
use the AWS Glue Data Catalog
as an external Apache Hive
Metastore. This allows jobs
and development endpoints to
directly run Apache Spark SQL
queries against the tables stored
in the AWS Glue Data Catalog.
For more information, see AWS
Glue Data Catalog Support for
Spark SQL Jobs.
Support for Python shell Added information about January 18, 2019
jobs (p. 622) Python shell jobs and the new
field Maximum capacity. For
more information, see Adding
Python Shell Jobs in AWS Glue.
Support for notifications when Added information about events January 16, 2019
there are changes to databases that are generated for changes
and tables (p. 622) to database, table, and partition
API calls. You can configure
actions in CloudWatch Events
to respond to these events.
For more information, see
Automating AWS Glue with
CloudWatch Events.
Support for resource-level Added information about using October 15, 2018
permission and resource-based resource-level permissions and
policies (p. 622) resource-based policies with
AWS Glue. For more information,
see the topics within Security in
AWS Glue.
Support for encryption (p. 622) Added information about using August 24, 2018
encryption with AWS Glue.
For more information, see
Encryption at Rest, Encryption
in Transit, and Setting Up
Encryption in AWS Glue.
626
AWS Glue Developer Guide
Support for Apache Spark job Added information about the July 13, 2018
metrics (p. 622) use of Apache Spark metrics for
better debugging and profiling
of ETL jobs. You can easily track
runtime metrics such as bytes
read and written, memory usage
and CPU load of the driver and
executors, and data shuffles
among executors from the
AWS Glue console. For more
information, see Monitoring
AWS Glue Using CloudWatch
Metrics, Job Monitoring and
Debugging and Working with
Jobs on the AWS Glue Console.
Updates now available over You can now subscribe to an June 25, 2018
RSS (p. 622) RSS feed to receive notifications
about updates to the AWS Glue
Developer Guide.
Support delay notifications for Added information about May 25, 2018
jobs (p. 622) configuring a delay threshold
when a job runs. For more
information, see Adding Jobs in
AWS Glue.
627
AWS Glue Developer Guide
Earlier Updates
Support Scala ETL script and Added information about using January 12, 2018
trigger jobs based on additional Scala as the ETL programming
run states (p. 622) language. In addition, the trigger
API now supports firing when
any conditions are met (in
addition to all conditions). Also,
jobs can be triggered based on
a "failed" or "stopped" job run
(in addition to a "succeeded" job
run).
Earlier Updates
The following table describes the important changes in each release of the AWS Glue Developer Guide
before January 2018.
Support XML data Added information about classifying XML November 16, 2017
sources and new data sources and new crawler option for
crawler configuration partition changes.
option
New transforms, Added information about the map and September 29, 2017
support for filter transforms, support for Amazon RDS
additional Amazon Microsoft SQL Server and Amazon RDS
RDS database Oracle, and new features for development
engines, and endpoints.
development
endpoint
enhancements
AWS Glue initial This is the initial release of the AWS Glue August 14, 2017
release Developer Guide.
628
AWS Glue Developer Guide
AWS Glossary
For the latest AWS terminology, see the AWS Glossary in the AWS General Reference.
629