

# Using Lake Formation-governed UDFs in AWS Glue

With AWS Glue version 6.1 and higher, your AWS Glue for Apache Spark jobs and interactive sessions can load AWS Glue Data Catalog user-defined functions (UDFs) that are governed by Lake Formation through the `--lakeformation-artifacts` parameter. A governed UDF is a Data Catalog function with `GovernanceMode` set to `LAKE_FORMATION`, whose code is packaged in JARs stored in Amazon S3. These JARs are the UDF's custom code artifacts. AWS Glue loads the UDFs that you declare in this parameter into the job.

With governed UDFs, you can use custom classes in a job that uses fine-grained access control. Without them, you can't use UDFs that involve custom classes in those jobs. This restriction protects the isolation of the system driver. You can also use governed UDFs in jobs that don't use fine-grained access control, including jobs that use full table access and jobs that don't use Lake Formation for data access.

Governed UDFs work the same way in AWS Glue as in Amazon EMR. For supported UDF types, the `fgac-config.yaml` file, rules for UDF code, where a UDF runs and which data it sees, and the error reference, see [Using governed UDFs with Lake Formation fine-grained access control](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-fgac-governed-udfs.html) in the *Amazon EMR Release Guide*. To create, update, and grant permissions on a governed UDF, see [Governing AWS Glue Data Catalog user-defined functions with Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/governing-user-defined-functions.html) in the *Lake Formation Developer Guide*.

## Understanding how governed UDFs work
<a name="lake-formation-governed-udfs-how-it-works"></a>

Governed UDFs work as follows in AWS Glue:

1. A data lake administrator creates a governed UDF for the JAR in the Data Catalog and grants the job's runtime role `EXECUTE` on it.

1. You declare the UDF's ARN in the `--lakeformation-artifacts` parameter.

1. For jobs that use fine-grained access control, AWS Glue checks with Lake Formation that the runtime role has `EXECUTE` on every declared UDF when the run starts. For a job run, this happens during `StartJobRun`. For an interactive session, it happens while AWS Glue creates the session. If any check fails, the job run or session doesn't start. For other jobs, Lake Formation checks `EXECUTE` when the job run loads the JAR. If the check fails, the job run fails.

## Prerequisites
<a name="lake-formation-governed-udfs-prerequisites"></a>
+ AWS Glue version 6.1 or higher.
+ An AWS Glue ETL Spark job or an AWS Glue interactive session. Streaming, Ray, and Python shell jobs aren't supported.
+ A governed UDF in the same AWS Region as the job, with `EXECUTE` granted to the job's runtime role.
+ The UDF class is a supported UDF type. For supported types and Java versions, see [Using governed UDFs with Lake Formation fine-grained access control](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-fgac-governed-udfs.html) in the *Amazon EMR Release Guide*.
+ The runtime role has the IAM permissions described in [Granting IAM permissions to the job runtime role](#lake-formation-governed-udfs-iam).

## Granting IAM permissions to the job runtime role
<a name="lake-formation-governed-udfs-iam"></a>

In addition to the permissions your job already needs, the runtime role needs the permissions in the following table.


| Action | Purpose | 
| --- |--- |
| glue:GetUserDefinedFunction | Reads the UDF's metadata, such as the Amazon S3 location of its JAR. | 
| lakeformation:GetDataAccess | Existing requirement for Lake Formation data access. | 
| lakeformation:GetTemporaryGlueFunctionCredentials | Gets temporary credentials, scoped to each UDF, that the user driver uses to download the UDF's JARs. | 

The following example IAM policy grants the runtime role permission to read UDF metadata and to get temporary credentials from Lake Formation.

```json
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "GlueGovernedUdfAccess",
      "Effect": "Allow",
      "Action": "glue:GetUserDefinedFunction",
      "Resource": [
        "arn:aws:glue:{{aa-example-1}}:{{111122223333}}:catalog",
        "arn:aws:glue:{{aa-example-1}}:{{111122223333}}:database/{{my_database}}",
        "arn:aws:glue:{{aa-example-1}}:{{111122223333}}:userDefinedFunction/{{my_database}}/{{my_function}}"
      ]
    },
    {
      "Sid": "LakeFormationGovernedUdfAccess",
      "Effect": "Allow",
      "Action": [
        "lakeformation:GetDataAccess",
        "lakeformation:GetTemporaryGlueFunctionCredentials"
      ],
      "Resource": "*"
    }
  ]
}
```

In the policy, replace the following values:
+ {{111122223333}} with your AWS account ID.
+ {{aa-example-1}} with your AWS Region.
+ {{my\_database}} and {{my\_function}} with the database and name of the governed UDF.

Use `"Resource": "*"` for the Lake Formation actions. Their IAM resource is the Lake Formation catalog, not an AWS Glue resource ARN.

These IAM permissions are separate from Lake Formation permissions. The runtime role still needs the `EXECUTE` grant on each governed UDF in Lake Formation.

## Declaring governed UDFs for a job
<a name="lake-formation-governed-udfs-job"></a>

Add the `--lakeformation-artifacts` parameter to the job's default arguments (`CreateJob` or `UpdateJob`). You can also override it for a single run (`StartJobRun`) or set it in a trigger's job action. The value is a comma-separated list of governed UDF ARNs:
+ Key: `--lakeformation-artifacts`
+ Value: `arn:aws:glue:{{aa-example-1}}:{{111122223333}}:userDefinedFunction/{{my_database}}/{{my_function}}`

Don't use the Spark property `spark.aws.lakeformation.artifacts` in AWS Glue. Only the `--lakeformation-artifacts` job parameter makes the UDFs available in system space.

The following rules apply:
+ Each ARN must have the format `arn:{{partition}}:glue:{{region}}:{{account-id}}:userDefinedFunction/{{database-name}}/{{function-name}}`.
+ You can declare up to 10 UDFs. The list can't contain duplicates or empty entries.
+ Each UDF must be in the same Region and partition as the job.
+ The JAR files of all declared UDFs must have distinct file names.

The following AWS CLI command creates a job that uses fine-grained access control and declares one governed UDF.

```bash
aws glue create-job \
  --name {{my-governed-udf-job}} \
  --role arn:aws:iam::{{111122223333}}:role/{{MyGlueJobRole}} \
  --glue-version 6.1 \
  --worker-type G.1X \
  --number-of-workers 5 \
  --command '{"Name":"glueetl","ScriptLocation":"s3://{{amzn-s3-demo-bucket}}/scripts/{{my_script.py}}"}' \
  --default-arguments '{
    "--enable-lakeformation-fine-grained-access": "true",
    "--lakeformation-artifacts": "arn:aws:glue:{{aa-example-1}}:{{111122223333}}:userDefinedFunction/{{my_database}}/{{my_function}}"
  }'
```

In the command, replace the following values:
+ {{my-governed-udf-job}} with a name for the job.
+ {{111122223333}} with your AWS account ID.
+ {{MyGlueJobRole}} with the job's runtime role.
+ {{amzn-s3-demo-bucket}} and {{my\_script.py}} with the Amazon S3 location of your script.
+ {{aa-example-1}}, {{my\_database}}, and {{my\_function}} with the Region, database, and name of the governed UDF.

## Declaring governed UDFs for an interactive session
<a name="lake-formation-governed-udfs-session"></a>

Add the `--lakeformation-artifacts` parameter to the session's default arguments (`CreateSession`). The same rules apply as for a job.

The following AWS CLI command creates an interactive session that uses fine-grained access control and declares one governed UDF.

```bash
aws glue create-session \
  --id {{my-governed-udf-session}} \
  --role arn:aws:iam::{{111122223333}}:role/{{MyGlueJobRole}} \
  --glue-version 6.1 \
  --worker-type G.1X \
  --number-of-workers 5 \
  --command '{"Name":"glueetl"}' \
  --default-arguments '{
    "--enable-lakeformation-fine-grained-access": "true",
    "--lakeformation-artifacts": "arn:aws:glue:{{aa-example-1}}:{{111122223333}}:userDefinedFunction/{{my_database}}/{{my_function}}"
  }'
```

In the command, replace the following values:
+ {{my-governed-udf-session}} with an ID for the session.
+ {{111122223333}} with your AWS account ID.
+ {{MyGlueJobRole}} with the session's runtime role.
+ {{aa-example-1}}, {{my\_database}}, and {{my\_function}} with the Region, database, and name of the governed UDF.

## Reviewing security considerations
<a name="lake-formation-governed-udfs-security"></a>

Review the following security considerations before you grant `EXECUTE` on a governed UDF:
+ **Granting `EXECUTE` on a governed UDF means trusting its code.** Declaring a governed UDF loads its JAR and initializes its class in the system driver, where the code can call AWS services as the runtime role. Grant `EXECUTE` only on UDFs whose code you have reviewed. A new governed UDF automatically gets `SELECT` on all tables in its catalog. To narrow that grant, see [Governing AWS Glue Data Catalog user-defined functions with Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/governing-user-defined-functions.html) in the *Lake Formation Developer Guide*.
+ **Revoking access doesn't stop running work.** After you revoke `EXECUTE`, new job runs and sessions can't load the UDF. To stop access right away, stop the job runs and sessions that use it.
+ **Protect the JAR's Amazon S3 location.** Give write access to that location only to the authors of the UDF code. In jobs that don't use fine-grained access control, a job can run a governed UDF without declaring it if the runtime role can read its JAR in Amazon S3. For more information, see [Using governed UDFs with Lake Formation fine-grained access control](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-fgac-governed-udfs.html) in the *Amazon EMR Release Guide*.
+ **System logs can include output from governed UDFs.** For how to access system logs, see [Debugging fine-grained access control (FGAC) jobs and sessions](debugging-fgac-jobs-sessions.md).

## Resolving governed UDF errors
<a name="lake-formation-governed-udfs-troubleshooting"></a>

If a job run fails while it loads a governed UDF, the error message that `GetJobRun` returns can show only `BrokenPipeError`. To find the cause, check the job run's error log in the `/aws-glue/jobs/error` log group in Amazon CloudWatch Logs. For system logs, see [Debugging fine-grained access control (FGAC) jobs and sessions](debugging-fgac-jobs-sessions.md).

The following table lists errors that AWS Glue returns for governed UDFs. For errors from the Spark engine, see the error reference in [Using governed UDFs with Lake Formation fine-grained access control](https://docs.aws.amazon.com/emr/latest/ReleaseGuide/emr-spark-fgac-governed-udfs.html) in the *Amazon EMR Release Guide*.


| Error | Cause and fix | 
| --- |--- |
| Invalid Glue UserDefinedFunction ARN: {{arn}}. Expected format: arn:<partition>:glue:<region>:<account>:userDefinedFunction/<database>/<function-name> | An entry in --lakeformation-artifacts isn't a valid UDF ARN. Fix the ARN. | 
| Lake Formation artifact ARN region must match the job region ({{region}}): {{arn}} | Use a UDF in the same Region as the job. | 
| Number of Lake Formation artifact ARNs ({{n}}) exceeds the maximum allowed (10). | --lakeformation-artifacts declares more than 10 UDFs. Declare 10 or fewer. | 
| The argument --lakeformation-artifacts is not supported for {{command}} jobs. | Governed UDFs are supported only for Spark jobs (glueetl) and Spark interactive sessions. Remove the parameter from streaming, Ray, and Python shell jobs. | 
| AccessDeniedException: Lake Formation artifact authorization failed: Insufficient Lake Formation permission(s): Required EXECUTE on UserDefinedFunction: {{function-name}} | The runtime role doesn't have EXECUTE on the UDF. Ask your data lake administrator to grant it. | 
| Artifact {{arn}} failed integrity verification: S3 object {{s3-uri}} was modified after it was approved (approved LastModified {{timestamp}}). Have the updated artifact re-approved. | The JAR's Amazon S3 object has a newer last-modified time than Lake Formation recorded, even if the content is the same. Update the UDF with UpdateUserDefinedFunction (requires Lake Formation ALTER on the UDF) so that Lake Formation records the replacement JAR's last-modified time. | 
| Failed to load custom code artifacts on the driver. (job run fails right after it starts) | For jobs that don't use fine-grained access control, permissions are checked when the job run loads the JAR, not when the run starts. Check the driver's error log for the cause. | 