

# Identity and access management in Athena
Identity and access management

Amazon Athena uses [AWS Identity and Access Management (IAM)](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html) policies to restrict access to Athena operations. For a full list of permissions for Athena, see [Actions, resources, and condition keys for Amazon Athena](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonathena.html) in the *Service Authorization Reference*.

Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

The permissions required to run Athena queries include the following:
+ Amazon S3 locations where the underlying data to query is stored. For more information, see [Identity and access management in Amazon S3](https://docs.aws.amazon.com/AmazonS3/latest/dev/s3-access-control.html) in the *Amazon Simple Storage Service User Guide*.
+ Metadata and resources that you store in the AWS Glue Data Catalog, such as databases and tables, including additional actions for encrypted metadata. For more information, see [Setting up IAM permissions for AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/getting-started-access.html) and [Setting up encryption in AWS Glue](https://docs.aws.amazon.com/glue/latest/dg/set-up-encryption.html) in the *AWS Glue Developer Guide*.
+ Athena API actions. For a list of API actions in Athena, see [Actions](https://docs.aws.amazon.com/athena/latest/APIReference/API_Operations.html) in the *Amazon Athena API Reference*.

The following topics provide more information about permissions for specific areas of Athena.

**Topics**
+ [AWS managed policies](security-iam-awsmanpol.md)
+ [

# Data perimeters
](data-perimeters.md)
+ [Access through JDBC and ODBC connections](policy-actions.md)
+ [

# Control access to Amazon S3 from Athena
](s3-permissions.md)
+ [Cross-account access to S3 buckets](cross-account-permissions.md)
+ [Access to databases and tables in AWS Glue](fine-grained-access-to-glue-resources.md)
+ [Cross-account access to AWS Glue data catalogs](security-iam-cross-account-glue-catalog-access.md)
+ [Access to encrypted metadata in the Data Catalog](access-encrypted-data-glue-data-catalog.md)
+ [Access to workgroups and tags](workgroups-access.md)
+ [

# Use IAM policies to control workgroup access
](workgroups-iam-policy.md)
+ [IAM Identity Center enabled workgroups](workgroups-identity-center.md)
+ [Configure minimum encryption](workgroups-minimum-encryption.md)
+ [

# Configure access to prepared statements
](security-iam-athena-prepared-statements.md)
+ [Use CalledVia context keys](security-iam-athena-calledvia.md)
+ [

# Allow access to the Athena Data Connector for External Hive Metastore
](hive-metastore-iam-access.md)
+ [

# Allow Lambda function access to external Hive metastores
](hive-metastore-iam-access-lambda.md)
+ [

# Permissions required to create connector and Athena catalog
](athena-catalog-access.md)
+ [Allow access to Athena Federated Query](federated-query-iam-access.md)
+ [Allow access to UDFs](udf-iam-access.md)
+ [

# Allow access for ML with Athena
](machine-learning-iam-access.md)
+ [

# Enable federated access to the Athena API
](access-federation-saml.md)

# AWS managed policies for Amazon Athena
AWS managed policies

An AWS managed policy is a standalone policy that is created and administered by AWS. AWS managed policies are designed to provide permissions for many common use cases so that you can start assigning permissions to users, groups, and roles.

Keep in mind that AWS managed policies might not grant least-privilege permissions for your specific use cases because they're available for all AWS customers to use. We recommend that you reduce permissions further by defining [ customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#customer-managed-policies) that are specific to your use cases.

You cannot change the permissions defined in AWS managed policies. If AWS updates the permissions defined in an AWS managed policy, the update affects all principal identities (users, groups, and roles) that the policy is attached to. AWS is most likely to update an AWS managed policy when a new AWS service is launched or new API operations become available for existing services.

For more information, see [AWS managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html#aws-managed-policies) in the *IAM User Guide*.

## Considerations when using managed policies with Athena


Managed policies are easy to use and are updated automatically with the required actions as the service evolves. When using managed policies with Athena, keep the following points in mind:
+ To allow or deny Amazon Athena service actions for yourself or other users using AWS Identity and Access Management (IAM), you attach identity-based policies to principals, such as users or groups. 
+ Each identity-based policy consists of statements that define the actions that are allowed or denied. For more information and step-by-step instructions for attaching a policy to a user, see [Attaching managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-using.html#attach-managed-policy-console) in the *IAM User Guide*. For a list of actions, see the [Amazon Athena API Reference](https://docs.aws.amazon.com/athena/latest/APIReference/).
+  *Customer-managed* and *inline* identity-based policies allow you to specify more detailed Athena actions within a policy to fine-tune access. We recommend that you use the `AmazonAthenaFullAccess` policy as a starting point and then allow or deny specific actions listed in the [Amazon Athena API Reference](https://docs.aws.amazon.com/athena/latest/APIReference/). For more information about inline policies, see [Managed policies and inline policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_managed-vs-inline.html) in the *IAM User Guide*.
+ If you also have principals that connect using JDBC, you must provide the JDBC driver credentials to your application. For more information, see [Control access through JDBC and ODBC connections](policy-actions.md).
+ If you have encrypted the AWS Glue Data Catalog, you must specify additional actions in the identity-based IAM policies for Athena. For more information, see [Configure access from Athena to encrypted metadata in the AWS Glue Data Catalog](access-encrypted-data-glue-data-catalog.md).
+ If you create and use workgroups, make sure your policies include relevant access to workgroup actions. For detailed information, see [Use IAM policies to control workgroup access](workgroups-iam-policy.md) and [Example workgroup policies](example-policies-workgroup.md). 

## AWS managed policy: AmazonAthenaFullAccess
AmazonAthenaFullAccess

The `AmazonAthenaFullAccess` managed policy grants full access to Athena.

To provide access, add permissions to your users, groups, or roles:
+ Users and groups in AWS IAM Identity Center:

  Create a permission set. Follow the instructions in [Create a permission set](https://docs.aws.amazon.com//singlesignon/latest/userguide/howtocreatepermissionset.html) in the *AWS IAM Identity Center User Guide*.
+ Users managed in IAM through an identity provider:

  Create a role for identity federation. Follow the instructions in [Create a role for a third-party identity provider (federation)](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-idp.html) in the *IAM User Guide*.
+ IAM users:
  + Create a role that your user can assume. Follow the instructions in [Create a role for an IAM user](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_roles_create_for-user.html) in the *IAM User Guide*.
  + (Not recommended) Attach a policy directly to a user or add a user to a user group. Follow the instructions in [Adding permissions to a user (console)](https://docs.aws.amazon.com//IAM/latest/UserGuide/id_users_change-permissions.html#users_change_permissions-add-console) in the *IAM User Guide*.

### Permissions groupings


The `AmazonAthenaFullAccess` policy is grouped into the following sets of permissions.
+ **`athena`** – Allows principals access to Athena resources.
+ **`glue`** – Allows principals access to AWS Glue Catalogs, databases, tables, and partitions. This is required so that the principal can use the AWS Glue Data Catalogs with Athena.
+ **`s3`** – Allows the principal to write and read query results from Amazon S3, to read publically available Athena data examples that reside in Amazon S3, and to list buckets. This is required so that the principal can use Athena to work with Amazon S3.
+ **`sns`** – Allows principals to list Amazon SNS topics and get topic attributes. This enables principals to use Amazon SNS topics with Athena for monitoring and alert purposes.
+ **`cloudwatch`** – Allows principals to create, read, and delete CloudWatch alarms. For more information, see [Use CloudWatch and EventBridge to monitor queries and control costs](workgroups-control-limits.md).
+ **`lakeformation`** – Allows principals to request temporary credentials to access data in a data lake location that is registered with Lake Formation. For more information, see [Underlying data access control](https://docs.aws.amazon.com/lake-formation/latest/dg/access-control-underlying-data.html) in the *AWS Lake Formation Developer Guide*.
+ **`datazone`** – Allows principals to list Amazon DataZone projects, domains, and environments. For information about using DataZone in Athena, see [Use Amazon DataZone in Athena](datazone-using.md).
+ **`pricing`** – Provides access to AWS Billing and Cost Management. For more information, see [GetProducts](https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_pricing_GetProducts.html) in the *AWS Billing and Cost Management API Reference*.

To view the permissions for this policy, see [AmazonAthenaFullAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AmazonAthenaFullAccess.html) in the AWS Managed Policy Reference.

**Note**  
You must explicitly allow access to service-owned Amazon S3 buckets to store example queries and sample dataset. For more information, see [Data perimeters](data-perimeters.md).

## AWS managed policy: AWSQuicksightAthenaAccess
AWSQuicksightAthenaAccess

`AWSQuicksightAthenaAccess` grants access to actions that Quick requires for integration with Athena. You can attach the `AWSQuicksightAthenaAccess` policy to your IAM identities. Attach this policy only to principals who use Quick with Athena. This policy includes some actions for Athena that are either deprecated and not included in the current public API, or that are used only with the JDBC and ODBC drivers.

### Permissions groupings


The `AWSQuicksightAthenaAccess` policy is grouped into the following sets of permissions.
+ **`athena`** – Allows the principal to run queries on Athena resources.
+ **`glue`** – Allows principals access to AWS Glue Catalogs, databases, tables, and partitions. This is required so that the principal can use the AWS Glue Data Catalogs with Athena.
+ **`s3`** – Allows the principal to write and read query results from Amazon S3.
+ **`lakeformation`** – Allows principals to request temporary credentials to access data in a data lake location that is registered with Lake Formation. For more information, see [Underlying data access control](https://docs.aws.amazon.com/lake-formation/latest/dg/access-control-underlying-data.html) in the *AWS Lake Formation Developer Guide*.

To view the permissions for this policy, see [AWSQuicksightAthenaAccess](https://docs.aws.amazon.com/aws-managed-policy/latest/reference/AWSQuicksightAthenaAccess.html) in the AWS Managed Policy Reference.

## Athena updates to AWS managed policies
Policy updates

View details about updates to AWS managed policies for Athena since this service began tracking these changes.


| Change | Description | Date | 
| --- | --- | --- | 
| [AWSQuicksightAthenaAccess](#awsquicksightathenaaccess-managed-policy) – Updates to existing policies | The glue:GetCatalog and glue:GetCatalogs permissions were added to enable Athena users to access to SageMaker AI Lakehouse catalogs. | January 02, 2025 | 
| [AmazonAthenaFullAccess](#amazonathenafullaccess-managed-policy) – Update to existing policy | The glue:GetCatalog and glue:GetCatalogs permissions were added to enable Athena users to access to SageMaker AI Lakehouse catalogs. | January 02, 2025 | 
| [AmazonAthenaFullAccess](#amazonathenafullaccess-managed-policy) – Update to existing policy |  Enables Athena to use the publicly documented AWS Glue `GetCatalogImportStatus` API to retrieve catalog import status.  | June 18, 2024 | 
|  [AmazonAthenaFullAccess](#amazonathenafullaccess-managed-policy) – Update to existing policy  |  The `datazone:ListDomains`, `datazone:ListProjects`, and `datazone:ListAccountEnvironments` permissions were added to enable Athena users to work with Amazon DataZone domains, projects, and environments. For more information, see [Use Amazon DataZone in Athena](datazone-using.md).  | January 3, 2024 | 
|  [AmazonAthenaFullAccess](#amazonathenafullaccess-managed-policy) – Update to existing policy  |  The `glue:StartColumnStatisticsTaskRun`, `glue:GetColumnStatisticsTaskRun`, and `glue:GetColumnStatisticsTaskRuns` permissions were added to give Athena the right to call AWS Glue to retrieve statistics for the cost-based optimizer feature. For more information, see [Use the cost-based optimizer](cost-based-optimizer.md).  | January 3, 2024 | 
|  [AmazonAthenaFullAccess](#amazonathenafullaccess-managed-policy) – Update to existing policy  |  Athena added `pricing:GetProducts` to provide access to AWS Billing and Cost Management. For more information, see [GetProducts](https://docs.aws.amazon.com/aws-cost-management/latest/APIReference/API_pricing_GetProducts.html) in the *AWS Billing and Cost Management API Reference*.  | January 25, 2023 | 
|  [AmazonAthenaFullAccess](#amazonathenafullaccess-managed-policy) – Update to existing policy  |  Athena added `cloudwatch:GetMetricData` to retrieve CloudWatch metric values. For more information, see [GetMetricData](https://docs.aws.amazon.com/AmazonCloudWatch/latest/APIReference/API_GetMetricData.html) in the *Amazon CloudWatch API Reference*.  | November 14, 2022 | 
|  [AmazonAthenaFullAccess](#amazonathenafullaccess-managed-policy) and [AWSQuicksightAthenaAccess](#awsquicksightathenaaccess-managed-policy) – Updates to existing policies  |  Athena added `s3:PutBucketPublicAccessBlock` to enable the blocking of public access on the buckets created by Athena.  | July 7, 2021 | 
|  Athena started tracking changes  |  Athena started tracking changes for its AWS managed policies.  | July 7, 2021 | 

# Data perimeters


A [data perimeter](https://aws.amazon.com/identity/data-perimeters-on-aws/) is a set of permissions guardrails in your AWS environment you use to help ensure that only your trusted identities are accessing trusted resources from expected networks. 

Amazon Athena uses service-owned Amazon S3 buckets to store example queries and sample datasets. If you are using data perimeters to control access in your environment, you must explicitly allow access to these service-owned resources to use the corresponding Athena features. 

 The following table lists the ARN of the Amazon S3 bucket that Athena needs to access, required permissions, identity used by Athena, and the features that rely on the S3 bucket. To allow access, replace `<region>` in the bucket ARN with your actual AWS Region and allowlist this bucket based on your Amazon S3 access controls. 


**Data perimeters that Athena uses**  

| Resource ARN | Required permissions | Identity used for access | Access scenarios | 
| --- | --- | --- | --- | 
|  arn:aws:s3:::athena-examples-<region>  | s3:GetObjects3:ListBucket | The IAM principal accessing Athena. |  [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/athena/latest/ug/data-perimeters.html)  | 

# Control access through JDBC and ODBC connections
Access through JDBC and ODBC connections

To gain access to AWS services and resources, such as Athena and the Amazon S3 buckets, provide the JDBC or ODBC driver credentials to your application. If you are using the JDBC or ODBC driver, ensure that the IAM permissions policy includes all of the actions listed in [AWS managed policy: AWSQuicksightAthenaAccess](security-iam-awsmanpol.md#awsquicksightathenaaccess-managed-policy).

Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

## Authentication methods


The Athena JDBC and ODBC drivers support SAML 2.0-based authentication, including the following identity providers:
+ Active Directory Federation Services (AD FS)
+ Azure Active Directory (AD)
+ Okta 
+ PingFederate

For more information, see the installation and configuration guides for the respective drivers, downloadable in PDF format from the [JDBC](connect-with-jdbc.md) and [ODBC](connect-with-odbc.md) driver pages. For additional related information, see the following:
+ [Enable federated access to the Athena API](access-federation-saml.md)
+ [Use Lake Formation and JDBC or ODBC drivers for federated access to Athena](security-athena-lake-formation-jdbc.md)
+  [Configure single sign-on using ODBC, SAML 2.0, and the Okta Identity Provider](okta-saml-sso.md)

For information about the latest versions of the JDBC and ODBC drivers and their documentation, see [Connect to Amazon Athena with JDBC](connect-with-jdbc.md) and [Connect to Amazon Athena with ODBC](connect-with-odbc.md).

# Control access to Amazon S3 from Athena


You can grant access to Amazon S3 locations using identity-based policies, bucket resource policies, access point policies, or any combination of the above. When actors interact with Athena, their permissions pass through Athena to determine what Athena can access. This means that users must have permission to access Amazon S3 buckets in order to query them with Athena.

Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

Note that requests to Amazon S3 come from a private IPv4 address for Athena, not the source IP specified in `aws:SourceIp`. For this reason, you cannot use the `aws:SourceIp` condition to deny access to Amazon S3 actions in a given IAM policy. You also cannot restrict or allow access to Amazon S3 resources based on the `aws:SourceVpc` or `aws:SourceVpce` condition keys.

**Note**  
Athena workgroups that use IAM Identity Center authentication require that S3 Access Grants be configured to use trusted identity propagation identities. For more information, see [S3 Access Grants and directory identities](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-grants-directory-ids.html) in the *Amazon Simple Storage Service User Guide*.

**Topics**
+ [Identity-based policies](#s3-permissions-identity-based-policies)
+ [Bucket resource policies](#s3-permissions-bucket-resource-policies)
+ [Access point policies](#s3-permissions-aliases)
+ [CalledVia context keys](#s3-permissions-calledvia)
+ [

## Additional resources
](#s3-permissions-additional-resources)

## Use identity-based policies to control access to Amazon S3 buckets
Identity-based policies

Identity-based policies are attached to an IAM user, group, or role. These policies let you specify what that identity can do (its permissions). You can use identity-based policies to control access to your Amazon S3 buckets.

The following identity-based policy allows `Read` and `Write` access to objects in a specific Amazon S3 bucket. To use this policy, replace the *italicized placeholder text* with your own values.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "ListObjectsInBucket",
            "Effect": "Allow",
            "Action": [
                "s3:ListBucket"
            ],
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket"
            ]
        },
        {
            "Sid": "AllObjectActions",
            "Effect": "Allow",
            "Action": "s3:*Object",
            "Resource": [
                "arn:aws:s3:::amzn-s3-demo-bucket/*"
            ]
        }
    ]
}
```

------

## Use bucket resource policies to control access to Amazon S3 buckets
Bucket resource policies

You can use Amazon S3 bucket policies to secure access to objects in your buckets so that only users with the appropriate permissions can access them. For guidance on creating your Amazon S3 policy, see [Adding a bucket policy by using the Amazon S3 console](https://docs.aws.amazon.com/AmazonS3/latest/userguide/add-bucket-policy.html) in the *Amazon S3 User Guide*.

The following example permissions policy limits a user to reading objects that have the `environment: production` tag key and value. The example policy uses the `s3:ExistingObjectTag` condition key to specify the tag key and value.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Principal": {
                "AWS": "arn:aws:iam::111122223333:role/JohnDoe"
            },
            "Effect": "Allow",
            "Action": [
                "s3:GetObject",
                "s3:GetObjectVersion"
            ],
            "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*",
            "Condition": {
                "StringEquals": {
                    "s3:ExistingObjectTag/environment": "production"
                }
            }
        }
    ]
}
```

------

For more bucket policy examples, see [Examples of Amazon S3 bucket policies](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-bucket-policies.html) in the *Amazon S3 User Guide*.

## Use Amazon S3 access points for more precise control over bucket access
Access point policies

If you have a shared dataset in an Amazon S3 bucket, maintaining a single bucket policy that manages access for hundreds of use cases can be challenging.

Amazon S3 bucket access points, policies, and aliases can help solve this issue. A bucket can have multiple access points, each with a policy that controls access to the bucket in a different way. 

For each access point that you create, Amazon S3 generates an alias that represents the access point. Because the alias is in Amazon S3 bucket name format, you can use the alias in the `LOCATION` clause of your `CREATE TABLE` statements in Athena. Athena's access to the bucket is then controlled by the policy for the access point that the alias represents. 

For more information, see [Specify a table location in Amazon S3](tables-location-format.md) and [Using access points](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-points.html) in the *Amazon S3 User Guide*.

## Use CalledVia context keys to allow only calls from Athena to another service
CalledVia context keys

For added security, you can use the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-calledvia](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-calledvia) global condition context key. The `aws:CalledVia` condition key contains a list of services that you allow to call another service. For example, you can allow `InvokeFunction` calls to AWS Lambda only if the calls come from Athena by specifying the Athena service principal name `athena.amazonaws.com` for the `aws:CalledVia` context key. For more information, see [Use CalledVia context keys for Athena](security-iam-athena-calledvia.md).

## Additional resources


For detailed information and examples about how to grant Amazon S3 access, see the following resources:
+ [Example walkthroughs: Managing access](https://docs.aws.amazon.com/AmazonS3/latest/userguide/example-walkthroughs-managing-access.html) in the *Amazon S3 User Guide*.
+ [How can I provide cross-account access to objects that are in Amazon S3 buckets?](https://aws.amazon.com/premiumsupport/knowledge-center/cross-account-access-s3/) in the AWS Knowledge Center.
+ [Configure cross-account access in Athena to Amazon S3 buckets](cross-account-permissions.md).

# Configure cross-account access in Athena to Amazon S3 buckets
Cross-account access to S3 buckets

A common Amazon Athena scenario is granting access to users in an account different from the bucket owner so that they can perform queries. In this case, use a bucket policy to grant access.

**Note**  
For information about cross-account access to AWS Glue data catalogs from Athena, see [Configure cross-account access to AWS Glue data catalogs](security-iam-cross-account-glue-catalog-access.md).

The following example bucket policy, created and applied to bucket `s3://amzn-s3-demo-bucket` by the bucket owner, grants access to all users in account `123456789123`, which is a different account.

------
#### [ JSON ]

****  

```
{
   "Version":"2012-10-17",		 	 	 
   "Id": "MyPolicyID",
   "Statement": [
      {
          "Sid": "MyStatementSid",
          "Effect": "Allow",
          "Principal": {
             "AWS": "arn:aws:iam::123456789123:root"
          },
          "Action": [
             "s3:GetBucketLocation",
             "s3:GetObject",
             "s3:ListBucket",
             "s3:ListBucketMultipartUploads",
             "s3:ListMultipartUploadParts",
             "s3:AbortMultipartUpload"
          ],
          "Resource": [
             "arn:aws:s3:::amzn-s3-demo-bucket",
             "arn:aws:s3:::amzn-s3-demo-bucket/*"
          ]
       }
    ]
 }
```

------

To grant access to a particular user in an account, replace the `Principal` key with a key that specifies the user instead of `root`. For example, for user profile `Dave`, use `arn:aws:iam::123456789123:user/Dave`.

## Configure cross-account access to a bucket encrypted with a custom AWS KMS key


If you have an Amazon S3 bucket that is encrypted with a custom AWS Key Management Service (AWS KMS) key, you might need to grant access to it to users from another Amazon Web Services account.

Granting access to an AWS KMS-encrypted bucket in Account A to a user in Account B requires the following permissions:
+ The bucket policy in Account A must grant access to the role assumed by Account B.
+ The AWS KMS key policy in Account A must grant access to the role assumed by the user in Account B.
+ The AWS Identity and Access Management (IAM) role assumed by Account B must grant access to both the bucket and the key in Account A.

The following procedures describe how to grant each of these permissions.

**To grant access to the bucket in account a to the user in account b**
+ From Account A, [review the S3 bucket policy](https://docs.aws.amazon.com/AmazonS3/latest/userguide/add-bucket-policy.html) and confirm that there is a statement that allows access from the account ID of Account B.

  For example, the following bucket policy allows `s3:GetObject` access to the account ID `111122223333`:

------
#### [ JSON ]

****  

  ```
  {
    "Id": "ExamplePolicy1",
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Sid": "ExampleStmt1",
        "Action": [
          "s3:GetObject"
        ],
        "Effect": "Allow",
        "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*",
        "Principal": {
          "AWS": [
            "111122223333"
          ]
        }
      }
    ]
  }
  ```

------

**To grant access to the user in account b from the AWS KMS key policy in account a**

1. In the AWS KMS key policy for Account A, grant the role assumed by Account B permissions to the following actions:
   +  `kms:Encrypt` 
   +  `kms:Decrypt` 
   +  `kms:ReEncrypt*` 
   +  `kms:GenerateDataKey*` 
   +  `kms:DescribeKey` 

   The following example grants key access to only one IAM role.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Sid": "AllowUseOfTheKey",
               "Effect": "Allow",
               "Principal": {
                   "AWS": "arn:aws:iam::111122223333:role/role_name"
               },
               "Action": [
                   "kms:Encrypt",
                   "kms:Decrypt",
                   "kms:ReEncrypt*",
                   "kms:GenerateDataKey*",
                   "kms:DescribeKey"
               ],
               "Resource": "*"
           }
       ]
   }
   ```

------

1. From Account A, review the key policy [using the AWS Management Console policy view](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-modifying.html#key-policy-modifying-how-to-console-policy-view).

1. In the key policy, verify that the following statement lists Account B as a principal.

   ```
   "Sid": "Allow use of the key" 
   ```

1. If the `"Sid": "Allow use of the key"` statement is not present, perform the following steps:

   1. Switch to view the key policy [using the console default view](https://docs.aws.amazon.com/kms/latest/developerguide/key-policy-modifying.html#key-policy-modifying-how-to-console-default-view). 

   1.  Add Account B's account ID as an external account with access to the key.

**To grant access to the bucket and the key in account a from the IAM role assumed by account b**

1. From Account B, open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. Open the IAM role associated with the user in Account B.

1. Review the list of permissions policies applied to IAM role.

1. Ensure that a policy is applied that grants access to the bucket.

   The following example statement grants the IAM role access to the `s3:GetObject` and `s3:PutObject` operations on the bucket `amzn-s3-demo-bucket`:

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Sid": "ExampleStmt2",
         "Action": [
           "s3:GetObject",
           "s3:PutObject"
         ],
         "Effect": "Allow",
         "Resource": "arn:aws:s3:::amzn-s3-demo-bucket/*"
       }
     ]
   }
   ```

------

1. Ensure that a policy is applied that grants access to the key.
**Note**  
If the IAM role assumed by Account B already has [administrator access](https://docs.aws.amazon.com/IAM/latest/UserGuide/getting-started_create-admin-group.html), then you don't need to grant access to the key from the user's IAM policies.

   The following example statement grants the IAM role access to use the key `arn:aws:kms:us-west-2:123456789098:key/111aa2bb-333c-4d44-5555-a111bb2c33dd`.

------
#### [ JSON ]

****  

   ```
   {
     "Version":"2012-10-17",		 	 	 
     "Statement": [
       {
         "Sid": "ExampleStmt3",
         "Action": [
           "kms:Decrypt",
           "kms:DescribeKey",
           "kms:Encrypt",
           "kms:GenerateDataKey",
           "kms:ReEncrypt*"
         ],
         "Effect": "Allow",
         "Resource": "arn:aws:kms:us-west-2:123456789098:key/111aa2bb-333c-4d44-5555-a111bb2c33dd"
       }
     ]
   }
   ```

------

## Configure cross-account access to bucket objects


Objects that are uploaded by an account (Account C) other than the bucket's owning account (Account A) might require explicit object-level ACLs that grant read access to the querying account (Account B). To avoid this requirement, Account C should assume a role in Account A before it places objects in Account A's bucket. For more information, see [How can I provide cross-account access to objects that are in Amazon S3 buckets?](https://aws.amazon.com/premiumsupport/knowledge-center/cross-account-access-s3/).

# Configure access to databases and tables in the AWS Glue Data Catalog
Access to databases and tables in AWS Glue

If you use the AWS Glue Data Catalog with Amazon Athena, you can define resource-level policies for the database and table Data Catalog objects that are used in Athena.

**Note**  
This topic discusses database- and table-level security. For information about configuring column-, row-, and cell-level security, see [Data filtering and cell-level security in Lake Formation](https://docs.aws.amazon.com/lake-formation/latest/dg/data-filtering.html). 

You define resource-level permissions in IAM identity-based policies.

**Important**  
This section discusses resource-level permissions in IAM identity-based policies. These are different from resource-based policies. For more information about the differences, see [Identity-based policies and resource-based policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html) in the *IAM User Guide*.

See the following topics for these tasks: 


| To perform this task | See the following topic | 
| --- | --- | 
| Create an IAM policy that defines access to resources | [Creating IAM policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the IAM User Guide. | 
| Learn about IAM identity-based policies used in AWS Glue | [ Identity-based policies (IAM policies)](https://docs.aws.amazon.com/glue/latest/dg/using-identity-based-policies.html) in the AWS Glue Developer Guide.  | 

 **In this section** 
+  [Limitations](#access-to-glue-resources-limitations) 
+  [Configure AWS Glue access to your catalog and database per AWS Region](#full-access-to-default-db-per-region) 
+  [About access control for table partitions and versions in AWS Glue](#access-to-glue-resources-table-partitions-and-versions) 
+  [Examples of database and table-level permissions](#examples-fine-grained-table-database-policies) 

## Limitations


Consider the following limitations when you use database and table-level access control for the AWS Glue Data Catalog and Athena:
+ IAM Identity Center enabled Athena workgroups require Lake Formation be configured to use IAM Identity Center identities. For more information, see [Integrating IAM Identity Center](https://docs.aws.amazon.com/lake-formation/latest/dg/identity-center-integration.html) in the *AWS Lake Formation Developer Guide*. 
+ You can limit access only to databases and tables. These controls apply at the table level. You cannot limit access to individual partitions within a table. For more information, see [About access control for table partitions and versions in AWS Glue](#access-to-glue-resources-table-partitions-and-versions).
+ The AWS Glue Data Catalog contains the following resources: `CATALOG`, `DATABASE`, `TABLE`, and `FUNCTION`. 
**Note**  
From this list, resources that are common between Athena and the AWS Glue Data Catalog are `TABLE`, `DATABASE`, and `CATALOG` for each account. `Function` is specific to AWS Glue. For delete actions in Athena, you must include permissions to AWS Glue actions. See [Examples of database and table-level permissions](#examples-fine-grained-table-database-policies).

  The hierarchy is as follows: `CATALOG` is an ancestor of all `DATABASES` in each account, and each `DATABASE` is an ancestor for all of its `TABLES` and `FUNCTIONS`. For example, for a table named `table_test` that belongs to a database `db` in the catalog in your account, its ancestors are `db` and the catalog in your account. For the `db` database, its ancestor is the catalog in your account, and its descendants are tables and functions. For more information about the hierarchical structure of resources, see [List of ARNs in Data Catalog](https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html#data-catalog-resource-arns) in the *AWS Glue Developer Guide*. 
+ For any non-delete Athena action on a resource, such as `CREATE DATABASE`, `CREATE TABLE`, `SHOW DATABASE`, `SHOW TABLE`, or `ALTER TABLE`, you need permissions to call this action on the resource (table or database) and all ancestors of the resource in the Data Catalog. For example, for a table, its ancestors are the database to which it belongs, and the catalog for the account. For a database, its ancestor is the catalog for the account. See [Examples of database and table-level permissions](#examples-fine-grained-table-database-policies). 
+ For a delete action in Athena, such as `DROP DATABASE` or `DROP TABLE`, you also need permissions to call the delete action on all ancestors and descendants of the resource in the Data Catalog. For example, to delete a database you need permissions on the database, the catalog, which is its ancestor, and all the tables and user defined functions, which are its descendents. A table does not have descendants. To run `DROP TABLE`, you need permissions to this action on the table, the database to which it belongs, and the catalog. See [Examples of database and table-level permissions](#examples-fine-grained-table-database-policies).

## Configure AWS Glue access to your catalog and database per AWS Region


For Athena to work with the AWS Glue, a policy that grants access to your database and to the AWS Glue Data Catalog in your account per AWS Region is required. To create databases, the `CreateDatabase` permission is also required. In the following example policy, replace the AWS Region, AWS account ID, and database name with those of your own.

```
{
   "Sid": "DatabasePermissions",
   "Effect": "Allow",
   "Action": [
      "glue:GetDatabase", 
      "glue:GetDatabases",
      "glue:CreateDatabase"
   ],
   "Resource": [
     "arn:aws:glue:us-east-1:123456789012:catalog",
     "arn:aws:glue:us-east-1:123456789012:database/default"
   ]
}
```

## About access control for table partitions and versions in AWS Glue


In AWS Glue, tables can have partitions and versions. Table versions and partitions are not considered to be independent resources in AWS Glue. Access to table versions and partitions is given by granting access on the table and ancestor resources for the table. 

For the purposes of access control, the following access permissions apply:
+ Controls apply at the table level. You can limit access only to databases and tables. For example, if you allow access to a partitioned table, this access applies to all partitions in the table. You cannot limit access to individual partitions within a table. 
**Important**  
To run actions in AWS Glue on partitions, permissions for partition actions are required at the catalog, database, and table levels. Having access to partitions within a table is not sufficient. For example, to run `GetPartitions` on table `myTable` in the database `myDB`, you must grant `glue:GetPartitions` permissions on the catalog, `myDB` database, and `myTable` resources. 
+ Access controls do not apply to table versions. As with partitions, access to previous versions of a table is granted through access to the table version APIs in AWS Glue on the table, and to the table ancestors.

For information about permissions on AWS Glue actions, see [AWS Glue API permissions: Actions and resources reference](https://docs.aws.amazon.com/glue/latest/dg/api-permissions-reference.html) in the *AWS Glue Developer Guide*. 

## Examples of database and table-level permissions


The following table lists examples of IAM identity-based policies that allow access to databases and tables in Athena. We recommend that you start with these examples and, depending on your needs, adjust them to allow or deny specific actions to particular databases and tables.

These examples include access to databases and catalogs so that Athena and AWS Glue can work together. For multiple AWS Regions, include similar policies for each of your databases and catalogs, one line for each Region. 

In the examples, replace the `example_db` database and `test` table with your own database and table names.


| DDL statement | Example of an IAM access policy granting access to the resource | 
| --- | --- | 
| ALTER DATABASE | Allows you to modify the properties for the example\$1db database.<pre>{<br />   "Effect": "Allow",<br />   "Action": [<br />      "glue:GetDatabase", <br />      "glue:UpdateDatabase"<br />   ],<br />   "Resource": [<br />     "arn:aws:glue:us-east-1:123456789012:catalog",<br />     "arn:aws:glue:us-east-1:123456789012:database/example_db"<br />   ]<br />}</pre> | 
| CREATE DATABASE | Allows you to create the database named example\$1db.<pre>{<br />   "Effect": "Allow",<br />   "Action": [<br />      "glue:GetDatabase", <br />      "glue:CreateDatabase"<br />   ],<br />   "Resource": [<br />     "arn:aws:glue:us-east-1:123456789012:catalog",<br />     "arn:aws:glue:us-east-1:123456789012:database/example_db"<br />   ]<br />}<br /></pre> | 
| CREATE TABLE | Allows you to create a table named test in the example\$1db database.<pre>{<br />   "Sid": "DatabasePermissions",<br />   "Effect": "Allow",<br />   "Action": [<br />      "glue:GetDatabase", <br />      "glue:GetDatabases"<br />   ],<br />   "Resource": [<br />     "arn:aws:glue:us-east-1:123456789012:catalog",<br />     "arn:aws:glue:us-east-1:123456789012:database/example_db"<br />   ]<br />},<br />{<br />   "Sid": "TablePermissions",<br />   "Effect": "Allow",<br />   "Action": [<br />      "glue:GetTables",<br />      "glue:GetTable",<br />      "glue:GetPartitions",<br />      "glue:CreateTable"<br />   ],<br />   "Resource": [<br />     "arn:aws:glue:us-east-1:123456789012:catalog",<br />     "arn:aws:glue:us-east-1:123456789012:database/example_db",<br />     "arn:aws:glue:us-east-1:123456789012:table/example_db/test"<br />   ]<br />}</pre> | 
| DROP DATABASE | Allows you to drop the example\$1db database, including all tables in it.<pre>{<br />   "Effect": "Allow",<br />   "Action": [<br />      "glue:GetDatabase",<br />      "glue:DeleteDatabase",<br />      "glue:GetTables", <br />      "glue:GetTable", <br />      "glue:DeleteTable" <br />   ],<br />   "Resource": [<br />     "arn:aws:glue:us-east-1:123456789012:catalog",<br />     "arn:aws:glue:us-east-1:123456789012:database/example_db", <br />     "arn:aws:glue:us-east-1:123456789012:table/example_db/*", <br />     "arn:aws:glue:us-east-1:123456789012:userDefinedFunction/example_db/*"<br />   ]<br /> }</pre> | 
| DROP TABLE | Allows you to drop a partitioned table named test in the example\$1db database. If your table does not have partitions, do not include partition actions.<pre>{<br />   "Effect": "Allow",<br />   "Action": [<br />      "glue:GetDatabase",<br />      "glue:GetTable",<br />      "glue:DeleteTable", <br />      "glue:GetPartitions",<br />      "glue:GetPartition",<br />      "glue:DeletePartition" <br />   ],<br />   "Resource": [<br />     "arn:aws:glue:us-east-1:123456789012:catalog",<br />     "arn:aws:glue:us-east-1:123456789012:database/example_db", <br />     "arn:aws:glue:us-east-1:123456789012:table/example_db/test"<br />   ]<br /> }</pre> | 
| MSCK REPAIR TABLE | Allows you to update catalog metadata after you add Hive compatible partitions to the table named test in the example\$1db database.<pre>{<br />    "Effect": "Allow",<br />    "Action": [<br />        "glue:GetDatabase",<br />        "glue:CreateDatabase",<br />        "glue:GetTable",<br />        "glue:GetPartitions",<br />        "glue:GetPartition",<br />        "glue:BatchCreatePartition"<br />    ],<br />    "Resource": [<br />      "arn:aws:glue:us-east-1:123456789012:catalog",<br />      "arn:aws:glue:us-east-1:123456789012:database/example_db", <br />      "arn:aws:glue:us-east-1:123456789012:table/example_db/test"<br />    ]<br />}</pre> | 
| SHOW DATABASES | Allows you to list all databases in the AWS Glue Data Catalog.<pre>{<br />   "Effect": "Allow",<br />   "Action": [<br />      "glue:GetDatabase",<br />      "glue:GetDatabases" <br />   ],<br />   "Resource": [<br />     "arn:aws:glue:us-east-1:123456789012:catalog",<br />     "arn:aws:glue:us-east-1:123456789012:database/*"<br />   ]<br /> }</pre> | 
| SHOW TABLES | Allows you to list all tables in the example\$1db database.<pre>{<br />   "Effect": "Allow",<br />   "Action": [<br />      "glue:GetDatabase",<br />      "glue:GetTables"    <br />   ],<br />   "Resource": [<br />     "arn:aws:glue:us-east-1:123456789012:catalog",<br />     "arn:aws:glue:us-east-1:123456789012:database/example_db",  <br />     "arn:aws:glue:us-east-1:123456789012:table/example_db/*"<br />   ]<br />}</pre> | 

# Configure cross-account access to AWS Glue data catalogs
Cross-account access to AWS Glue data catalogs

You can use Athena's cross-account AWS Glue catalog feature to register an AWS Glue catalog from an account other than your own. After you configure the required IAM permissions for AWS Glue and register the catalog as an Athena [DataCatalog](https://docs.aws.amazon.com/athena/latest/APIReference/API_DataCatalog.html) resource, you can use Athena to run cross-account queries. For information about using the Athena console to register a catalog from another account, see [Register a Data Catalog from another account](data-sources-glue-cross-account.md).

For more information about cross-account access in AWS Glue, see [Granting cross-account access](https://docs.aws.amazon.com/glue/latest/dg/cross-account-access.html) in the *AWS Glue Developer Guide*.

## Before you start


Because this feature uses existing Athena `DataCatalog` resource APIs and functionality to enable cross-account access, we recommend that you read the following resources before you start:
+ [Connect to data sources](work-with-data-stores.md) - Contains topics on using Athena with AWS Glue, Hive, or Lambda data catalog sources.
+ [Data Catalog example policies](datacatalogs-example-policies.md) - Shows how to write policies that control access to data catalogs.
+ [Use the AWS CLI with Hive metastores](datastores-hive-cli.md) - Shows how to use the AWS CLI with Hive metastores, but contains use cases applicable to other data sources.

## Considerations and limitations


Currently, Athena cross-account AWS Glue catalog access has the following limitations:
+ The feature is available only in AWS Regions where Athena engine version 2 or later is supported. For information about Athena engine versions, see [Athena engine versioning](engine-versions.md). To upgrade the engine version for a workgroup, see [Change Athena engine versions](engine-versions-changing.md).
+ When you register another account's AWS Glue Data Catalog in your account, you create a regional `DataCatalog` resource that is linked to the other account's data in that particular Region only.
+ Currently, `CREATE VIEW` statements that include a cross-account AWS Glue catalog are not supported.
+ Catalogs encrypted using AWS managed keys cannot be queried across accounts. For catalogs that you want to query across accounts, use customer managed keys (`KMS_CMK`) instead. For information about the differences between customer managed keys and AWS managed keys, see [Customer keys and AWS keys](https://docs.aws.amazon.com/kms/latest/developerguide/concepts.html#key-mgmt                     ) in the *AWS Key Management Service Developer Guide*. 

## Get started


In the following scenario, the "borrower" account (666666666666) wants to run a `SELECT` query that refers to the AWS Glue catalog that belongs to the "owner" account (999999999999), as in the following example:

```
SELECT * FROM ownerCatalog.tpch1000.customer
```

In the following procedure, Steps 1a and 1b show how to give the borrower account access to the owner account's AWS Glue resources, from both the borrower and owner's side. The example grants access to the database `tpch1000` and the table `customer`. Change these example names to fit your requirements.

### Step 1a: Create a borrower role with a policy to access the owner's AWS Glue resources


To create borrower account role with a policy to access to the owner account's AWS Glue resources, you can use the AWS Identity and Access Management (IAM) console or the [IAM API](https://docs.aws.amazon.com/IAM/latest/APIReference/API_Operations.html). The following procedures use the IAM console.

**To create a borrower role and policy to access the owner account's AWS Glue resources**

1. Sign in to the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) from the borrower account.

1. In the navigation pane, expand **Access management**, and then choose **Policies**.

1. Choose **Create policy**.

1. For **Policy editor**, choose **JSON**.

1. In the policy editor, enter the following policy, and then modify it according to your requirements:

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Action": "glue:*",
               "Resource": [
                   "arn:aws:glue:us-east-1:999999999999:catalog",
                   "arn:aws:glue:us-east-1:999999999999:database/tpch1000",
                   "arn:aws:glue:us-east-1:999999999999:table/tpch1000/customer"
               ]
           }
       ]
   }
   ```

------

1. Choose **Next**.

1. On the **Review and create** page, for **Policy name**, enter a name for the policy (for example, **CrossGluePolicyForBorrowerRole**).

1. Choose **Create policy**.

1. In the navigation pane, choose **Roles**.

1. Choose **Create role**.

1. On the **Select trusted entity** page, choose **AWS account**, and then choose **Next**.

1. On the **Add permissions** page, enter the name of the policy that you created into the search box (for example, **CrossGluePolicyForBorrowerRole**).

1. Select the check box next to the policy name, and then choose **Next**.

1. On the **Name, review, and create** page, for **Role name**, enter a name for the role (for example, **CrossGlueBorrowerRole**).

1. Choose **Create role**.

### Step 1b: Create an owner policy to grant AWS Glue access to the borrower


To grant AWS Glue access from the owner account (999999999999) to the borrower's role, you can use the AWS Glue console or the AWS Glue [PutResourcePolicy](https://docs.aws.amazon.com/glue/latest/webapi/API_PutResourcePolicy.html) API operation. The following procedure uses the AWS Glue console.

**To grant AWS Glue access to the borrower account from the owner**

1. Sign in to the AWS Glue console at [https://console.aws.amazon.com/glue/](https://console.aws.amazon.com/glue/) from the owner account.

1. In the navigation pane, expand **Data Catalog**, and then choose **Catalog settings**.

1. In the **Permissions** box, enter a policy like the following. For *rolename*, enter the role that the borrower created in Step 1a (for example, **CrossGlueBorrowerRole**). If you want to increase the permission scope, you can use the wild card character `*` for both the database and table resource types.

------
#### [ JSON ]

****  

   ```
   {
       "Version":"2012-10-17",		 	 	 
       "Statement": [
           {
               "Effect": "Allow",
               "Principal": {
                   "AWS": [
                       "arn:aws:iam::666666666666:user/username",
                       "arn:aws:iam::666666666666:role/rolename"
                   ]
               },
               "Action": "glue:*",
               "Resource": [
                   "arn:aws:glue:us-east-1:999999999999:catalog",
                   "arn:aws:glue:us-east-1:999999999999:database/tpch1000",
                   "arn:aws:glue:us-east-1:999999999999:table/tpch1000/customer"
               ]
           }
       ]
   }
   ```

------

After you finish, we recommend that you use the [AWS Glue API](https://docs.aws.amazon.com/glue/latest/dg/aws-glue-api.html) to make some test cross-account calls to confirm that permissions are configured as you expect.

### Step 2: The borrower registers the AWS Glue Data Catalog that belongs to the owner account


The following procedure shows you how to use the Athena console to configure the AWS Glue Data Catalog in the owner Amazon Web Services account as a data source. For information about using API operations instead of the console to register the catalog, see [(Optional) Use the API to register an Athena Data Catalog that belongs to the owner account](#security-iam-cross-account-glue-catalog-access-step-2-api).

**To register an AWS Glue Data Catalog belonging to another account**

1. Open the Athena console at [https://console.aws.amazon.com/athena/](https://console.aws.amazon.com/athena/home).

1. If the console navigation pane is not visible, choose the expansion menu on the left.  
![\[Choose the expansion menu.\]](http://docs.aws.amazon.com/athena/latest/ug/images/nav-pane-expansion.png)

1. Expand **Administration**, and then choose **Data sources**.

1. On the upper right, choose **Create data source**.

1. On the **Choose a data source** page, for **Data sources**, select **S3 - AWS Glue Data Catalog**, and then choose **Next**.

1. On the **Enter data source details** page, in the **AWS Glue Data Catalog** section, for **Choose an AWS Glue Data Catalog**, choose **AWS Glue Data Catalog in another account**.

1. For **Data source details**, enter the following information:
   + **Data source name** – Enter the name that you want to use in your SQL queries to refer to the data catalog in the other account.
   + **Description** – (Optional) Enter a description of the data catalog in the other account.
   + **Catalog ID** – Enter the 12-digit Amazon Web Services account ID of the account to which the data catalog belongs. The Amazon Web Services account ID is the catalog ID.

1. (Optional) Expand **Tags**, and then enter key-value pairs that you want to associate with the data source. For more information about tags, see [Tag Athena resources](tags.md).

1. Choose **Next**.

1. On the **Review and create** page, review the information that you provided, and then choose **Create data source**. The **Data source details** page lists the databases and tags for the data catalog that you registered.

1. Choose **Data sources and catalogs**. The data catalog that you registered is listed in the **Data source name** column.

1. To view or edit information about the data catalog, choose the catalog, and then choose **Actions**, **Edit**.

1. To delete the new data catalog, choose the catalog, and then choose **Actions**, **Delete**.

### Step 3: The borrower submits a query


The borrower submits a query that references the catalog using the *catalog*.*database*.*table* syntax, as in the following example:

```
SELECT * FROM ownerCatalog.tpch1000.customer
```

Instead of using the fully qualified syntax, the borrower can also specify the catalog contextually by passing it in through the [QueryExecutionContext](https://docs.aws.amazon.com/athena/latest/APIReference/API_QueryExecutionContext.html).

## (Optional) Configure additional Amazon S3 permissions

+ If the borrower account uses an Athena query to write new data to a table in the owner account, the owner will not automatically have access to this data in Amazon S3, even though the table exists in the owner's account. This is because the borrower is the object owner of the information in Amazon S3 unless otherwise configured. To grant the owner access to the data, set the permissions on the objects accordingly as an additional step.
+ Certain cross-account DDL operations like [MSCK REPAIR TABLE](msck-repair-table.md) require Amazon S3 permissions. For example, if the borrower account is performing a cross-account `MSCK REPAIR` operation against a table in the owner account that has its data in an owner account S3 bucket, that bucket must grant permissions to the role assumed by the borrower for the query to succeed.

For information about granting bucket permissions, see [How do I set ACL bucket permissions?](https://docs.aws.amazon.com/AmazonS3/latest/user-guide/set-bucket-permissions.html) in the *Amazon Simple Storage Service User Guide*.

## (Optional) Use a catalog dynamically


In some cases you might want to quickly perform testing against a cross-account AWS Glue catalog without the prerequisite step of registering it. You can dynamically perform cross-account queries without creating the `DataCatalog` resource object if the required IAM and Amazon S3 permissions are correctly configured as described earlier in this document.

To explicitly reference a catalog without registration, use the syntax in the following example:

```
SELECT * FROM "glue:arn:aws:glue:us-east-1:999999999999:catalog".tpch1000.customer
```

Use the format "`glue:<arn>`", where `<arn>` is the [AWS Glue Data Catalog ARN](https://docs.aws.amazon.com/glue/latest/dg/glue-specifying-resource-arns.html#data-catalog-resource-arns) that you want to use. In the example, Athena uses this syntax to dynamically point to account 999999999999's AWS Glue data catalog as if you had separately created a `DataCatalog` object for it.

### Notes for using dynamic catalogs


When you use dynamic catalogs, remember the following points.
+ Use of a dynamic catalog requires the IAM permissions that you normally use for Athena Data Catalog API operations. The main difference is that the Data Catalog resource name follows the `glue:*` naming convention.
+ The catalog ARN must belong to the same Region where the query is being run.
+ When using a dynamic catalog in a DML query or view, surround it with escaped double quotation marks (`\"`). When using a dynamic catalog in a DDL query, surround it with backtick characters (```).

## (Optional) Use the API to register an Athena Data Catalog that belongs to the owner account


Instead of using the Athena console as described in Step 2, it is possible to use API operations to register the Data Catalog that belongs to the owner account.

The creator of the Athena [DataCatalog](https://docs.aws.amazon.com/athena/latest/APIReference/API_DataCatalog.html) resource must have the necessary permissions to run the Athena [CreateDataCatalog](https://docs.aws.amazon.com/athena/latest/APIReference/API_CreateDataCatalog.html) API operation. Depending on your requirements, access to additional API operations might be necessary. For more information, see [Data Catalog example policies](datacatalogs-example-policies.md).

The following `CreateDataCatalog` request body registers an AWS Glue catalog for cross-account access:

```
# Example CreateDataCatalog request to register a cross-account Glue catalog:
{
    "Description": "Cross-account Glue catalog",
    "Name": "ownerCatalog",
    "Parameters": {"catalog-id" : "999999999999"  # Owner's account ID
    },
    "Type": "GLUE"
}
```

The following sample code uses a Java client to create the `DataCatalog` object.

```
# Sample code to create the DataCatalog through Java client
CreateDataCatalogRequest request = new CreateDataCatalogRequest()
    .withName("ownerCatalog")
    .withType(DataCatalogType.GLUE)
    .withParameters(ImmutableMap.of("catalog-id", "999999999999"));

athenaClient.createDataCatalog(request);
```

After these steps, the borrower should see `ownerCatalog` when it calls the [ListDataCatalogs](https://docs.aws.amazon.com/athena/latest/APIReference/API_ListDataCatalogs.html) API operation.

## Additional resources

+ [Register a Data Catalog from another account](data-sources-glue-cross-account.md)
+ [Configure cross-account access to a shared AWS Glue Data Catalog using Amazon Athena](https://docs.aws.amazon.com/prescriptive-guidance/latest/patterns/configure-cross-account-access-to-a-shared-aws-glue-data-catalog-using-amazon-athena.html) in the *AWS Prescriptive Guidance Patterns* guide.
+ [Query cross-account AWS Glue Data Catalogs using Amazon Athena](https://aws.amazon.com/blogs/big-data/query-cross-account-aws-glue-data-catalogs-using-amazon-athena/) in the *AWS Big Data Blog*
+ [Granting cross-account access](https://docs.aws.amazon.com/glue/latest/dg/cross-account-access.html) in the *AWS Glue Developer Guide* 

# Configure access from Athena to encrypted metadata in the AWS Glue Data Catalog
Access to encrypted metadata in the Data Catalog

If you use the AWS Glue Data Catalog with Amazon Athena, you can enable encryption in the AWS Glue Data Catalog using the AWS Glue console or the API. For information, see [Encrypting your data catalog](https://docs.aws.amazon.com/glue/latest/dg/encrypt-glue-data-catalog.html) in the *AWS Glue Developer Guide*.

If the AWS Glue Data Catalog is encrypted, you must add the following actions to all policies that are used to access Athena:

Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

# Configure access to workgroups and tags
Access to workgroups and tags

A workgroup is a resource managed by Athena. Therefore, if your workgroup policy uses actions that take `workgroup` as an input, you must specify the workgroup's ARN as follows, where `workgroup-name` is the name of your workgroup:

```
"Resource": [arn:aws:athena:region:AWSAcctID:workgroup/workgroup-name]
```

For example, for a workgroup named `test_workgroup` in the `us-west-2` region for Amazon Web Services account `123456789012`, specify the workgroup as a resource using the following ARN:

```
"Resource":["arn:aws:athena:us-east-2:123456789012:workgroup/test_workgroup"]
```

To access trusted identity propagation (TIP) enabled workgroups, IAM Identity Center users must be assigned to the `IdentityCenterApplicationArn` that is returned by the response of the Athena [GetWorkGroup](https://docs.aws.amazon.com/athena/latest/APIReference/API_GetWorkGroup.html) API action.
+ For a list of workgroup policies, see [Example workgroup policies](example-policies-workgroup.md).
+ For a list of tag-based policies for workgroups, see [Use tag-based IAM access control policies](tags-access-control.md).
+ For more information about creating IAM policies for workgroups, see [Use IAM policies to control workgroup access](workgroups-iam-policy.md).
+ For a complete list of Amazon Athena actions, see the API action names in the [Amazon Athena API Reference](https://docs.aws.amazon.com/athena/latest/APIReference/). 
+ For more information about IAM policies, see [Creating policies with the visual editor](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-visual-editor) in the *IAM User Guide*. 

Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

# Use IAM policies to control workgroup access


To control access to workgroups, use resource-level IAM permissions or identity-based IAM policies. Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

**Note**  
To access trusted identity propagation enabled workgroups, IAM Identity Center users must be assigned to the `IdentityCenterApplicationArn` that is returned by the response of the Athena [GetWorkGroup](https://docs.aws.amazon.com/athena/latest/APIReference/API_GetWorkGroup.html) API action.

The following procedure is specific to Athena. 

For IAM-specific information, see the links listed at the end of this section. For information about example JSON workgroup policies, see [Example workgroup policies](example-policies-workgroup.md).

**To use the visual editor in the IAM console to create a workgroup policy**

1. Sign in to the AWS Management Console and open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

1. In the navigation pane on the left, choose **Policies**, and then choose **Create policy**.

1. On the **Visual editor** tab, choose **Choose a service**. Then choose Athena to add to the policy.

1. Choose **Select actions**, and then choose the actions to add to the policy. The visual editor shows the actions available in Athena. For more information, see [Actions, resources, and condition keys for Amazon Athena](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonathena.html) in the *Service Authorization Reference*.

1. Choose **add actions** to type a specific action or use wildcards (\$1) to specify multiple actions. 

   By default, the policy that you are creating allows the actions that you choose. If you chose one or more actions that support resource-level permissions to the `workgroup` resource in Athena, then the editor lists the `workgroup` resource. 

1. Choose **Resources** to specify the specific workgroups for your policy. For example JSON workgroup policies, see [Example workgroup policies](example-policies-workgroup.md).

1. Specify the `workgroup` resource as follows:

   ```
   arn:aws:athena:<region>:<user-account>:workgroup/<workgroup-name>
   ```

1. Choose **Review policy**, and then type a **Name** and a **Description** (optional) for the policy that you are creating. Review the policy summary to make sure that you granted the intended permissions. 

1. Choose **Create policy** to save your new policy.

1. Attach this identity-based policy to a user, a group, or role.

For more information, see the following topics in the *Service Authorization Reference* and *IAM User Guide*:
+  [Actions, resources, and condition keys for Amazon Athena](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonathena.html) 
+  [Creating policies with the visual editor](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-visual-editor) 
+  [Adding and removing IAM policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) 
+  [Controlling access to resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_controlling.html#access_controlling-resources) 

For example JSON workgroup policies, see [Example workgroup policies](example-policies-workgroup.md).

For a complete list of Amazon Athena actions, see the API action names in the [Amazon Athena API Reference](https://docs.aws.amazon.com/athena/latest/APIReference/). 

# Example workgroup policies


This section includes example policies you can use to enable various actions on workgroups. Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

A workgroup is an IAM resource managed by Athena. Therefore, if your workgroup policy uses actions that take `workgroup` as an input, you must specify the workgroup's ARN as follows:

```
"Resource": [arn:aws:athena:<region>:<user-account>:workgroup/<workgroup-name>]
```

Where `<workgroup-name>` is the name of your workgroup. For example, for workgroup named `test_workgroup`, specify it as a resource as follows:

```
"Resource": ["arn:aws:athena:us-east-1:123456789012:workgroup/test_workgroup"]
```

For a complete list of Amazon Athena actions, see the API action names in the [Amazon Athena API Reference](https://docs.aws.amazon.com/athena/latest/APIReference/). For more information about IAM policies, see [Creating policies with the visual editor](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html#access_policies_create-visual-editor) in the *IAM User Guide*. For more information about creating IAM policies for workgroups, see [Use IAM policies to control workgroup access](workgroups-iam-policy.md).
+  [Example policy for full access to all workgroups](#example1-full-access-all-wkgs) 
+  [Example policy for full access to a specified workgroup](#example2-full-access-this-wkg) 
+  [Example policy for running queries in a specified workgroup](#example3-user-access) 
+  [Example policy for running queries in the primary workgroup](#example4-run-in-primary-access) 
+  [Example policy for management operations on a specified workgroup](#example5-manage-wkgs-access) 
+  [Example policy for listing workgroups](#example6-list-all-wkgs-access) 
+  [Example policy for running and stopping queries in a specific workgroup](#example7-run-queries-access) 
+  [Example policy for working with named queries in a specific workgroup](#example8-named-queries-access) 
+  [Example policy for working with Spark notebooks](#example9-spark-workgroup) 

**Example policy for full access to all workgroups**  
The following policy allows full access to all workgroup resources that might exist in the account. We recommend that you use this policy for those users in your account that must administer and manage workgroups for all other users.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:*"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

**Example policy for full access to a specified workgroup**  
The following policy allows full access to the single specific workgroup resource, named `workgroupA`. You could use this policy for users with full control over a particular workgroup.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:ListEngineVersions",
                "athena:ListWorkGroups",
                "athena:ListDataCatalogs",
                "athena:ListDatabases",
                "athena:GetDatabase",
                "athena:ListTableMetadata",
                "athena:GetTableMetadata"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "athena:BatchGetQueryExecution",
                "athena:GetQueryExecution",
                "athena:ListQueryExecutions",
                "athena:StartQueryExecution",
                "athena:StopQueryExecution",
                "athena:GetQueryResults",
                "athena:GetQueryResultsStream",
                "athena:CreateNamedQuery",
                "athena:GetNamedQuery",
                "athena:BatchGetNamedQuery",
                "athena:ListNamedQueries",
                "athena:DeleteNamedQuery",
                "athena:CreatePreparedStatement",
                "athena:GetPreparedStatement",
                "athena:ListPreparedStatements",
                "athena:UpdatePreparedStatement",
                "athena:DeletePreparedStatement"
            ],
            "Resource": [
                "arn:aws:athena:us-east-1:123456789012:workgroup/workgroupA"
            ]
        },
        {
            "Effect": "Allow",
            "Action": [
                "athena:DeleteWorkGroup",
                "athena:UpdateWorkGroup",
                "athena:GetWorkGroup",
                "athena:CreateWorkGroup"
            ],
            "Resource": [
                "arn:aws:athena:us-east-1:123456789012:workgroup/workgroupA"
            ]
        }
    ]
}
```

**Example policy for running queries in a specified workgroup**  
In the following policy, a user is allowed to run queries in the specified `workgroupA`, and view them. The user is not allowed to perform management tasks for the workgroup itself, such as updating or deleting it. Note that the example policy does not limit users to only this workgroup or deny access to other workgroups.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
       {
            "Effect": "Allow",
            "Action": [
                "athena:ListEngineVersions",
                "athena:ListWorkGroups",
                "athena:ListDataCatalogs",
                "athena:ListDatabases",
                "athena:GetDatabase",
                "athena:ListTableMetadata",
                "athena:GetTableMetadata"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "athena:GetWorkGroup", 
                "athena:BatchGetQueryExecution",
                "athena:GetQueryExecution",
                "athena:ListQueryExecutions",
                "athena:StartQueryExecution",
                "athena:StopQueryExecution",
                "athena:GetQueryResults",
                "athena:GetQueryResultsStream",
                "athena:CreateNamedQuery",
                "athena:GetNamedQuery",
                "athena:BatchGetNamedQuery",
                "athena:ListNamedQueries",
                "athena:DeleteNamedQuery",
                "athena:CreatePreparedStatement",
                "athena:GetPreparedStatement",
                "athena:ListPreparedStatements",
                "athena:UpdatePreparedStatement",
                "athena:DeletePreparedStatement"
            ],
            "Resource": [
                "arn:aws:athena:us-east-1:123456789012:workgroup/workgroupA"
            ]
        }
    ]
}
```

**Example policy for running queries in the primary workgroup**  
You can modify the preceding example to allow a particular user to also run queries in the primary workgroup.   
We recommend that you add the primary workgroup resource for all users who are otherwise configured to run queries in their designated workgroups. Adding this resource to their workgroup user policies is useful in case their designated workgroup is deleted or is disabled. In this case, they can continue running queries in the primary workgroup.
To allow users in your account to run queries in the primary workgroup, add a line that contains the ARN of the primary workgroup to the resource section of the [Example policy for running queries in a specified workgroup](#example3-user-access), as in the following example.  

```
arn:aws:athena:us-east-1:123456789012:workgroup/primary"
```

**Example policy for management operations on a specified workgroup**  
In the following policy, a user is allowed to create, delete, obtain details, and update a workgroup `test_workgroup`.     
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:ListEngineVersions"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "athena:CreateWorkGroup",
                "athena:GetWorkGroup",
                "athena:DeleteWorkGroup",
                "athena:UpdateWorkGroup"
            ],
            "Resource": [
                "arn:aws:athena:us-east-1:123456789012:workgroup/test_workgroup"
            ]
        }
    ]
}
```

**Example policy for listing workgroups**  
The following policy allows all users to list all workgroups:    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:ListWorkGroups"
            ],
            "Resource": "*"
        }
    ]
}
```

**Example policy for running and stopping queries in a specific workgroup**  
In this policy, a user is allowed to run queries in the workgroup:    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:StartQueryExecution",
                "athena:StopQueryExecution"
            ],
            "Resource": [
                "arn:aws:athena:us-east-1:123456789012:workgroup/test_workgroup"
            ]
        }
    ]
}
```

**Example policy for working with named queries in a specific workgroup**  
In the following policy, a user has permissions to create, delete, and obtain information about named queries in the specified workgroup:    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:CreateNamedQuery",
                "athena:GetNamedQuery",
                "athena:DeleteNamedQuery"
            ],
            "Resource": [
                "arn:aws:athena:us-east-1:123456789012:workgroup/test_workgroup"            ]
        }
    ]
}
```

**Example policy for working with Spark notebooks in Athena**  
Use a policy like the following to work with Spark notebooks in Athena.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowCreatingWorkGroupWithDefaults",
            "Action": [
                "athena:CreateWorkGroup",
                "s3:CreateBucket",
                "iam:CreateRole",
                "iam:CreatePolicy",
                "iam:AttachRolePolicy",
                "s3:GetBucketLocation",
                "athena:ImportNotebook"
            ],
            "Effect": "Allow",
            "Resource": [
                "arn:aws:athena:us-east-1:123456789012:workgroup/Demo*",
                "arn:aws:s3:::123456789012-us-east-1-athena-results-bucket-*",
                "arn:aws:iam::123456789012:role/service-role/AWSAthenaSparkExecutionRole-*",
                "arn:aws:iam::123456789012:policy/service-role/AWSAthenaSparkRolePolicy-*"
            ]
        },
        {
            "Sid": "AllowRunningCalculations",
            "Action": [
                "athena:ListWorkGroups",
                "athena:GetWorkGroup",
                "athena:StartSession",
                "athena:CreateNotebook",
                "athena:ListNotebookMetadata",
                "athena:ListNotebookSessions",
                "athena:GetSessionStatus",
                "athena:GetSession",
                "athena:GetNotebookMetadata",
                "athena:CreatePresignedNotebookUrl"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:athena:us-east-1:123456789012:workgroup/Demo*"
        },
        {
            "Sid": "AllowListWorkGroupAndEngineVersions",
            "Action": [
                "athena:ListWorkGroups",
                "athena:ListEngineVersions"
            ],
            "Effect": "Allow",
            "Resource": "*"
        }
    ]
}
```

# Use IAM Identity Center enabled Athena workgroups
IAM Identity Center enabled workgroups

[Trusted identity propagation](https://docs.aws.amazon.com//singlesignon/latest/userguide/trustedidentitypropagation-overview.html) is an AWS IAM Identity Center feature that administrators of connected AWS services can use to grant and audit access to service data. Access to this data is based on user attributes such as group associations. Setting up trusted identity propagation requires collaboration between the administrators of connected AWS services and the IAM Identity Center administrators. For more information, see [Prerequisites and considerations](https://docs.aws.amazon.com//singlesignon/latest/userguide/trustedidentitypropagation-overall-prerequisites.html).

With [IAM Identity Center](https://docs.aws.amazon.com/singlesignon/latest/userguide/what-is.html), you can manage sign-in security for your workforce identities, also known as workforce users. IAM Identity Center provides one place where you can create or connect workforce users and centrally manage their access across all their AWS accounts and applications. You can use multi-account permissions to assign these users access to AWS accounts. You can use application assignments to assign your users access to IAM Identity Center enabled applications, cloud applications, and customer Security Assertion Markup Language (SAML 2.0) applications. For more information, see [Trusted identity propagation across applications](https://docs.aws.amazon.com/singlesignon/latest/userguide/trustedidentitypropagation.html) in the *AWS IAM Identity Center User Guide*.

Athena SQL support for trusted identity propagation is available in both EMR Studio and SageMaker Unified Studio. Each platform provides specific interfaces for using TIP with Athena. 

When using Athena SQL in EMR Studio with IAM Identity Center identities, you have two workgroup options:
+ **Regular WorkGroups** – No user/group assignments needed.
+ **IAM Identity Center enabled workgroups** – Requires assigning users/groups through IAM Identity Center console or API.

For both options, you can run queries using the Athena SQL interface in EMR Studio with IAM Identity Center enabled. 

## Considerations and limitations


When you use Trusted identity propagation with Amazon Athena, consider the following points:
+ You cannot change the authentication method for the workgroup after the workgroup is created.
  + Existing Athena SQL workgroups cannot be modified to support IAM Identity Center enabled workgroups. Existing Athena SQL workgroups can propagate identity to downstream services.
  + IAM Identity Center enabled workgroups cannot be modified to support resource-level IAM permissions or identity based IAM policies.
+ To access Trusted identity propagation enabled workgroups, IAM Identity Center users must be assigned to the `IdentityCenterApplicationArn` that is returned by the response of the Athena [GetWorkGroup](https://docs.aws.amazon.com/athena/latest/APIReference/API_GetWorkGroup.html) API action.
+ Amazon S3 Access Grants must be configured to use Trusted identity propagation identities. For more information, see [S3 Access Grants and corporate directory identities](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-grants-directory-ids.html) in the *Amazon S3 User Guide*.
+ IAM Identity Center enabled Athena workgroups require Lake Formation to be configured to use IAM Identity Center identities. For configuration information, see [Integrating IAM Identity Center](https://docs.aws.amazon.com/lake-formation/latest/dg/identity-center-integration.html) in the *AWS Lake Formation Developer Guide*.
+ By default, queries time out after 30 minutes in IAM Identity Center enabled workgroups. You can request a query timeout increase, but the maximum a query can run in Trusted identity propagation workgroups is one hour. 
+ User or group entitlement changes in Trusted identity propagation workgroups can require up to an hour to take effect.
+ Queries in an Athena workgroup that uses Trusted identity propagation cannot be run directly from the Athena console. They must be run from the Athena interface in an EMR Studio that has IAM Identity Center enabled. For more information about using Athena in EMR Studio, see [Use the Amazon Athena SQL editor in EMR Studio](https://docs.aws.amazon.com/emr/latest/ManagementGuide/emr-studio-athena.html) in the *Amazon EMR Management Guide*.
+ Trusted identity propagation is not compatible with the following Athena features.
  + `aws:CalledVia` context keys for IAM Identity Center enabled workgroups.
  + Athena for Spark workgroups.
  + Federated access to the Athena API.
  + Federated access to Athena using Lake Formation and the Athena JDBC and ODBC drivers.
+ You can use Trusted identity propagation with Athena only in the following AWS Regions: 
  + `us-east-2` – US East (Ohio)
  + `us-east-1` – US East (N. Virginia)
  + `us-west-1` – US West (N. California)
  + `us-west-2` – US West (Oregon)
  + `af-south-1` – Africa (Cape Town)
  + `ap-east-1` – Asia Pacific (Hong Kong)
  + `ap-southeast-3` – Asia Pacific (Jakarta)
  + `ap-south-1` – Asia Pacific (Mumbai)
  + `ap-northeast-3` – Asia Pacific (Osaka)
  + `ap-northeast-2` – Asia Pacific (Seoul)
  + `ap-southeast-1` – Asia Pacific (Singapore)
  + `ap-southeast-2` – Asia Pacific (Sydney)
  + `ap-northeast-1` – Asia Pacific (Tokyo)
  + `ca-central-1` – Canada (Central)
  + `eu-central-1` – Europe (Frankfurt)
  + `eu-central-2` – Europe (Zurich)
  + `eu-west-1` – Europe (Ireland)
  + `eu-west-2` – Europe (London)
  + `eu-south-1` – Europe (Milan)
  + `eu-west-3` – Europe (Paris)
  + `eu-north-1` – Europe (Stockholm)
  + `me-south-1` – Middle East (Bahrain)
  + `sa-east-1` – South America (São Paulo)

## Required permissions


The IAM user of the admin who creates the IAM Identity Center enabled workgroup in the Athena console must have the following policies attached.
+ The `AmazonAthenaFullAccess` managed policy. For details, see [AWS managed policy: AmazonAthenaFullAccess](security-iam-awsmanpol.md#amazonathenafullaccess-managed-policy).
+ The following inline policy that allows IAM and IAM Identity Center actions:

------
#### [ JSON ]

****  

  ```
  { "Version":"2012-10-17",		 	 	  "Statement": [ { "Action": [ "iam:createRole",
      "iam:CreatePolicy", "iam:AttachRolePolicy", "iam:ListRoles", "identitystore:ListUsers",
      "identitystore:ListGroups", "identitystore:CreateUser", "identitystore:CreateGroup",
      "sso:ListInstances", "sso:CreateInstance", "sso:DeleteInstance", "sso:ListTrustedTokenIssuers",
      "sso:DescribeTrustedTokenIssuer", "sso:ListApplicationAssignments",
      "sso:DescribeRegisteredRegions", "sso:GetManagedApplicationInstance",
      "sso:GetSharedSsoConfiguration", "sso:PutApplicationAssignmentConfiguration",
      "sso:CreateApplication", "sso:DeleteApplication", "sso:PutApplicationGrant",
      "sso:PutApplicationAuthenticationMethod", "sso:PutApplicationAccessScope",
      "sso:ListDirectoryAssociations", "sso:CreateApplicationAssignment",
      "sso:DeleteApplicationAssignment", "organizations:ListDelegatedAdministrators",
      "organizations:DescribeAccount", "organizations:DescribeOrganization",
      "organizations:CreateOrganization", "sso-directory:SearchUsers", "sso-directory:SearchGroups",
      "sso-directory:CreateUser" ], "Effect": "Allow", "Resource": [ "*" ] }, { "Action": [
      "iam:PassRole" ], "Effect": "Allow", "Resource": [
          "arn:aws:iam::111122223333:role/service-role/AWSAthenaSQLRole-*"
      ] } ] }
  ```

------

## Creating an IAM Identity Center enabled Athena workgroup


The following procedure shows the steps and options related to creating an IAM Identity Center enabled Athena workgroup. For a description of the other configuration options available for Athena workgroups, see [Create a workgroup](creating-workgroups.md).

**To create an SSO enabled workgroup in the Athena console**

1. Open the Athena console at [https://console.aws.amazon.com/athena/](https://console.aws.amazon.com/athena/home).

1. In the Athena console navigation pane, choose **Workgroups**.

1. On the **Workgroups** page, choose **Create workgroup**.

1. On the **Create workgroup** page, for **Workgroup name**, enter a name for the workgroup.

1. For **Analytics engine**, use the **Athena SQL** default.

1. For **Authentication**, choose **IAM Identity Center**.

1. For **Service role for IAM Identity Center access**, choose an existing service role, or create a new one.

   Athena requires permissions to access IAM Identity Center for you. A service role is required for Athena to do this. A service role is an IAM role that you manage that authorizes an AWS service to access other AWS services on your behalf. To query federated catalogs or run UDF, update service role with corresponding Lambda permissions. For more information, see [Creating a role to delegate permissions to an AWS service](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-service.html) in the *IAM User Guide*.

1. Expand **Query result configuration**, and then enter or choose an Amazon S3 path for **Location of query result**.

1. (Optional) Choose **Encrypt query results**. By default, SSE-S3 is supported. To use SSE-KMS and CSE-KMS with query result location, provide grants to the **Service role for IAM Identity Center** from Amazon S3 Access Grants. For more information, see [Sample role policy](#workgroups-identity-center-access-grant-location-sample-role-policy).

1. (Optional) Choose **Create user identity based S3 prefix**.

   When you create an IAM Identity Center enabled workgroup, the **Enable S3 Access Grants** option is selected by default. You can use Amazon S3 Access Grants to control access to Athena query results locations (prefixes) in Amazon S3. For more information about Amazon S3 Access Grants, see [Managing access with Amazon S3 Access Grants](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-grants.html).

   In Athena workgroups that use IAM Identity Center authentication, you can enable the creation of identity based query result locations that are governed by Amazon S3 Access Grants. These user identity based Amazon S3 prefixes let users in an Athena workgroup keep their query results isolated from other users in the same workgroup.

   When you enable the user prefix option, Athena appends the user ID as an Amazon S3 path prefix to the query result output location for the workgroup (for example, `s3://amzn-s3-demo-bucket/${user_id}`). To use this feature, you must configure Access Grants to allow only the user permission to the location that has the `user_id` prefix. For a sample Amazon S3 Access Grants location role policy that restricts access to Athena query results, see [Sample role policy](#workgroups-identity-center-access-grant-location-sample-role-policy). 
**Note**  
Selecting the user identity S3 prefix option automatically enables the override client-side settings option for the workgroup, as described in the next step. The override client-side settings option is a requirement for the user identity prefix feature.

1. Expand **Settings**, and then confirm that **Override client-side settings** is selected.

   When you select **Override client-side settings**, workgroup settings are enforced at the workgroup level for all clients in the workgroup. For more information, see [Override client-side settings](workgroups-settings-override.md).

1. (Optional) Make any other configuration settings that you require as described in [Create a workgroup](creating-workgroups.md).

1. Choose **Create workgroup**.

1. Use the **Workgroups** section of the Athena console to assign users or groups from your IAM Identity Center directory to your IAM Identity Center enabled Athena workgroup.

## Sample role policy


The following sample shows a policy for a role to attach to an Amazon S3 Access Grant location that restricts access to Athena query results. 

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Action": [
                "s3:*"
            ],
            "Condition": {
                "ArnNotEquals": {
                    "s3:AccessGrantsInstanceArn": "arn:aws:s3:us-east-1:111122223333:access-grants/default"
                },
                "StringNotEquals": {
                    "aws:ResourceAccount": "111122223333"
                }
            },
            "Effect": "Deny",
            "Resource": "*",
            "Sid": "ExplicitDenyS3"
        },
        {
            "Action": [
                "kms:*"
            ],
            "Effect": "Deny",
            "NotResource": "arn:aws:kms:us-east-1:111122223333:key/${keyid}",
            "Sid": "ExplictDenyKMS"
        },
        {
            "Action": [
                "s3:ListMultipartUploadParts",
                "s3:GetObject"
            ],
            "Condition": {
                "ArnEquals": {
                    "s3:AccessGrantsInstanceArn": "arn:aws:s3:us-east-1:111122223333:access-grants/default"
                },
                "StringEquals": {
                    "aws:ResourceAccount": "111122223333"
                }
            },
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::ATHENA-QUERY-RESULT-LOCATION/${identitystore:UserId}/*",
            "Sid": "ObjectLevelReadPermissions"
        },
        {
            "Action": [
                "s3:PutObject",
                "s3:AbortMultipartUpload"
            ],
            "Condition": {
                "ArnEquals": {
                    "s3:AccessGrantsInstanceArn": "arn:aws:s3:us-east-1:111122223333:access-grants/default"
                },
                "StringEquals": {
                "aws:ResourceAccount": "111122223333"
                }
            },
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::ATHENA-QUERY-RESULT-LOCATION/${identitystore:UserId}/*",
            "Sid": "ObjectLevelWritePermissions"
        },
        {
            "Action": "s3:ListBucket",
            "Condition": {
                "ArnEquals": {
                    "s3:AccessGrantsInstanceArn": "arn:aws:s3:us-east-1:111122223333:access-grants/default"
                },
                "StringEquals": {
                    "aws:ResourceAccount": "111122223333"
                },
                "StringLikeIfExists": {
                    "s3:prefix": [
                        "${identitystore:UserId}",
                        "${identitystore:UserId}/*"
                    ]
                }
            },
            "Effect": "Allow",
            "Resource": "arn:aws:s3:::ATHENA-QUERY-RESULT-LOCATION",
            "Sid": "BucketLevelReadPermissions"
        },
        {
            "Action": [
                "kms:GenerateDataKey",
                "kms:Decrypt"
            ],
            "Effect": "Allow",
            "Resource": "arn:aws:kms:us-east-1:111122223333:key/${keyid}",
            "Sid": "KMSPermissions"
        }
    ]
}
```

------

# Configure minimum encryption for a workgroup
Configure minimum encryption

As an administrator of an Athena SQL workgroup, you can enforce a minimal level of encryption in Amazon S3 for all query results from the workgroup. You can use this feature to ensure that query results are never stored in an Amazon S3 bucket in an unencrypted state.

When users in a workgroup with minimum encryption enabled submit a query, they can only set the encryption to the minimum level that you configure, or to a higher level if one is available. Athena encrypts query results at either the level specified when the user runs the query or at the level set in the workgroup.

The following levels are available:
+ **Basic** – Amazon S3 server side encryption with Amazon S3 managed keys (**SSE\$1S3**).
+ **Intermediate** – Server Side encryption with KMS managed keys (**SSE\$1KMS**).
+ **Advanced** – Client side encryption with KMS managed keys (**CSE\$1KMS**).

## Considerations and limitations

+ The minimum encryption feature is not available for Apache Spark enabled workgroups.
+ The minimum encryption feature is functional only when the workgroup does not enable the **[Override client-side settings](https://docs.aws.amazon.com/athena/latest/ug/workgroups-settings-override.html)** option.
+ If the workgroup has the **Override client-side settings** option enabled, the workgroup encryption setting prevails, and the minimum encryption setting has no effect.
+ There is no cost to enable this feature.

## Enable minimum encryption for a workgroup


You can enable a minimum encryption level for the query results from your Athena SQL workgroup when you create or update the workgroup. To do this, you can use the Athena console, Athena API, or AWS CLI.

### Use the Athena console to enable minimum encryption


To get started creating or editing your workgroup using the Athena console, see [Create a workgroup](https://docs.aws.amazon.com/athena/latest/ug/workgroups-create-update-delete.html#creating-workgroups) or [Edit a workgroup](https://docs.aws.amazon.com/athena/latest/ug/workgroups-create-update-delete.html#editing-workgroups). When configuring your workgroup, use the following steps to enable minimum encryption.

**To configure the minimum encryption level for workgroup query results**

1. Clear the **Override client-side settings** option, or verify that it is not selected.

1. Select the **Encrypt query results** option.

1. For **Encryption type**, select the encryption method that you want Athena to use for your workgroup's query results (**SSE\$1S3**, **SSE\$1KMS**, or **CSE\$1KMS**). These encryption types correspond to basic, intermediate, and advanced security levels.

1. To enforce the encryption method that you chose as the minimum level of encryption for all users, select **Set *encryption\$1method* as minimum encryption**.

   When you select this option, a table shows the encryption hierarchy and encryption levels that users will be allowed when the encryption type that you choose becomes the minimum.

1. After you create your workgroup or update your workgroup configuration, choose **Create workgroup** or **Save changes**.

### Use the Athena API or AWS CLI to enable minimum encryption


When you use the [CreateWorkGroup](https://docs.aws.amazon.com/athena/latest/APIReference/API_CreateWorkGroup.html) or [UpdateWorkGroup](https://docs.aws.amazon.com/athena/latest/APIReference/API_UpdateWorkGroup.html) API to create or update an Athena SQL workgroup, set [EnforceWorkGroupConfiguration](https://docs.aws.amazon.com/athena/latest/APIReference/API_WorkGroupConfiguration.html#athena-Type-WorkGroupConfiguration-EnforceWorkGroupConfiguration) to `false`, [EnableMinimumEncryptionConfiguration](https://docs.aws.amazon.com/athena/latest/APIReference/API_WorkGroupConfiguration.html#athena-Type-WorkGroupConfiguration-EnableMinimumEncryptionConfiguration) to `true`, and use the [EncryptionOption](https://docs.aws.amazon.com/athena/latest/APIReference/API_EncryptionConfiguration.html#athena-Type-EncryptionConfiguration-EncryptionOption) to specify the type of encryption.

In the AWS CLI, use the [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/create-work-group.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/create-work-group.html) or [https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/update-work-group.html](https://awscli.amazonaws.com/v2/documentation/api/latest/reference/athena/update-work-group.html) command with the `--configuration` or `--configuration-updates` parameters and specify the options corresponding to those for the API.

# Configure access to prepared statements


This topic covers IAM permissions for prepared statements in Amazon Athena. Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

For more information about prepared statements, see [Use parameterized queries](querying-with-prepared-statements.md).

The following IAM permissions are required for creating, managing, and executing prepared statements.

```
athena:CreatePreparedStatement
athena:UpdatePreparedStatement
athena:GetPreparedStatement
athena:ListPreparedStatements
athena:DeletePreparedStatement
```

Use these permissions as shown in the following table.


****  

| To do this | Use these permissions | 
| --- | --- | 
| Run a PREPARE query | athena:StartQueryExecution athena:CreatePreparedStatement | 
| Re-run a PREPARE query to update an existing prepared statement | athena:StartQueryExecution athena:UpdatePreparedStatement | 
| Run an EXECUTE query | athena:StartQueryExecution athena:GetPreparedStatement | 
| Run a DEALLOCATE PREPARE query | athena:StartQueryExecution athena:DeletePreparedStatement | 

## Example


The following example IAM policy grants permissions to manage and run prepared statements on a specified account ID and workgroup.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:StartQueryExecution",
                "athena:CreatePreparedStatement",
                "athena:UpdatePreparedStatement",
                "athena:GetPreparedStatement",
                "athena:DeletePreparedStatement",
                "athena:ListPreparedStatements"
            ],
            "Resource": [
                "arn:aws:athena:*:111122223333:workgroup/<workgroup-name>"
            ]
        }
    ]
}
```

------

# Use CalledVia context keys for Athena
Use CalledVia context keys

When a [principal](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-principal) makes a [request](https://docs.aws.amazon.com/IAM/latest/UserGuide/intro-structure.html#intro-structure-request) to AWS, AWS gathers the request information into a *request context* that evaluates and authorizes the request. You can use the `Condition` element of a JSON policy to compare keys in the request context with key values that you specify in your policy. *Global condition context keys* are condition keys with an `aws:` prefix.

## About the aws:CalledVia context key


You can use the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-calledvia](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-calledvia) global condition context key to compare the services in the policy with the services that made requests on behalf of the IAM principal (user or role). When a principal makes a request to an AWS service, that service might use the principal's credentials to make subsequent requests to other services. The `aws:CalledVia` key contains an ordered list of each service in the chain that made requests on the principal's behalf.

By specifying a service principal name for the `aws:CalledVia` context key, you can make the context key AWS service-specific. For example, you can use the `aws:CalledVia` condition key to limit requests to only those made from Athena. To use the `aws:CalledVia` condition key in a policy with Athena, you specify the Athena service principal name `athena.amazonaws.com`, as in the following example.

```
 ...
    "Condition": {
        "ForAnyValue:StringEquals": { 
            "aws:CalledVia": "athena.amazonaws.com"
        }
    }
...
```

You can use the `aws:CalledVia` context key to ensure that callers only have access to a resource (like a Lambda function) if they call the resource from Athena.

**Note**  
The `aws:CalledVia` context key is not compatible with the trusted identity propagation feature.

## Add a CalledVia context key for access to Lambda functions


Athena requires the caller to have `lambda:InvokeFunction` permissions in order to invoke the Lambda function associated with the query. The following statement specifies that the user can invoke Lambda functions only from Athena.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor3",
            "Effect": "Allow",
            "Action": "lambda:InvokeFunction",
            "Resource": "arn:aws:lambda:us-east-1:111122223333:function:OneAthenaLambdaFunction",
            "Condition": {
                "ForAnyValue:StringEquals": {
                    "aws:CalledVia": "athena.amazonaws.com"
                }
            }
        }
    ]
}
```

------

The following example shows the addition of the previous statement to a policy that allows a user to run and read a federated query. Principals who are allowed to perform these actions can run queries that specify Athena catalogs associated with a federated data source. However, the principal cannot access the associated Lambda function unless the function is invoked through Athena.

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor0", 
            "Effect": "Allow",
            "Action": [ 
                "athena:GetWorkGroup", 
                "s3:PutObject", 
                "s3:GetObject", 
                "athena:StartQueryExecution", 
                "s3:AbortMultipartUpload",  
                "athena:StopQueryExecution", 
                "athena:GetQueryExecution", 
                "athena:GetQueryResults", 
                "s3:ListMultipartUploadParts" 
            ], 
            "Resource": [ 
                "arn:aws:athena:*:111122223333:workgroup/WorkGroupName",
                "arn:aws:s3:::MyQueryResultsBucket/*", 
                "arn:aws:s3:::MyLambdaSpillBucket/MyLambdaSpillPrefix*"
            ] 
        }, 
        {
            "Sid": "VisualEditor1", 
            "Effect": "Allow", 
            "Action": "athena:ListWorkGroups", 
            "Resource": "*" 
        }, 
        {
            "Sid": "VisualEditor2", 
            "Effect": "Allow", 
            "Action": 
                [ 
                "s3:ListBucket", 
                "s3:GetBucketLocation" 
                ], 
            "Resource": "arn:aws:s3:::MyLambdaSpillBucket" 
        },
        {
            "Sid": "VisualEditor3",
            "Effect": "Allow",
            "Action": "lambda:InvokeFunction",
            "Resource": [
                "arn:aws:lambda:*:111122223333:function:OneAthenaLambdaFunction", 
                "arn:aws:lambda:*:111122223333:function:AnotherAthenaLambdaFunction"
            ], 
            "Condition": {
                "ForAnyValue:StringEquals": { 
                    "aws:CalledVia": "athena.amazonaws.com"
                }
            }
        }            
    ]
}
```

------

For more information about `CalledVia` condition keys, see [AWS global condition context keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) in the *IAM User Guide*.

# Allow access to the Athena Data Connector for External Hive Metastore


The permission policy examples in this topic demonstrate required allowed actions and the resources for which they are allowed. Examine these policies carefully and modify them according to your requirements before you attach similar permissions policies to IAM identities.
+  [Example Policy to Allow an IAM Principal to Query Data Using Athena Data Connector for External Hive Metastore](#hive-using-iam) 
+  [Example Policy to Allow an IAM Principal to Create an Athena Data Connector for External Hive Metastore](#hive-creating-iam) 

**Example – Allow an IAM principal to query data using Athena Data Connector for External Hive Metastore**  
The following policy is attached to IAM principals in addition to the [AWS managed policy: AmazonAthenaFullAccess](security-iam-awsmanpol.md#amazonathenafullaccess-managed-policy), which grants full access to Athena actions.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "lambda:GetFunction",
                "lambda:GetLayerVersion",
                "lambda:InvokeFunction"
            ],
            "Resource": [
                "arn:aws:lambda:*:111122223333:function:MyAthenaLambdaFunction",
                "arn:aws:lambda:*:111122223333:function:AnotherAthenaLambdaFunction",
                "arn:aws:lambda:*:111122223333:layer:MyAthenaLambdaLayer:*"
            ]
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": [
                "s3:GetBucketLocation",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:PutObject",
                "s3:ListMultipartUploadParts",
                "s3:AbortMultipartUpload"
            ],
            "Resource": "arn:aws:s3:::MyLambdaSpillBucket/MyLambdaSpillLocation"
        }
    ]
}
```


**Explanation of permissions**  

| Allowed actions | Explanation | 
| --- | --- | 
|  <pre>"s3:GetBucketLocation",<br />"s3:GetObject",<br />"s3:ListBucket",<br />"s3:PutObject",<br />"s3:ListMultipartUploadParts",<br />"s3:AbortMultipartUpload"</pre>  |  `s3` actions allow reading from and writing to the resource specified as `"arn:aws:s3:::MyLambdaSpillBucket/MyLambdaSpillLocation"`, where *MyLambdaSpillLocation* identifies the spill bucket that is specified in the configuration of the Lambda function or functions being invoked. The *arn:aws:lambda:\$1:*MyAWSAcctId*:layer:*MyAthenaLambdaLayer*:\$1* resource identifier is required only if you use a Lambda layer to create custom runtime dependencies to reduce function artifact size at deployment time. The `*` in the last position is a wildcard for layer version.  | 
|  <pre>"lambda:GetFunction",<br />"lambda:GetLayerVersion",<br />"lambda:InvokeFunction"</pre>  | Allows queries to invoke the AWS Lambda functions specified in the Resource block. For example, arn:aws:lambda:\$1:MyAWSAcctId:function:MyAthenaLambdaFunction, where MyAthenaLambdaFunction specifies the name of a Lambda function to be invoked. Multiple functions can be specified as shown in the example. | 

**Example – Allow an IAM principal to create an Athena Data Connector for External Hive Metastore**  
The following policy is attached to IAM principals in addition to the [AWS managed policy: AmazonAthenaFullAccess](security-iam-awsmanpol.md#amazonathenafullaccess-managed-policy), which grants full access to Athena actions.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:GetFunction",
                "lambda:ListFunctions",
                "lambda:GetLayerVersion",
                "lambda:InvokeFunction",
                "lambda:CreateFunction",
                "lambda:DeleteFunction",
                "lambda:PublishLayerVersion",
                "lambda:DeleteLayerVersion",
                "lambda:UpdateFunctionConfiguration",
                "lambda:PutFunctionConcurrency",
                "lambda:DeleteFunctionConcurrency"
            ],
            "Resource": "arn:aws:lambda:*:111122223333: function: MyAthenaLambdaFunctionsPrefix*"
        }
    ]
}
```
 **Explanation of Permissions**   
Allows queries to invoke the AWS Lambda functions for the AWS Lambda functions specified in the `Resource` block. For example, `arn:aws:lambda:*:MyAWSAcctId:function:MyAthenaLambdaFunction`, where *MyAthenaLambdaFunction* specifies the name of a Lambda function to be invoked. Multiple functions can be specified as shown in the example.

# Allow Lambda function access to external Hive metastores


To invoke a Lambda function in your account, you must create a role that has the following permissions:
+ `AWSLambdaVPCAccessExecutionRole` – An [AWS Lambda execution role](https://docs.aws.amazon.com/lambda/latest/dg/lambda-intro-execution-role.html) permission to manage elastic network interfaces that connect your function to a VPC. Ensure that you have a sufficient number of network interfaces and IP addresses available.
+ `AmazonAthenaFullAccess` – The [AmazonAthenaFullAccess](security-iam-awsmanpol.md#amazonathenafullaccess-managed-policy) managed policy grants full access to Athena.
+ An Amazon S3 policy to allow the Lambda function to write to S3 and to allow Athena to read from S3.

For example, the following policy defines the permission for the spill location `s3:\\mybucket\spill`.

------
#### [ JSON ]

****  

```
{ "Version":"2012-10-17",		 	 	  "Statement": [ { "Effect": "Allow", "Action": [
    "s3:GetBucketLocation", "s3:GetObject", "s3:ListBucket", "s3:PutObject" ], "Resource": [
        "arn:aws:s3:::amzn-s3-demo-bucket/spill" ] } ] }
```

------

Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

## Create Lambda functions


To create a Lambda function in your account, function development permissions or the `AWSLambdaFullAccess` role are required. For more information, see [Identity-based IAM policies for AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/access-control-identity-based.html).

Because Athena uses the AWS Serverless Application Repository to create Lambda functions, the superuser or administrator who creates Lambda functions should also have IAM policies [to allow Athena federated queries](federated-query-iam-access.md).

## Configure permissions for catalog registration and metadata API operations


For API access to catalog registration and metadata operations, you can use the [AmazonAthenaFullAccess managed policy](security-iam-awsmanpol.md#amazonathenafullaccess-managed-policy). If you do not use the `AmazonAthenaFullAccess` policy, add the following API operations to your Athena policies:

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "athena:ListDataCatalogs",
                "athena:GetDataCatalog",
                "athena:CreateDataCatalog",
                "athena:UpdateDataCatalog",
                "athena:DeleteDataCatalog",
                "athena:GetDatabase",
                "athena:ListDatabases",
                "athena:GetTableMetadata",
                "athena:ListTableMetadata"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

------

## Call a Lambda function across regions


By default, Athena invokes Lambda functions defined in the same region. To invoke a Lambda function in an AWS Region other than the region in which you are running Athena queries, use the full ARN of the Lambda function. 

The following example shows how a catalog in the Europe (Frankfurt) Region can specify a Lambda function in the US East (N. Virginia) Region to fetch data from the Hive metastore in the Europe (Frankfurt) Region.

```
arn:aws:lambda:us-east-1:111122223333:function:external-hms-service-new     
```

When you specify the full ARN in this way, Athena can call the `external-hms-service-new` Lambda function on `us-east-1` to fetch the Hive metastore data from `eu-central-1`.

**Note**  
The catalog should be registered in the same AWS Region that you use to run Athena queries.

## Call a Lambda function across accounts


Sometimes you might require access to a Hive metastore from a different account. For example, to run a Hive metastore, you might use an account that is different from the one that you use for Athena queries. Different groups or teams might run Hive metastore with different accounts inside their VPC. Or you might want to access metadata from different Hive metastores from different groups or teams.

Athena uses the [AWS Lambda support for cross account access](https://aws.amazon.com/blogs/compute/easy-authorization-of-aws-lambda-functions/) to enable cross account access for Hive Metastores.

**Note**  
Note that cross account access for Athena normally implies cross account access for both metadata and data in Amazon S3.

Imagine the following scenario:
+ Account `111122223333` sets up the Lambda function `external-hms-service-new` on us-east-1 in Athena to access a Hive Metastore running on an EMR cluster.
+ Account `111122223333` wants to allow account 444455556666 to access the Hive Metastore data.

To grant account `444455556666` access to the Lambda function `external-hms-service-new`, account `111122223333` uses the following AWS CLI `add-permission` command. The command has been formatted for readability.

```
$ aws --profile perf-test lambda add-permission
      --function-name external-hms-service-new
      --region us-east-1
      --statement-id Id-ehms-invocation2
      --action "lambda:InvokeFunction"
      --principal arn:aws:iam::444455556666:user/perf1-test
{
    "Statement": "{\"Sid\":\"Id-ehms-invocation2\",
                   \"Effect\":\"Allow\",
                   \"Principal\":{\"AWS\":\"arn:aws:iam::444455556666:user/perf1-test\"},
                   \"Action\":\"lambda:InvokeFunction\",
                   \"Resource\":\"arn:aws:lambda:us-east-1:111122223333:function:external-hms-service-new\"}"
}
```

To check the Lambda permission, use the `get-policy` command, as in the following example. The command has been formatted for readability.

```
$ aws --profile perf-test lambda get-policy 
      --function-name arn:aws:lambda:us-east-1:111122223333:function:external-hms-service-new 
      --region us-east-1
{
    "RevisionId": "711e93ea-9851-44c8-a09f-5f2a2829d40f",
    "Policy": "{\"Version\":\"2012-10-17\",		 	 	 
                \"Id\":\"default\",
                \"Statement\":[{\"Sid\":\"Id-ehms-invocation2\",
                                \"Effect\":\"Allow\",
                                \"Principal\":{\"AWS\":\"arn:aws:iam::444455556666:user/perf1-test\"},
                                \"Action\":\"lambda:InvokeFunction\",
                                \"Resource\":\"arn:aws:lambda:us-east-1:111122223333:function:external-hms-service-new\"}]}"
}
```

After adding the permission, you can use a full ARN of the Lambda function on `us-east-1` like the following when you define catalog `ehms`:

```
arn:aws:lambda:us-east-1:111122223333:function:external-hms-service-new
```

For information about cross region invocation, see [Call a Lambda function across regions](#hive-metastore-iam-access-lambda-cross-region-invocation) earlier in this topic.

### Grant cross-account access to data


Before you can run Athena queries, you must grant cross account access to the data in Amazon S3. You can do this in one of the following ways:
+ Update the access control list policy of the Amazon S3 bucket with a [canonical user ID](https://docs.aws.amazon.com/general/latest/gr/acct-identifiers.html).
+ Add cross account access to the Amazon S3 bucket policy.

For example, add the following policy to the Amazon S3 bucket policy in the account `111122223333` to allow account `444455556666` to read data from the Amazon S3 location specified.

------
#### [ JSON ]

****  

```
{ "Version":"2012-10-17",		 	 	  "Statement": [ { "Sid": "Stmt1234567890123", "Effect":
    "Allow", "Principal": { "AWS":
        "arn:aws:iam::444455556666:user/perf1-test"
    }, "Action": "s3:GetObject", "Resource": "arn:aws:s3:::athena-test/lambda/dataset/*" } ]
    }
```

------

**Note**  
You might need to grant cross account access to Amazon S3 not only to your data, but also to your Amazon S3 spill location. Your Lambda function spills extra data to the spill location when the size of the response object exceeds a given threshold. See the beginning of this topic for a sample policy.

In the current example, after cross account access is granted to `444455556666,` `444455556666` can use catalog `ehms` in its own `account` to query tables that are defined in account `111122223333`.

In the following example, the SQL Workbench profile `perf-test-1` is for account `444455556666`. The query uses catalog `ehms` to access the Hive metastore and the Amazon S3 data in account `111122223333`.

![\[Accessing Hive metastore and Amazon S3 data across accounts in SQL Workbench.\]](http://docs.aws.amazon.com/athena/latest/ug/images/hive-metastore-iam-access-lambda-1.png)


# Permissions required to create connector and Athena catalog


To invoke Athena `CreateDataCatalog` you must create a role that has the following permissions:

------
#### [ JSON ]

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
  {
  "Sid": "ECR",
  "Effect": "Allow",
  "Action": [
  "ecr:BatchGetImage",
  "ecr:GetDownloadUrlForLayer"
  ],
  "Resource": "arn:aws:ecr:*:*:repository/*"
  },
  {
  "Effect": "Allow",
  "Action": [
  "s3:GetObject",
  "glue:TagResource",
  "glue:GetConnection",
  "glue:CreateConnection",
  "glue:DeleteConnection",
  "glue:UpdateConnection",
  "serverlessrepo:CreateCloudFormationTemplate",
  "serverlessrepo:GetCloudFormationTemplate",
  "cloudformation:CreateStack",
  "cloudformation:DeleteStack",
  "cloudformation:DescribeStacks",
  "cloudformation:CreateChangeSet",
  "cloudformation:DescribeAccountLimits",
  "cloudformation:CreateStackSet",
  "cloudformation:ValidateTemplate",
  "cloudformation:CreateUploadBucket",
  "cloudformation:DescribeStackDriftDetectionStatus",
  "cloudformation:ListExports",
  "cloudformation:ListStacks",
  "cloudformation:EstimateTemplateCost",
  "cloudformation:ListImports",
  "lambda:InvokeFunction",
  "lambda:GetFunction",
  "lambda:DeleteFunction",
  "lambda:CreateFunction",
  "lambda:TagResource",
  "lambda:ListFunctions",
  "lambda:GetAccountSettings",
  "lambda:ListEventSourceMappings",
  "lambda:ListVersionsByFunction",
  "lambda:GetFunctionConfiguration",
  "lambda:PutFunctionConcurrency",
  "lambda:UpdateFunctionConfiguration",
  "lambda:UpdateFunctionCode",
  "lambda:DeleteFunctionConcurrency",
  "lambda:RemovePermission",
  "lambda:AddPermission",
  "lambda:ListTags",
  "lambda:GetAlias",
  "lambda:GetPolicy",
  "lambda:ListAliases",
  "ec2:DescribeSecurityGroups",
  "ec2:DescribeSubnets",
  "ec2:DescribeVpcs",
  "secretsmanager:ListSecrets",
  "glue:GetCatalogs"
  ],
  "Resource": "*"
  },
  {
  "Effect": "Allow",
  "Action": [
  "iam:AttachRolePolicy",
  "iam:DetachRolePolicy",
  "iam:DeleteRolePolicy",
  "iam:PutRolePolicy",
  "iam:GetRolePolicy",
  "iam:CreateRole",
  "iam:TagRole",
  "iam:DeleteRole",
  "iam:GetRole",
  "iam:PassRole",
  "iam:ListRoles",
  "iam:ListAttachedRolePolicies",
  "iam:ListRolePolicies",
  "iam:GetPolicy",
  "iam:UpdateRole"
  ],
  "Resource": [
  "arn:aws:iam::*:role/RoleName",
  "arn:aws:iam::111122223333:policy/*"
  ]
  }
  ]
  }
```

------

# Allow access to Athena Federated Query: Example policies
Allow access to Athena Federated Query

The permission policy examples in this topic demonstrate required allowed actions and the resources for which they are allowed. Examine these policies carefully and modify them according to your requirements before attaching them to IAM identities.

For information about attaching policies to IAM identities, see [Adding and removing IAM identity permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/).
+  [Example policy to allow an IAM principal to run and return results using Athena Federated Query](#fed-using-iam) 
+  [Example Policy to Allow an IAM Principal to Create a Data Source Connector](#fed-creating-iam) 

**Example – Allow an IAM principal to run and return results using Athena Federated Query**  
The following identity-based permissions policy allows actions that a user or other IAM principal requires to use Athena Federated Query. Principals who are allowed to perform these actions are able to run queries that specify Athena catalogs associated with a federated data source.    
****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "Athena",
            "Effect": "Allow",
            "Action": [
                "athena:GetDataCatalog",
                "athena:GetQueryExecution",
                "athena:GetQueryResults",
                "athena:GetWorkGroup",
                "athena:StartQueryExecution",
                "athena:StopQueryExecution"
            ],
            "Resource": [
                "arn:aws:athena:*:111122223333:workgroup/WorkgroupName",
                "arn:aws:athena:us-east-1:111122223333:datacatalog/DataCatalogName"
            ]
        },
        {
            "Sid": "ListAthenaWorkGroups",
            "Effect": "Allow",
            "Action": "athena:ListWorkGroups",
            "Resource": "*"
        },
        {
            "Sid": "Lambda",
            "Effect": "Allow",
            "Action": "lambda:InvokeFunction",
            "Resource": [
                "arn:aws:lambda:*:111122223333:function:OneAthenaLambdaFunction",
                "arn:aws:lambda:*:111122223333:function:AnotherAthenaLambdaFunction"
            ]
        },
        {
            "Sid": "S3",
            "Effect": "Allow",
            "Action": [
                "s3:AbortMultipartUpload",
                "s3:GetBucketLocation",
                "s3:GetObject",
                "s3:ListBucket",
                "s3:ListMultipartUploadParts",
                "s3:PutObject"
            ],
            "Resource": [
                "arn:aws:s3:::MyLambdaSpillBucket",
                "arn:aws:s3:::MyLambdaSpillBucket/*",
                "arn:aws:s3:::MyQueryResultsBucket",
                "arn:aws:s3:::MyQueryResultsBucket/*"
            ]
        }
    ]
}
```


**Explanation of permissions**  

| Allowed actions | Explanation | 
| --- | --- | 
|  <pre> "athena:GetQueryExecution", <br /> "athena:GetQueryResults",<br /> "athena:GetWorkGroup",<br /> "athena:StartQueryExecution",<br /> "athena:StopQueryExecution"</pre>  |  Athena permissions that are required to run federated queries.  | 
|  <pre> "athena:GetDataCatalog",<br /> "athena:GetQueryExecution,"<br /> "athena:GetQueryResults",<br /> "athena:GetWorkGroup",<br /> "athena:StartQueryExecution",<br /> "athena:StopQueryExecution"</pre>  |  Athena permissions that are required to run federated view queries. The `GetDataCatalog` action is required for views.  | 
|  <pre>"lambda:InvokeFunction"</pre>  | Allows queries to invoke the AWS Lambda functions for the AWS Lambda functions specified in the Resource block. For example, arn:aws:lambda:\$1:MyAWSAcctId:function:MyAthenaLambdaFunction, where MyAthenaLambdaFunction specifies the name of a Lambda function to be invoked. As shown in the example, multiple functions can be specified. | 
|  <pre>"s3:AbortMultipartUpload",<br />"s3:GetBucketLocation",<br />"s3:GetObject",<br />"s3:ListBucket",<br />"s3:ListMultipartUploadParts",<br />"s3:PutObject"</pre>  |  The `s3:ListBucket` and `s3:GetBucketLocation` permissions are required to access the query output bucket for IAM principals that run `StartQueryExecution`. `s3:PutObject`, `s3:ListMultipartUploadParts`, and `s3:AbortMultipartUpload` allow writing query results to all sub-folders of the query results bucket as specified by the `arn:aws:s3:::MyQueryResultsBucket/*` resource identifier, where *MyQueryResultsBucket* is the Athena query results bucket. For more information, see [Work with query results and recent queries](querying.md). `s3:GetObject` allows reading of query results and query history for the resource specified as `arn:aws:s3:::MyQueryResultsBucket`, where *MyQueryResultsBucket* is the Athena query results bucket. `s3:GetObject` also allows reading from the resource specified as `"arn:aws:s3:::MyLambdaSpillBucket/MyLambdaSpillPrefix*"`, where *MyLambdaSpillPrefix* is specified in the configuration of the Lambda function or functions being invoked.  | 

**Example – Allow an IAM principal to create a data source connector**  

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:CreateFunction",
                "lambda:ListVersionsByFunction",
                "iam:CreateRole",
                "lambda:GetFunctionConfiguration",
                "iam:AttachRolePolicy",
                "iam:PutRolePolicy",
                "lambda:PutFunctionConcurrency",
                "iam:PassRole",
                "iam:DetachRolePolicy",
                "lambda:ListTags",
                "iam:ListAttachedRolePolicies",
                "iam:DeleteRolePolicy",
                "lambda:DeleteFunction",
                "lambda:GetAlias",
                "iam:ListRolePolicies",
                "iam:GetRole",
                "iam:GetPolicy",
                "lambda:InvokeFunction",
                "lambda:GetFunction",
                "lambda:ListAliases",
                "lambda:UpdateFunctionConfiguration",
                "iam:DeleteRole",
                "lambda:UpdateFunctionCode",
                "s3:GetObject",
                "lambda:AddPermission",
                "iam:UpdateRole",
                "lambda:DeleteFunctionConcurrency",
                "lambda:RemovePermission",
                "iam:GetRolePolicy",
                "lambda:GetPolicy"
            ],
            "Resource": [
                "arn:aws:lambda:*:111122223333:function:MyAthenaLambdaFunctionsPrefix*",
                "arn:aws:s3:::awsserverlessrepo-changesets-1iiv3xa62ln3m/*",
                "arn:aws:iam::*:role/RoleName",
                "arn:aws:iam::111122223333:policy/*"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "cloudformation:CreateUploadBucket",
                "cloudformation:DescribeStackDriftDetectionStatus",
                "cloudformation:ListExports",
                "cloudformation:ListStacks",
                "cloudformation:ListImports",
                "lambda:ListFunctions",
                "iam:ListRoles",
                "lambda:GetAccountSettings",
                "ec2:DescribeSecurityGroups",
                "cloudformation:EstimateTemplateCost",
                "ec2:DescribeVpcs",
                "lambda:ListEventSourceMappings",
                "cloudformation:DescribeAccountLimits",
                "ec2:DescribeSubnets",
                "cloudformation:CreateStackSet",
                "cloudformation:ValidateTemplate"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": "cloudformation:*",
            "Resource": [
                "arn:aws:cloudformation:*:111122223333:stack/aws-serverless-repository-MyCFStackPrefix*/*",
                "arn:aws:cloudformation:*:111122223333:stack/serverlessrepo-MyCFStackPrefix*/*",
                "arn:aws:cloudformation:*:*:transform/Serverless-*",
                "arn:aws:cloudformation:*:111122223333:stackset/aws-serverless-repository-MyCFStackPrefix*:*",
                "arn:aws:cloudformation:*:111122223333:stackset/serverlessrepo-MyCFStackPrefix*:*"
            ]
        },
        {
            "Sid": "VisualEditor3",
            "Effect": "Allow",
            "Action": "serverlessrepo:*",
            "Resource": "arn:aws:serverlessrepo:*:*:applications/*"
        },
        {
            "Sid": "ECR",
            "Effect": "Allow",
            "Action": [
                "ecr:BatchGetImage",
                "ecr:GetDownloadUrlForLayer"
            ],
            "Resource": "arn:aws:ecr:*:*:repository/*"
        }
    ]
}
```


**Explanation of permissions**  

| Allowed actions | Explanation | 
| --- | --- | 
|  <pre>"lambda:CreateFunction",<br />"lambda:ListVersionsByFunction",<br />"lambda:GetFunctionConfiguration",<br />"lambda:PutFunctionConcurrency",<br />"lambda:ListTags",<br />"lambda:DeleteFunction",<br />"lambda:GetAlias",<br />"lambda:InvokeFunction",<br />"lambda:GetFunction",<br />"lambda:ListAliases",<br />"lambda:UpdateFunctionConfiguration",<br />"lambda:UpdateFunctionCode",<br />"lambda:AddPermission",<br />"lambda:DeleteFunctionConcurrency",<br />"lambda:RemovePermission",<br />"lambda:GetPolicy"<br />"lambda:GetAccountSettings",<br />"lambda:ListFunctions",<br />"lambda:ListEventSourceMappings",<br /></pre>  |  Allow the creation and management of Lambda functions listed as resources. In the example, a name prefix is used in the resource identifier `arn:aws:lambda:*:MyAWSAcctId:function:MyAthenaLambdaFunctionsPrefix*`, where `MyAthenaLambdaFunctionsPrefix` is a shared prefix used in the name of a group of Lambda functions so that they don't need to be specified individually as resources. You can specify one or more Lambda function resources.  | 
|  <pre>"s3:GetObject"</pre>  | Allows reading of a bucket that AWS Serverless Application Repository requires as specified by the resource identifier arn:aws:s3:::awsserverlessrepo-changesets-1iiv3xa62ln3m/\$1. This bucket may be specific to your account. | 
|  <pre>"cloudformation:*"</pre>  |  Allows the creation and management of CloudFormation stacks specified by the resource `MyCFStackPrefix`. These stacks and stacksets are how AWS Serverless Application Repository deploys connectors and UDFs.  | 
|  <pre>"serverlessrepo:*"</pre>  | Allows searching, viewing, publishing, and updating applications in the AWS Serverless Application Repository, specified by the resource identifier arn:aws:serverlessrepo:\$1:\$1:applications/\$1. | 
|  <pre>"ecr:BatchGetImage",<br />"ecr:GetDownloadUrlForLayer"</pre>  |  Allows the created Lambda function to access the federation connector ECR image.  | 

# Allow access to Athena UDFs: Example policies
Allow access to UDFs

The permission policy examples in this topic demonstrate required allowed actions and the resources for which they are allowed. Examine these policies carefully and modify them according to your requirements before you attach similar permissions policies to IAM identities.
+  [Example Policy to Allow an IAM Principal to Run and Return Queries that Contain an Athena UDF Statement](#udf-using-iam) 
+  [Example Policy to Allow an IAM Principal to Create an Athena UDF](#udf-creating-iam) 

**Example – Allow an IAM principal to run and return queries that contain an Athena UDF statement**  
The following identity-based permissions policy allows actions that a user or other IAM principal requires to run queries that use Athena UDF statements.  

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "athena:StartQueryExecution",
                "lambda:InvokeFunction",
                "athena:GetQueryResults",
                "s3:ListMultipartUploadParts",
                "athena:GetWorkGroup",
                "s3:PutObject",
                "s3:GetObject",
                "s3:AbortMultipartUpload",
                "athena:StopQueryExecution",
                "athena:GetQueryExecution",
                "s3:GetBucketLocation"
            ],
            "Resource": [
                "arn:aws:athena:*:MyAWSAcctId:workgroup/MyAthenaWorkGroup",
                "arn:aws:s3:::MyQueryResultsBucket/*",
                "arn:aws:lambda:*:MyAWSAcctId:function:OneAthenaLambdaFunction",
                "arn:aws:lambda:*:MyAWSAcctId:function:AnotherAthenaLambdaFunction"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": "athena:ListWorkGroups",
            "Resource": "*"
        }
    ]
}
```


**Explanation of permissions**  

| Allowed actions | Explanation | 
| --- | --- | 
|  <pre>"athena:StartQueryExecution",<br /> "athena:GetQueryResults",<br /> "athena:GetWorkGroup",<br /> "athena:StopQueryExecution",<br /> "athena:GetQueryExecution",<br /></pre>  |  Athena permissions that are required to run queries in the `MyAthenaWorkGroup` work group.  | 
|  <pre>"s3:PutObject",<br />"s3:GetObject",<br />"s3:AbortMultipartUpload"</pre>  |  `s3:PutObject` and `s3:AbortMultipartUpload` allow writing query results to all sub-folders of the query results bucket as specified by the `arn:aws:s3:::MyQueryResultsBucket/*` resource identifier, where *MyQueryResultsBucket* is the Athena query results bucket. For more information, see [Work with query results and recent queries](querying.md). `s3:GetObject` allows reading of query results and query history for the resource specified as `arn:aws:s3:::MyQueryResultsBucket`, where *MyQueryResultsBucket* is the Athena query results bucket. For more information, see [Work with query results and recent queries](querying.md). `s3:GetObject` also allows reading from the resource specified as `"arn:aws:s3:::MyLambdaSpillBucket/MyLambdaSpillPrefix*"`, where *MyLambdaSpillPrefix* is specified in the configuration of the Lambda function or functions being invoked.  | 
|  <pre>"lambda:InvokeFunction"</pre>  | Allows queries to invoke the AWS Lambda functions specified in the Resource block. For example, arn:aws:lambda:\$1:MyAWSAcctId:function:MyAthenaLambdaFunction, where MyAthenaLambdaFunction specifies the name of a Lambda function to be invoked. Multiple functions can be specified as shown in the example. | 

**Example – Allow an IAM principal to create an Athena UDF**  

```
{
    "Version": "2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": [
                "lambda:CreateFunction",
                "lambda:ListVersionsByFunction",
                "iam:CreateRole",
                "lambda:GetFunctionConfiguration",
                "iam:AttachRolePolicy",
                "iam:PutRolePolicy",
                "lambda:PutFunctionConcurrency",
                "iam:PassRole",
                "iam:DetachRolePolicy",
                "lambda:ListTags",
                "iam:ListAttachedRolePolicies",
                "iam:DeleteRolePolicy",
                "lambda:DeleteFunction",
                "lambda:GetAlias",
                "iam:ListRolePolicies",
                "iam:GetRole",
                "iam:GetPolicy",
                "lambda:InvokeFunction",
                "lambda:GetFunction",
                "lambda:ListAliases",
                "lambda:UpdateFunctionConfiguration",
                "iam:DeleteRole",
                "lambda:UpdateFunctionCode",
                "s3:GetObject",
                "lambda:AddPermission",
                "iam:UpdateRole",
                "lambda:DeleteFunctionConcurrency",
                "lambda:RemovePermission",
                "iam:GetRolePolicy",
                "lambda:GetPolicy"
            ],
            "Resource": [
                "arn:aws:lambda:*:111122223333:function:MyAthenaLambdaFunctionsPrefix*",
                "arn:aws:s3:::awsserverlessrepo-changesets-1iiv3xa62ln3m/*",
                "arn:aws:iam::*:role/RoleName",
                "arn:aws:iam::111122223333:policy/*"
            ]
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "cloudformation:CreateUploadBucket",
                "cloudformation:DescribeStackDriftDetectionStatus",
                "cloudformation:ListExports",
                "cloudformation:ListStacks",
                "cloudformation:ListImports",
                "lambda:ListFunctions",
                "iam:ListRoles",
                "lambda:GetAccountSettings",
                "ec2:DescribeSecurityGroups",
                "cloudformation:EstimateTemplateCost",
                "ec2:DescribeVpcs",
                "lambda:ListEventSourceMappings",
                "cloudformation:DescribeAccountLimits",
                "ec2:DescribeSubnets",
                "cloudformation:CreateStackSet",
                "cloudformation:ValidateTemplate"
            ],
            "Resource": "*"
        },
        {
            "Sid": "VisualEditor2",
            "Effect": "Allow",
            "Action": "cloudformation:*",
            "Resource": [
                "arn:aws:cloudformation:*:111122223333:stack/aws-serverless-repository-MyCFStackPrefix*/*",
                "arn:aws:cloudformation:*:111122223333:stack/serverlessrepo-MyCFStackPrefix*/*",
                "arn:aws:cloudformation:*:*:transform/Serverless-*",
                "arn:aws:cloudformation:*:111122223333:stackset/aws-serverless-repository-MyCFStackPrefix*:*",
                "arn:aws:cloudformation:*:111122223333:stackset/serverlessrepo-MyCFStackPrefix*:*"
            ]
        },
        {
            "Sid": "VisualEditor3",
            "Effect": "Allow",
            "Action": "serverlessrepo:*",
            "Resource": "arn:aws:serverlessrepo:*:*:applications/*"
        },
        {
            "Sid": "ECR",
            "Effect": "Allow",
            "Action": [
                "ecr:BatchGetImage",
                "ecr:GetDownloadUrlForLayer"
            ],
            "Resource": "arn:aws:ecr:*:*:repository/*"
        }
    ]
}
```


**Explanation of permissions**  

| Allowed actions | Explanation | 
| --- | --- | 
|  <pre>"lambda:CreateFunction",<br />"lambda:ListVersionsByFunction",<br />"lambda:GetFunctionConfiguration",<br />"lambda:PutFunctionConcurrency",<br />"lambda:ListTags",<br />"lambda:DeleteFunction",<br />"lambda:GetAlias",<br />"lambda:InvokeFunction",<br />"lambda:GetFunction",<br />"lambda:ListAliases",<br />"lambda:UpdateFunctionConfiguration",<br />"lambda:UpdateFunctionCode",<br />"lambda:AddPermission",<br />"lambda:DeleteFunctionConcurrency",<br />"lambda:RemovePermission",<br />"lambda:GetPolicy"<br />"lambda:GetAccountSettings",<br />"lambda:ListFunctions",<br />"lambda:ListEventSourceMappings",<br /></pre>  |  Allow the creation and management of Lambda functions listed as resources. In the example, a name prefix is used in the resource identifier `arn:aws:lambda:*:MyAWSAcctId:function:MyAthenaLambdaFunctionsPrefix*`, where *MyAthenaLambdaFunctionsPrefix* is a shared prefix used in the name of a group of Lambda functions so that they don't need to be specified individually as resources. You can specify one or more Lambda function resources.  | 
|  <pre>"s3:GetObject"</pre>  | Allows reading of a bucket that AWS Serverless Application Repository requires as specified by the resource identifier arn:aws:s3:::awsserverlessrepo-changesets-1iiv3xa62ln3m/\$1. | 
|  <pre>"cloudformation:*"</pre>  |  Allows the creation and management of CloudFormation stacks specified by the resource *MyCFStackPrefix*. These stacks and stacksets are how AWS Serverless Application Repository deploys connectors and UDFs.  | 
|  <pre>"serverlessrepo:*"</pre>  | Allows searching, viewing, publishing, and updating applications in the AWS Serverless Application Repository, specified by the resource identifier arn:aws:serverlessrepo:\$1:\$1:applications/\$1. | 

# Allow access for ML with Athena


IAM principals who run Athena ML queries must be allowed to perform the `sagemaker:invokeEndpoint` action for Sagemaker endpoints that they use. Include a policy statement similar to the following in identity-based permissions policies attached to user identities. In addition, attach the [AWS managed policy: AmazonAthenaFullAccess](security-iam-awsmanpol.md#amazonathenafullaccess-managed-policy), which grants full access to Athena actions, or a modified inline policy that allows a subset of actions.

Replace `arn:aws:sagemaker:region:AWSAcctID:ModelEndpoint` in the example with the ARN or ARNs of model endpoints to be used in queries. For more information, see [Actions, resources, and condition keys for SageMaker AI](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonsagemaker.html) in the *Service Authorization Reference*.

```
{
            "Effect": "Allow",
            "Action": [
                "sagemaker:invokeEndpoint"
            ],
            "Resource": "arn:aws:sagemaker:us-west-2:123456789012:workteam/public-crowd/default"
}
```

Whenever you use IAM policies, make sure that you follow IAM best practices. For more information, see [Security best practices in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html) in the *IAM User Guide*.

# Enable federated access to the Athena API


This section discusses federated access that allows a user or client application in your organization to call Amazon Athena API operations. In this case, your organization's users don't have direct access to Athena. Instead, you manage user credentials outside of AWS in Microsoft Active Directory. Active Directory supports [SAML 2.0](https://wiki.oasis-open.org/security) (Security Assertion Markup Language 2.0).

To authenticate users in this scenario, use the JDBC or ODBC driver with SAML.2.0 support to access Active Directory Federation Services (ADFS) 3.0 and enable a client application to call Athena API operations.

For more information about SAML 2.0 support on AWS, see [About SAML 2.0 federation](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_saml.html) in the *IAM User Guide*. 

**Note**  
Federated access to the Athena API is supported for a particular type of identity provider (IdP), the Active Directory Federation Service (ADFS 3.0), which is part of Windows Server. Federated access is not compatible with the IAM Identity Center trusted identity propagation feature. Access is established through the versions of JDBC or ODBC drivers that support SAML 2.0. For information, see [Connect to Amazon Athena with JDBC](connect-with-jdbc.md) and [Connect to Amazon Athena with ODBC](connect-with-odbc.md).

**Topics**
+ [

## Before you begin
](#access-federation-before-you-begin)
+ [

## Understand the authentication process
](#access-federation-diagram)
+ [

## Procedure: Enable SAML-based federated access to the Athena API
](#access-federation-procedure)

## Before you begin


 Before you begin, complete the following prerequisites: 
+ Inside your organization, install and configure the ADFS 3.0 as your IdP.
+ Install and configure the latest available versions of JDBC or ODBC drivers on clients that are used to access Athena. The driver must include support for federated access compatible with SAML 2.0. For information, see [Connect to Amazon Athena with JDBC](connect-with-jdbc.md) and [Connect to Amazon Athena with ODBC](connect-with-odbc.md).

## Understand the authentication process


The following diagram illustrates the authentication process of federated access to the Athena API.

![\[Diagram of federated access to the Athena API.\]](http://docs.aws.amazon.com/athena/latest/ug/images/athena-saml-based-federation.png)


1. A user in your organization uses a client application with the JDBC or ODBC driver to request authentication from your organization's IdP. The IdP is ADFS 3.0.

1. The IdP authenticates the user against Active Directory, which is your organization's Identity Store.

1. The IdP constructs a SAML assertion with information about the user and sends the assertion to the client application via the JDBC or ODBC driver.

1. The JDBC or ODBC driver calls the AWS Security Token Service [AssumeRoleWithSAML](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html) API operation, passing it the following parameters:
   + The ARN of the SAML provider
   + The ARN of the role to assume
   + The SAML assertion from the IdP

   For more information, see [AssumeRoleWithSAML](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html), in the *AWS Security Token Service API Reference*.

1. The API response to the client application via the JDBC or ODBC driver includes temporary security credentials.

1. The client application uses the temporary security credentials to call Athena API operations, allowing your users to access Athena API operations.

## Procedure: Enable SAML-based federated access to the Athena API


This procedure establishes trust between your organization's IdP and your AWS account to enable SAML-based federated access to the Amazon Athena API operation.

**To enable federated access to the Athena API:**

1. In your organization, register AWS as a service provider (SP) in your IdP. This process is known as *relying party trust*. For more information, see [Configuring your SAML 2.0 IdP with relying party trust](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml_relying-party.html) in the *IAM User Guide*. As part of this task, perform these steps:

   1. Obtain the sample SAML metadata document from this URL: [https://signin.aws.amazon.com/static/saml-metadata.xml](https://signin.aws.amazon.com/static/saml-metadata.xml).

   1. In your organization's IdP (ADFS), generate an equivalent metadata XML file that describes your IdP as an identity provider to AWS. Your metadata file must include the issuer name, creation date, expiration date, and keys that AWS uses to validate authentication responses (assertions) from your organization. 

1. In the IAM console, create a SAML identity provider entity. For more information, see [Creating SAML identity providers](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_saml.html) in the *IAM User Guide*. As part of this step, do the following: 

   1. Open the IAM console at [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/).

   1. Upload the SAML metadata document produced by the IdP (ADFS) in Step 1 in this procedure. 

1. In the IAM console, create one or more IAM roles for your IdP. For more information, see [Creating a role for a third-party Identity Provider (federation)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_create_for-idp.html) in the *IAM User Guide*. As part of this step, do the following: 
   + In the role's permission policy, list actions that users from your organization are allowed to do in AWS. 
   + In the role's trust policy, set the SAML provider entity that you created in Step 2 of this procedure as the principal. 

   This establishes a trust relationship between your organization and AWS.

1. In your organization's IdP (ADFS), define assertions that map users or groups in your organization to the IAM roles. The mapping of users and groups to the IAM roles is also known as a *claim rule*. Note that different users and groups in your organization might map to different IAM roles. 

   For information about configuring the mapping in ADFS, see the blog post: [Enabling federation to AWS using Windows Active Directory, ADFS, and SAML 2.0](https://aws.amazon.com/blogs/security/enabling-federation-to-aws-using-windows-active-directory-adfs-and-saml-2-0/).

1. Install and configure the JDBC or ODBC driver with SAML 2.0 support. For information, see [Connect to Amazon Athena with JDBC](connect-with-jdbc.md) and [Connect to Amazon Athena with ODBC](connect-with-odbc.md).

1. Specify the connection string from your application to the JDBC or ODBC driver. For information about the connection string that your application should use, see the topic *"Using the Active Directory Federation Services (ADFS) Credentials Provider"* in the *JDBC Driver Installation and Configuration Guide*, or a similar topic in the *ODBC Driver Installation and Configuration Guide* available as PDF downloads from the [Connect to Amazon Athena with JDBC](connect-with-jdbc.md) and [Connect to Amazon Athena with ODBC](connect-with-odbc.md) topics.

   Following is a high-level summary of configuring the connection string to the drivers:

   1. In the `AwsCredentialsProviderClass configuration`, set the `com.simba.athena.iamsupport.plugin.AdfsCredentialsProvider` to indicate that you want to use SAML 2.0 based authentication via ADFS IdP. 

   1. For `idp_host`, provide the host name of the ADFS IdP server.

   1. For `idp_port`, provide the port number that the ADFS IdP listens on for the SAML assertion request.

   1. For `UID` and `PWD`, provide the AD domain user credentials. When using the driver on Windows, if `UID` and `PWD` are not provided, the driver attempts to obtain the user credentials of the user logged in to the Windows machine.

   1. Optionally, set `ssl_insecure` to `true`. In this case, the driver does not check the authenticity of the SSL certificate for the ADFS IdP server. Setting to `true` is needed if the ADFS IdP's SSL certificate has not been configured to be trusted by the driver.

   1. To enable mapping of an Active Directory domain user or group to one or more IAM roles (as mentioned in step 4 of this procedure), in the `preferred_role` for the JDBC or ODBC connection, specify the IAM role (ARN) to assume for the driver connection. Specifying the `preferred_role` is optional, and is useful if the role is not the first role listed in the claim rule.

   As a result of this procedure, the following actions occur:

   1. The JDBC or ODBC driver calls the AWS STS [AssumeRoleWithSAML](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html) API, and passes it the assertions, as shown in step 4 of the [architecture diagram](#access-federation-diagram). 

   1. AWS makes sure that the request to assume the role comes from the IdP referenced in the SAML provider entity. 

   1. If the request is successful, the AWS STS [AssumeRoleWithSAML](https://docs.aws.amazon.com/STS/latest/APIReference/API_AssumeRoleWithSAML.html) API operation returns a set of temporary security credentials, which your client application uses to make signed requests to Athena. 

      Your application now has information about the current user and can access Athena programmatically. 