

# Securing your Amazon Neptune database
<a name="security"></a>

Cloud security at AWS is the highest priority. As an AWS customer, you benefit from a data center and network architecture that is built to meet the requirements of the most security-sensitive organizations.

Security is a shared responsibility between AWS and you. The [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) describes this as security *of* the cloud and security *in* the cloud:
+ **Security of the cloud** – AWS is responsible for protecting the infrastructure that runs AWS services in the AWS Cloud. AWS also provides you with services that you can use securely. Third-party auditors regularly test and verify the effectiveness of our security as part of the [AWS compliance programs](https://aws.amazon.com/compliance/programs/). To learn about the compliance programs that apply to Amazon Neptune, see [AWS Services in Scope by Compliance Program](https://aws.amazon.com/compliance/services-in-scope/).
+ **Security in the cloud** – Your responsibility is determined by the AWS service that you use. You are also responsible for other factors including the sensitivity of your data, your company’s requirements, and applicable laws and regulations.

This documentation helps you understand how to apply the shared responsibility model when using Neptune. The following topics show you how to configure Neptune to meet your security and compliance objectives. You also learn how to use other AWS services that help you to monitor and secure your Neptune resources.

**Topics**
+ [Amazon Neptune operating system upgrades](security-os-upgrades.md)
+ [Protecting data in your Amazon Neptune database](data-protection.md)
+ [Authenticating your Amazon Neptune database with AWS Identity and Access Management](iam-auth.md)
+ [Enabling IAM database authentication in Amazon Neptune](iam-auth-enable.md)
+ [Connecting to your Amazon Neptune database using AWS Identity and Access Management authentication](iam-auth-connecting.md)
+ [Managing access to Amazon Neptune databases using IAM policies](security-iam-access-manage.md)
+ [Using service-linked roles for Amazon Neptune](security-iam-service-linked-roles.md)
+ [Using temporary credentials to connect to Amazon Neptune](iam-auth-temporary-credentials.md)
+ [Logging and monitoring usage and performance in Amazon Neptune](security-monitoring.md)
+ [Amazon Neptune and interface VPC endpoints (AWS PrivateLink)](vpc-interface-endpoints.md)
+ [Compliance considerations for Amazon Neptune](neptune-compliance.md)
+ [Building resilient and disaster-tolerant Amazon Neptune deployments](disaster-recovery-resiliency.md)

# Amazon Neptune operating system upgrades
<a name="security-os-upgrades"></a>

 Amazon Neptune ensures continuous improvements in database performance, security, and stability through regular OS upgrades. These upgrades are applied to both Neptune Databases and Neptune Analytics, following a structured update process. Amazon Neptune releases OS upgrades at least once per month. 

 Neptune Database OS updates that do not require downtime are automatically applied during the maintenance window. Certain OS updates (eg: kernel version upgrade) requires an instance restart. These updates are optional and don't have a set date to apply them. However, if you don't apply these updates, they may eventually become required and automatically applied during your instance's maintenance window. 

 **Neptune Analytics** - Neptune Analytics OS upgrades are seamless and require no customer action. These updates are automatically applied in the background without downtime. 

 To maintain security and compliance, we recommend that you apply all updates made available by Amazon Neptune routinely during your maintenance window. Staying current on all optional and mandatory updates helps incorporate critical security patches and ensures alignment with various compliance obligations. Outdated OS versions may result in non-compliance with regulatory requirements. 

## Minimizing downtime for OS upgrades that require a restart
<a name="security-os-upgrades-minimizing-downtime"></a>

 For OS upgrades that require a restart, we recommend that you update the reader instances in a cluster first, then the writer instance to maximize the availability of your cluster. We don't recommend updating reader and writer instances at the same time, because you could incur longer downtime in the event of a failover. 

## Applying OS upgrades to your Neptune DB instance
<a name="security-applying-os-upgrades"></a>

 Neptune DB instances occasionally require operating system updates. Amazon Neptune upgrades the operating system to a newer version to improve database performance and customers overall security posture. Typically, the updates take about 10 minutes. Operating system updates don't change the DB engine version or DB instance class of a DB instance. 

 To be notified when a new optional update becomes available, you can subscribe to `RDS-EVENT-0230` in the security patching event category. For information about subscribing to Amazon Neptune events, see [ Subscribing to Neptune event notification](https://docs.aws.amazon.com//neptune/latest/userguide/events-subscribing.html). 

**Important**  
 Your Amazon Neptune DB instance will be taken offline during the operating system upgrade. You can minimize cluster downtime by having a multi-instance cluster. If you do not have a multi-instance cluster then you can choose to temporarily create one by adding secondary instance(s) to perform this maintenance, then deleting the additional reader instance(s) once the maintenance is completed (regular charges for the secondary instance will apply). 

 You can use the AWS Management Console or the AWS CLI to determine whether an update is available. 

### Using the AWS Management Console
<a name="security-applying-os-upgrades-management-console"></a>

 To determine whether an update is available using the AWS Management Console: 

1. Sign in to the AWS Management Console, and open the Amazon Neptune console at [https://console.aws.amazon.com/neptune/home](https://console.aws.amazon.com/neptune/home).

1.  In the navigation pane, choose **Clusters**, and then select the instance. 

1.  Choose **Maintenance**. 

1.  In the **Pending Maintenance** section, find the operating system update. 

![\[An image showing the AWS Management Console Maintenance section, and an available OS update.\]](http://docs.aws.amazon.com/neptune/latest/userguide/images/consoleForOSUpgrades.png)


 You can select the operating system update and click **Apply now** or **Apply at next maintenance window** in the **Pending Maintenance** section. If the maintenance value is **next window**, defer the maintenance items by choosing **Defer upgrade**. You can't defer a maintenance action if it has already started. 

 Alternatively, you can choose the instance from a list of clusters by clicking on **Clusters** in the navigation pane and select **Apply now** or **Apply at next maintenance window** from the **Actions** menu. 

### Using the AWS CLI
<a name="security-applying-os-upgrades-cli"></a>

 To determine whether an update is available using the AWS CLI, call the `describe-pending-maintenance-actions` command: 

```
aws neptune describe-pending-maintenance-actions
```

```
{
    "ResourceIdentifier": "arn:aws:rds:us-east-1:123456789012:db:myneptune",
    "PendingMaintenanceActionDetails": [
        {
            "Action": "system-update",
            "Description": "New Operating System update is available"
        }
    ]
}
```

 To apply the Operating system updates, call the `apply-pending-maintenance-action` command: 

```
aws neptune apply-pending-maintenance-action \
    --apply-action system-update \
    --resource-identifier (ARN of your DB instance) \
    --opt-in-type immediate
```

# Protecting data in your Amazon Neptune database
<a name="data-protection"></a>

The AWS [shared responsibility model](https://aws.amazon.com/compliance/shared-responsibility-model/) applies to data protection in Amazon Neptune. As described in this model, AWS is responsible for protecting the global infrastructure that runs all of the AWS Cloud. You are responsible for maintaining control over your content that is hosted on this infrastructure. You are also responsible for the security configuration and management tasks for the AWS services that you use. For more information about data privacy, see the [Data Privacy FAQ](https://aws.amazon.com/compliance/data-privacy-faq/). For information about data protection in Europe, see the [AWS Shared Responsibility Model and GDPR](https://aws.amazon.com/blogs/security/the-aws-shared-responsibility-model-and-gdpr/) blog post on the *AWS Security Blog*.

For data protection purposes, we recommend that you protect AWS account credentials and set up individual users with AWS IAM Identity Center or AWS Identity and Access Management (IAM). That way, each user is given only the permissions necessary to fulfill their job duties. We also recommend that you secure your data in the following ways:
+ Use multi-factor authentication (MFA) with each account.
+ Use SSL/TLS to communicate with AWS resources. We require TLS 1.2 and recommend TLS 1.3.
+ Set up API and user activity logging with AWS CloudTrail. For information about using CloudTrail trails to capture AWS activities, see [Working with CloudTrail trails](https://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-trails.html) in the *AWS CloudTrail User Guide*.
+ Use AWS encryption solutions, along with all default security controls within AWS services.
+ Use advanced managed security services such as Amazon Macie, which assists in discovering and securing sensitive data that is stored in Amazon S3.
+ If you require FIPS 140-3 validated cryptographic modules when accessing AWS through a command line interface or an API, use a FIPS endpoint. For more information about the available FIPS endpoints, see [Federal Information Processing Standard (FIPS) 140-3](https://aws.amazon.com/compliance/fips/).

We strongly recommend that you never put confidential or sensitive information, such as your customers' email addresses, into tags or free-form text fields such as a **Name** field. This includes when you work with Neptune or other AWS services using the console, API, AWS CLI, or AWS SDKs. Any data that you enter into tags or free-form text fields used for names may be used for billing or diagnostic logs. If you provide a URL to an external server, we strongly recommend that you do not include credentials information in the URL to validate your request to that server.

**Important**  
 TLS 1.3 is only supported for Neptune engine version 1.3.2.0 and up. 

You use AWS published API calls to manage Neptune through the network. Clients must support Transport Layer Security (TLS) 1.2 or later using strong cipher suites, as described in [Encrypting connects to Neptune databases](security-ssl.md). Most modern systems such as Java 7 and later support these modes.

The following sections describe further how Neptune data is protected.

**Topics**
+ [Securing your Amazon Neptune database with Amazon VPC](security-vpc.md)
+ [Encrypting connections to your Amazon Neptune database with SSL/HTTPS](security-ssl.md)
+ [Encrypting data at rest in your Amazon Neptune database](encrypt.md)

# Securing your Amazon Neptune database with Amazon VPC
<a name="security-vpc"></a>

An Amazon Neptune DB cluster can *only* be created in an Amazon Virtual Private Cloud (Amazon VPC), and its endpoints are accessible within that VPC, usually from an Amazon Elastic Compute Cloud (Amazon EC2) instance running in that VPC. Alternatively, it can be accessed using a public endpoint. For more information on public endpoints, see [Neptune public endpoints](neptune-public-endpoints.md).

You can secure your Neptune data by limiting access to the VPC where your Neptune DB cluster is located, as described in [Connecting to an Amazon Neptune cluster](get-started-connecting.md).

# Encrypting connections to your Amazon Neptune database with SSL/HTTPS
<a name="security-ssl"></a>

Amazon Neptune only allows Secure Sockets Layer (SSL) connections through HTTPS to any instance or cluster endpoint.

Neptune requires at least TLS version 1.2, using the following strong cipher suites:
+ `TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256`
+ `TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384`
+ `TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256`
+ `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`

Starting with Neptune engine version 1.3.2.0, Neptune supports TLS version 1.3 using the following cipher suites:
+ TLS\$1AES\$1128\$1GCM\$1SHA256
+ TLS\$1AES\$1256\$1GCM\$1SHA384

Even where HTTP connections are allowed in earlier engine versions, any DB cluster that uses a new DB cluster parameter group is required to use SSL by default. *To protect your data, Neptune endpoints in engine version `1.0.4.0` and above only support HTTPS requests.* See [Using the HTTP REST endpoint to connect to a Neptune DB instance](access-graph-sparql-http-rest.md) for more information.

Neptune automatically provides SSL certificates for your Neptune DB instances. You don't need to request any certificates. The certificates are provided when you create a new instance.

Neptune assigns a single wildcard SSL certificate to the instances in your account for each AWS Region. The certificate provides entries for the cluster endpoints, cluster read-only endpoints, and instance endpoints.

**Certificate Details**  
The following entries are included in the provided certificate:
+ Cluster endpoint — `*.cluster-a1b2c3d4wxyz.region.neptune.amazonaws.com`
+ Read-only endpoint — `*.cluster-ro-a1b2c3d4wxyz.region.neptune.amazonaws.com`
+ Instance endpoints — `*.a1b2c3d4wxyz.region.neptune.amazonaws.com`

Only the entries listed here are supported. 

**Proxy Connections**  
The certificates support only the hostnames that are listed in the previous section. 

If you are using a load balancer or a proxy server (such as HAProxy), you must use SSL termination and have your own SSL certificate on the proxy server. 

SSL passthrough doesn't work because the provided SSL certificates don't match the proxy server hostname.

**Root CA Certificates**  
The certificates for Neptune instances are normally validated using the local trust store of the operating system or SDK (such as the Java SDK).

If you need to provide a root certificate manually, you can download the [Amazon Root CA certificate](https://www.amazontrust.com/repository/AmazonRootCA1.pem) in PEM format from the [Amazon Trust Services Policy Repository](https://www.amazontrust.com/repository/).

**More Information**  
For more information about connecting to Neptune endpoints with SSL, see [Set up the Gremlin console to connect to a Neptune DB instance](access-graph-gremlin-console.md) and [Using the HTTP REST endpoint to connect to a Neptune DB instance](access-graph-sparql-http-rest.md).

# Encrypting data at rest in your Amazon Neptune database
<a name="encrypt"></a>

Neptune encrypted instances provide an additional layer of data protection by helping to secure your data from unauthorized access to the underlying storage. You can use Neptune encryption to increase data protection of your applications that are deployed in the cloud. You can also use it to fulfill compliance requirements for data-at-rest encryption.

To manage the keys used for encrypting and decrypting your Neptune resources, you use [AWS Key Management Service (AWS KMS)](https://docs.aws.amazon.com/kms/latest/developerguide/). AWS KMS combines secure, highly available hardware and software to provide a key management system scaled for the cloud. Using AWS KMS, you can create encryption keys and define the policies that control how these keys can be used. AWS KMS supports AWS CloudTrail, so you can audit key usage to verify that keys are being used appropriately. You can use your AWS KMS keys in combination with Neptune and supported AWS services such as Amazon Simple Storage Service (Amazon S3), Amazon Elastic Block Store (Amazon EBS), and Amazon Redshift. For a list of services that support AWS KMS, see [How AWS Services Use AWS KMS](https://docs.aws.amazon.com/kms/latest/developerguide/services.html) in the *AWS Key Management Service Developer Guide*.

All logs, backups, and snapshots are encrypted for a Neptune encrypted instance.

## Enabling Encryption for a Neptune DB Instance
<a name="encrypt-enable"></a>

To enable encryption for a new Neptune DB instance, choose **Yes** in the **Enable encryption** section on the Neptune console. For information about creating a Neptune DB instance, see [Creating an Amazon Neptune cluster](get-started-create-cluster.md).

When you create an encrypted Neptune DB instance, you can also supply the AWS KMS key identifier for your encryption key. If you don't specify an AWS KMS key identifier, Neptune uses your default Amazon RDS encryption key (`aws/rds`) for your new Neptune DB instance. AWS KMS creates your default encryption key for Neptune for your AWS account. Your AWS account has a different default encryption key for each AWS Region.

After you create an encrypted Neptune DB instance, you can't change the encryption key for that instance. So, be sure to determine your encryption key requirements before you create your encrypted Neptune DB instance.

You can use the Amazon Resource Name (ARN) of a key from another account to encrypt a Neptune DB instance. If you create a Neptune DB instance with the same AWS account that owns the AWS KMS encryption key that's used to encrypt that new Neptune DB instance, the AWS KMS key ID that you pass can be the AWS KMS key alias instead of the key's ARN.

**Important**  
If Neptune loses access to the encryption key for a Neptune DB instance—for example, when Neptune access to a key is revoked—the encrypted DB instance is placed into a terminal state and can only be restored from a backup. We strongly recommend that you always enable backups for encrypted NeptuneDB instances to guard against the loss of encrypted data in your databases.

## Key permissions needed when enabling encryption
<a name="encrypt-key-permissions"></a>

The IAM user or role creating an encrypted Neptune DB instance must have at least the following permissions for the KMS key:
+ `"kms:Encrypt"`
+ `"kms:Decrypt"`
+ `"kms:GenerateDataKey"`
+ `"kms:ReEncryptTo"`
+ `"kms:GenerateDataKeyWithoutPlaintext"`
+ `"kms:CreateGrant"`
+ `"kms:ReEncryptFrom"`
+ `"kms:DescribeKey"`

Here is an example of a key policy that includes the necessary permissions:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Id": "key-consolepolicy-3",
  "Statement": [
    {
      "Sid": "Allow use of the key for Neptune",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:role/NeptuneFullAccess"
      },
      "Action": [
        "kms:Encrypt",
        "kms:Decrypt",
        "kms:GenerateDataKey",
        "kms:ReEncryptTo",
        "kms:GenerateDataKeyWithoutPlaintext",
        "kms:CreateGrant",
        "kms:ReEncryptFrom",
        "kms:DescribeKey"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "kms:ViaService": "rds.us-east-1.amazonaws.com"
        }
      }
    },
    {
      "Sid": "Deny use of the key for non Neptune",
      "Effect": "Deny",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:role/NeptuneFullAccess"
      },
      "Action": [
        "kms:*"
      ],
      "Resource": "*",
      "Condition": {
        "StringNotEquals": {
          "kms:ViaService": "rds.us-east-1.amazonaws.com"
        }
      }
    }
  ]
}
```

------
+ The first statement provides access to all the required AWS KMS APIs for this role, scoped down to the RDS Service Principal.
+ The second statement tightens the security more by enforcing that this key is not usable by this role for any other AWS service.

You could also scope `createGrant` permissions down further by adding:

```
"Condition": {
  "Bool": {
    "kms:GrantIsForAWSResource": true
  }
}
```

## Limitations of Neptune Encryption
<a name="encrypt-limitations"></a>

The following limitations exist for encrypting Neptune clusters:
+ You cannot convert an unencrypted DB cluster to an encrypted one.

  However, you can restore an unencrypted DB cluster snapshot to an encrypted DB cluster. To do this, specify a KMS encryption key when you restore from the unencrypted DB cluster snapshot.
+ You cannot convert an unencrypted DB instance to an encrypted one. You can only enable encryption for a DB instance when you create it.
+ Also, DB instances that are encrypted can't be modified to disable encryption.
+ You can't have an encrypted Read Replica of an unencrypted DB instance, or an unencrypted Read Replica of an encrypted DB instance.
+ Encrypted Read Replicas must be encrypted with the same key as the source DB instance.

# Authenticating your Amazon Neptune database with AWS Identity and Access Management
<a name="iam-auth"></a>

AWS Identity and Access Management (IAM) is an AWS service that helps an administrator securely control access to AWS resources. IAM administrators control who can be *authenticated* (signed in) and *authorized* (have permissions) to use Neptune resources. IAM is an AWS service that you can use with no additional charge.

You can use AWS Identity and Access Management (IAM) to authenticate to your Neptune DB instance or DB cluster. When IAM database authentication is enabled, each request must be signed using AWS Signature Version 4.

AWS Signature Version 4 adds authentication information to AWS requests. For security, all requests to Neptune DB clusters with IAM authentication enabled must be signed with an access key. This key consists of an access key ID and secret access key. The authentication is managed externally using IAM policies.

Neptune authenticates on connection, and for WebSockets connections it verifies the permissions periodically to ensure that the user still has access.

**Note**  
Revoking, deleting, or rotating of credentials associated with the IAM user is not recommended because it does not terminate any connections that are already open.
There are limits on the number of concurrent WebSocket connections per database instance, and on how long a connection can remain open. For more information, see [WebSockets Limits](limits.md#limits-websockets).

## IAM Use Depends on Your Role
<a name="security-iam-audience"></a>

How you use AWS Identity and Access Management (IAM) differs, depending on the work you do in Neptune.

**Service user** – If you use the Neptune service to do your job, then your administrator provides you with the credentials and permissions that you need for using the Neptune data plane. As you need more access to do your work, understanding how data access is managed can help you request the right permissions from your administrator.

**Service administrator** – If you're in charge of Neptune resources at your company, you probably have access to Neptune management actions, which correspond to the [Neptune managment API](api.md). It may also be your job to determine which Neptune data-access actions and resources service users need in order to do their jobs. An IAM administrator can then apply IAM policies to change the permissions of your service users.

**IAM administrator** – If you're an IAM administrator, you will need to write IAM policies to manage both management and data access to Neptune. To view example Neptune identity-based policies that you can use, see [Using different kinds of IAM policies for controlling access to Neptune](security-iam-access-manage.md#iam-auth-policy).

## Authenticating with Identities
<a name="security-iam-authentication"></a>

Authentication is how you sign in to AWS using your identity credentials. You must be authenticated as the AWS account root user, an IAM user, or by assuming an IAM role.

You can sign in as a federated identity using credentials from an identity source like AWS IAM Identity Center (IAM Identity Center), single sign-on authentication, or Google/Facebook credentials. For more information about signing in, see [How to sign in to your AWS account](https://docs.aws.amazon.com/signin/latest/userguide/how-to-sign-in.html) in the *AWS Sign-In User Guide*.

For programmatic access, AWS provides an SDK and CLI to cryptographically sign requests. For more information, see [AWS Signature Version 4 for API requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_sigv.html) in the *IAM User Guide*.

### AWS account root user
<a name="security-iam-authentication-rootuser"></a>

 When you create an AWS account, you begin with one sign-in identity called the AWS account *root user* that has complete access to all AWS services and resources. We strongly recommend that you don't use the root user for everyday tasks. For tasks that require root user credentials, see [Tasks that require root user credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_root-user.html#root-user-tasks) in the *IAM User Guide*. 

### IAM Users and Groups
<a name="security-iam-authentication-iamuser"></a>

An *[IAM user](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users.html)* is an identity with specific permissions for a single person or application. We recommend using temporary credentials instead of IAM users with long-term credentials. For more information, see [Require human users to use federation with an identity provider to access AWS using temporary credentials](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#bp-users-federation-idp) in the *IAM User Guide*.

An [https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_groups.html) specifies a collection of IAM users and makes permissions easier to manage for large sets of users. For more information, see [Use cases for IAM users](https://docs.aws.amazon.com/IAM/latest/UserGuide/gs-identities-iam-users.html) in the *IAM User Guide*.

### IAM Roles
<a name="security-iam-authentication-iamrole"></a>

An *[IAM role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)* is an identity with specific permissions that provides temporary credentials. You can assume a role by [switching from a user to an IAM role (console)](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-console.html) or by calling an AWS CLI or AWS API operation. For more information, see [Methods to assume a role](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_manage-assume.html) in the *IAM User Guide*.

IAM roles are useful for federated user access, temporary IAM user permissions, cross-account access, cross-service access, and applications running on Amazon EC2. For more information, see [Cross account resource access in IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-cross-account-resource-access.html) in the *IAM User Guide*.

# Enabling IAM database authentication in Amazon Neptune
<a name="iam-auth-enable"></a>

By default, IAM database authentication is disabled when you create an Amazon Neptune DB cluster. You can enable IAM database authentication (or disable it again) using the AWS Management Console.

To create a new Neptune DB cluster with IAM authentication by using the console, follow the instructions for creating a Neptune DB cluster in [Launching a Neptune DB cluster using the AWS Management Console](manage-console-launch-console.md).

On the second page of the creation process, for **Enable IAM DB Authentication**, choose **Yes**.

**To enable or disable IAM authentication for an existing DB instance or cluster**

1. Sign in to the AWS Management Console, and open the Amazon Neptune console at [https://console.aws.amazon.com/neptune/home](https://console.aws.amazon.com/neptune/home).

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

1. Choose the Neptune DB cluster that you want to modify, and choose **Cluster actions**. Then choose **Modify cluster**.

1. In the **Database options** section, for **IAM DB Authentication**, choose either **Enable IAM DB authorization** or **No** (to disable). Then choose **Continue**.

1. To apply the changes immediately, choose **Apply immediately**.

1. Choose **Modify cluster**.

# Connecting to your Amazon Neptune database using AWS Identity and Access Management authentication
<a name="iam-auth-connecting"></a>

Amazon Neptune resources that have IAM DB authentication enabled require all HTTP requests to be signed using AWS Signature Version 4. For general information about signing requests with AWS Signature Version 4, see [Signing AWS API requests](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-signing.html).

AWS Signature Version 4 is the process to add authentication information to AWS requests. For security, most requests to AWS must be signed with an access key, which consists of an access key ID and secret access key.

**Note**  
If you are using temporary credentials, they expire after a specified interval, *including the session token*.  
You must update your session token when you request new credentials. For more information, see [Using Temporary Security Credentials to Request Access to AWS Resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html).

**Important**  
Accessing Neptune with IAM-based authentication requires that you create HTTP requests and sign the requests yourself.

**How Signature Version 4 Works**

1. You create a canonical request.

1. You use the canonical request and some other information to create a string-to-sign.

1. You use your AWS secret access key to derive a signing key, and then use that signing key and the string-to-sign to create a signature.

1. You add the resulting signature to the HTTP request in a header or as a query string parameter.

When Neptune receives the request, it performs the same steps that you did to calculate the signature. Neptune then compares the calculated signature to the one you sent with the request. If the signatures match, the request is processed. If the signatures don't match, the request is denied.

For general information about signing requests with AWS Signature Version 4, see [Signature Version 4 Signing Process](https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html) in the *AWS General Reference*.

The following sections contain examples that show how to send signed requests to the Gremlin and SPARQL endpoints of a Neptune DB instance with IAM authentication enabled.

**Topics**
+ [Prerequisites for connecting Amazon Neptune databases using IAM authentication](iam-auth-connect-prerq.md)
+ [Connecting to Amazon Neptune databases using IAM authentication from the command line](iam-auth-connect-command-line.md)
+ [Connecting to Amazon Neptune databases using IAM authentication with Gremlin console](iam-auth-connecting-gremlin-console.md)
+ [Connecting to Amazon Neptune databases using IAM with Gremlin Java](iam-auth-connecting-gremlin-java.md)
+ [Connecting to Amazon Neptune databases using IAM authentication with Java and SPARQL](iam-auth-connecting-sparql-java.md)
+ [Connecting to Amazon Neptune databases using IAM authentication with SPARQL and Node.js](iam-auth-connecting-sparql-node.md)
+ [Connecting to Amazon Neptune databases using IAM authentication with Python](iam-auth-connecting-python.md)
+ [Connecting to Amazon Neptune databases using IAM authentication with Gremlin Python](gremlin-python-iam-auth.md)
+ [Connecting to Amazon Neptune databases using IAM authentication with Gremlin JavaScript](gremlin-javascript-iam-auth.md)
+ [Connecting to Amazon Neptune databases using IAM authentication with Gremlin Go](gremlin-go-iam-auth.md)
+ [Connecting to Amazon Neptune databases using IAM authentication with Gremlin .NET](gremlin-dotnet-iam-auth.md)

# Prerequisites for connecting Amazon Neptune databases using IAM authentication
<a name="iam-auth-connect-prerq"></a>

The following are instructions for installing Apache Maven and Java 8 on an Amazon EC2 instance. These are required for the Amazon Neptune Signature Version 4 authentication samples.

**To Install Apache Maven and Java 8 on your EC2 instance**

1. Connect to your Amazon EC2 instance with an SSH client.

1. Install Apache Maven on your EC2 instance. If using Amazon Linux 2023 (preferred), use:

   ```
   sudo dnf update -y
   sudo dnf install maven -y
   ```

   If using Amazon Linux 2, download the latest binary from [ https://maven.apache.org/download.cgi: ](https://maven.apache.org/download.cgi:)

   ```
   sudo yum remove maven -y
   wget https://dlcdn.apache.org/maven/maven-3/ <version>/binaries/apache-maven-<version>-bin.tar.gz
   sudo tar -xzf apache-maven-<version>-bin.tar.gz -C /opt/
   sudo ln -sf /opt/apache-maven-<version> /opt/maven
   echo 'export MAVEN_HOME=/opt/maven' >> ~/.bashrc
   echo 'export PATH=$MAVEN_HOME/bin:$PATH' >> ~/.bashrc
   source ~/.bashrc
   ```

1. The Gremlin libraries require Java 8. Enter the following to install Java 8 on your EC2 instance.

   ```
   sudo yum install java-1.8.0-devel
   ```

1. Enter the following to set Java 8 as the default runtime on your EC2 instance.

   ```
   sudo /usr/sbin/alternatives --config java
   ```

   When prompted, enter the number for Java 8.

1. Enter the following to set Java 8 as the default compiler on your EC2 instance.

   ```
   sudo /usr/sbin/alternatives --config javac
   ```

   When prompted, enter the number for Java 8.

# Connecting to Amazon Neptune databases using IAM authentication from the command line
<a name="iam-auth-connect-command-line"></a>

Having a command-line tool for submitting queries to your Neptune DB cluster is very handy, as illustrated in many of the examples in this documentation. The [curl](https://curl.haxx.se/) tool is an excellent option for communicating with Neptune endpoints if IAM authentication is not enabled.

**However, to keep your data secure it is best to enable IAM authentication.**

When IAM authentication is enabled, every request must be [signed using Signature Version 4 (Sig4)](https://docs.aws.amazon.com/general/latest/gr/signing-aws-api-requests.html). The third-party [awscurl](https://github.com/okigan/awscurl) command-line tool uses the same syntax as `curl`, and can sign queries using Sig4 signing. The [Using `awscurl`](#iam-auth-connect-awscurl) section below explains how to use `awscurl` securely with temporary credentials.

## Setting up a command-line tool to use HTTPS
<a name="iam-auth-connect-command-line-https"></a>

Neptune requires that all connections use HTTPS. Any command line tool like `curl` or `awscurl` needs access to appropriate certificates in order to use HTTPS. As long as `curl` or `awscurl` can locate the appropriate certificates, they handle HTTPS connections just like HTTP connections, without needing extra parameters. Examples in this documentation are based on that scenario.

To learn how to obtain such certificates and how to format them properly into a certificate authority (CA) certificate store that `curl` can use, see [SSL Certificate Verification](https://curl.haxx.se/docs/sslcerts.html) in the `curl` documentation.

You can then specify the location of this CA certificate store using the `CURL_CA_BUNDLE` environment variable. On Windows, `curl` automatically looks for it in a file named `curl-ca-bundle.crt`. It looks first in the same directory as `curl.exe` and then elsewhere on the path. For more information, see [SSL Certificate Verification](https://curl.haxx.se/docs/sslcerts.html).

## Using `awscurl` with temporary credentials to securely connect to a DB cluster with IAM authentication enabled
<a name="iam-auth-connect-awscurl"></a>

The [awscurl](https://github.com/okigan/awscurl) tool uses the same syntax as `curl`, but needs additional information as well:
+ **`--access_key`**   –   A valid access key. If not supplied using this parameter, it must be supplied in the `AWS_ACCESS_KEY_ID` enviroment variable, or in a configuration file.
+ **`--secret_key`**   –   A valid secret key corresponding to the access key. If not supplied using this parameter, it must be supplied in the `AWS_SECRET_ACCESS_KEY` enviroment variable, or in a configuration file.
+ **`--security_token`**   –   A valid session token. If not supplied using this parameter, it must be supplied in the `AWS_SECURITY_TOKEN` enviroment variable, or in a configuration file.

In the past, it was common practice to use persistent credentials with `awscurl`, such as IAM user credentials or even root credentials, but this is not recommended. Instead, generate temporary credentials using one of the [AWS Security Token Service (STS) APIs](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_request.html), or one of their [AWS CLI wrappers](https://docs.aws.amazon.com/cli/latest/reference/sts/index.html).

It is best to place the `AccessKeyId`, `SecretAccessKey`, and `SessionToken` values that are returned by the STS call into appropriate environment variables in your shell session rather than into a configuration file. Then, when the shell terminates, the credentials are automatically discarded, which is not the case with a configuration file. Similarly, don't request a longer duration for the temporary credentials than you are likely to need.

The following example shows the steps you might take in a Linux shell to obtain temporary credentials that are good for half an hour using [sts assume-role](https://docs.aws.amazon.com/cli/latest/reference/sts/assume-role), and then place them in environment variables where `awscurl` can find them:

```
aws sts assume-role \
    --duration-seconds 1800 \
    --role-arn "arn:aws:iam::(account-id):role/(rolename)" \
    --role-session-name AWSCLI-Session > $output
AccessKeyId=$(echo $output | jq '.Credentials''.AccessKeyId')
SecretAccessKey=$(echo $output | jq '.Credentials''.SecretAccessKey')
SessionToken=$(echo $output | jq '.Credentials''.SessionToken')

export AWS_ACCESS_KEY_ID=$AccessKeyId
export AWS_SECRET_ACCESS_KEY=$SecretAccessKey
export AWS_SESSION_TOKEN=$SessionToken
```

You could then use `awscurl` to make a signed request to your DB cluster something like this:

```
awscurl (your cluster endpoint):8182/status \
    --region us-east-1 \
    --service neptune-db
```

# Connecting to Amazon Neptune databases using IAM authentication with Gremlin console
<a name="iam-auth-connecting-gremlin-console"></a>

To connect to Amazon Neptune using the Gremlin console with Signature Version 4 authentication, you use `requestInterceptor()` to plug in a SigV4 signer to the connection established by the `:remote` command. This requires you to configure the `Cluster` object manually and then pass it to the `:remote` command.

Note that this is quite different from the typical situation where the `:remote` command takes a configuration file to form the connection. The configuration file approach won't work because `requestInterceptor()` must be set programmatically, and can't load its configuration from a file.

**Note**  
The following examples use `requestInterceptor()`, which was introduced in TinkerPop 3.6.6. If you are using a TinkerPop version earlier than 3.6.6 (but 3.5.5 or higher), use `handshakeInterceptor()` instead of `requestInterceptor()` in the code examples below.

The following prerequisites are necessary:
+ You must have the IAM credentials needed to sign the requests. See [Using the default credential provider chain](https://docs.aws.amazon.com//sdk-for-java/latest/developer-guide/credentials-chain.html) in the AWS SDK for Java Developer Guide.
+ You must have installed a Gremlin console version that is compatible with the version of the Neptune engine being used by your DB cluster.

If you are using temporary credentials, they expire after a specified interval, as does the session token, so you must update your session token when you request new credentials. See [Using temporary security credentials to request access to AWS resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) in the IAM User Guide.

For help connecting using SSL/TLS, see [SSL/TLS configuration](access-graph-gremlin-java.md#access-graph-gremlin-java-ssl).

**Connect the Gremlin console with Sig4 signing**

1. Start the Gremlin console:

   ```
   $ bin/gremlin.sh
   ```

1. At the `gremlin>` prompt, install the `amazon-neptune-sigv4-signer` library (this only needs to be done once for the console):

   ```
   :install com.amazonaws amazon-neptune-sigv4-signer 2.4.0
   ```

   If you encounter problems with this step, it may help to consult the [TinkerPop documentation](https://tinkerpop.apache.org/docs/current/reference/#gremlin-applications) about [Grape](http://docs.groovy-lang.org/latest/html/documentation/grape.html) configuration.
**Note**  
If you are using an HTTP proxy, you may encounter errors with this step where the `:install` command does not complete. To solve this problem, run the following commands to tell the console about the proxy:  

   ```
   System.setProperty("https.proxyHost", "(the proxy IP address)")
   System.setProperty("https.proxyPort", "(the proxy port)")
   ```

1. Import the class required to handle the signing into `requestInterceptor()`:

   ```
   :import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider
   :import com.amazonaws.neptune.auth.NeptuneNettyHttpSigV4Signer
   ```

1. If you are using temporary credentials, you will also need to supply your Session Token as follows:

   ```
   System.setProperty("aws.sessionToken","(your session token)")
   ```

1. If you haven't otherwise established your account credentials, you can assign them as follows:

   ```
   System.setProperty("aws.accessKeyId","(your access key)")
   System.setProperty("aws.secretKey","(your secret key)")
   ```

1. Manually construct the `Cluster` object to connect to Neptune:

   ```
   cluster = Cluster.build("(host name)")  \
                    .enableSsl(true) \
                    .requestInterceptor { r ->  \
                      def sigV4Signer = new NeptuneNettyHttpSigV4Signer("(Amazon region)", \
                                        DefaultCredentialsProvider.create()); \
                      sigV4Signer.signRequest(r); \
                      return r; } \
                    .create()
   ```

   For help finding the host name of a Neptune DB instance, see [Connecting to Amazon Neptune Endpoints](feature-overview-endpoints.md).

1. Establish the `:remote` connection using the variable name of the `Cluster` object in the previous step:

   ```
   :remote connect tinkerpop.server cluster
   ```

1. Enter the following command to switch to remote mode. This sends all Gremlin queries to the remote connection:

   ```
   :remote console
   ```

# Connecting to Amazon Neptune databases using IAM with Gremlin Java
<a name="iam-auth-connecting-gremlin-java"></a>

Here is an example of how to connect to Neptune using the Gremlin Java API with Sig4 signing (it assumes general knowledge about using Maven). This example uses the [Amazon Neptune SigV4 Signer](https://github.com/aws/amazon-neptune-sigv4-signer) library to assist in request signing. First, define the dependencies as part of the `pom.xml` file:

**Note**  
The following examples use `requestInterceptor()`, which was introduced in TinkerPop 3.6.6. If you are using a TinkerPop version earlier than 3.6.6 (but 3.5.5 or higher), use `handshakeInterceptor()` instead of `requestInterceptor()` in the code examples below.

```
<dependency>
  <groupId>com.amazonaws</groupId>
  <artifactId>amazon-neptune-sigv4-signer</artifactId>
  <version>3.1.0</version>
</dependency>
```

 The Amazon Neptune SigV4 Signer supports both versions 1.x and 2.x of the AWS Java SDK. The following examples use 2.x, where `DefaultCredentialsProvider` is a `software.amazon.awssdk.auth.credentials.AwsCredentialsProvider` instance. If you are upgrading from 1.x to 2.x, see the [Credentials provider changes](https://docs.aws.amazon.com//sdk-for-java/latest/developer-guide/migration-client-credentials.html) in the AWS SDK for Java 2.x documentation. 

```
import software.amazon.awssdk.auth.credentials.DefaultCredentialsProvider;
import com.amazonaws.neptune.auth.NeptuneNettyHttpSigV4Signer;
import com.amazonaws.neptune.auth.NeptuneSigV4SignerException;

 ...

System.setProperty("aws.accessKeyId","your-access-key");
System.setProperty("aws.secretKey","your-secret-key");

 ...

Cluster cluster = Cluster.build((your cluster))
                 .enableSsl(true)
                 .requestInterceptor( r ->
                  {
                    try {
                      NeptuneNettyHttpSigV4Signer sigV4Signer =
                        new NeptuneNettyHttpSigV4Signer("(your region)", DefaultCredentialsProvider.create());
                      sigV4Signer.signRequest(r);
                    } catch (NeptuneSigV4SignerException e) {
                      throw new RuntimeException("Exception occurred while signing the request", e);
                    }
                    return r;
                  }
                 ).create();
try {
  Client client = cluster.connect();
  client.submit("g.V().has('code','IAD')").all().get();
} catch (Exception e) {
  throw new RuntimeException("Exception occurred while connecting to cluster", e);
}
```

## Cross account IAM authentication
<a name="iam-auth-connecting-gremlin-java-cross-account"></a>

 Amazon Neptune supports cross account IAM authentication through the use of role assumption, also sometimes referred to as [ role chaining](https://docs.aws.amazon.com//neptune/latest/userguide/bulk-load-tutorial-chain-roles.html#bulk-load-tutorial-chain-cross-account). To provide access to a Neptune cluster from an application hosted in a different AWS account: 
+  Create a new IAM user or role in the application AWS account, with a trust policy that allows the user or role to assume another IAM role. Assign this role to the compute hosting the application (EC2 instance, Lambda function, ECS Task, etc.). 

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

****  

  ```
  {
    "Version":"2012-10-17",		 	 	 
    "Statement": [
      {
        "Sid": "assumeRolePolicy",
        "Effect": "Allow",
        "Action": "sts:AssumeRole",
        "Resource": "arn:aws:iam::111122223333:role/role-name"
      }
    ]
  }
  ```

------
+  Create a new IAM role in the Neptune database AWS account that allows access to the Neptune database and allows role assumption from the application account IAM user/role. Use a trust policy of: 

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

****  

  ```
  {
      "Version":"2012-10-17",		 	 	 
      "Statement": [
          {
              "Effect": "Allow",
              "Principal": {
                  "AWS": [
                      "(ARN of application account IAM user or role)"
                  ]
              },
              "Action": "sts:AssumeRole",
              "Condition": {}
          }
      ]
  }
  ```

------
+  Use the following code example as guidance on how to use these two roles to allow the application to access Neptune. In this example, the application account role will be assumed via the [DefaultCredentialProviderChain](https://docs.aws.amazon.com//sdk-for-java/v1/developer-guide/credentials.html) when creating the `STSclient`. The `STSclient` is then used via the `STSAssumeRoleSessionCredentialsProvider` to assume the role hosted in the Neptune database AWS account. 

  ```
  public static void main( String[] args )
    {
  
      /* 
       * Establish an STS client from the application account.
       */
      AWSSecurityTokenService client = AWSSecurityTokenServiceClientBuilder
          .standard()
          .build();
  
      /*
       * Define the role ARN that you will be assuming in the database account where the Neptune cluster resides.
       */
      String roleArnToAssume = "arn:aws:iam::012345678901:role/CrossAccountNeptuneRole";
      String crossAccountSessionName = "cross-account-session-" + UUID.randomUUID();
  
      /*
       * Change the Credentials Provider in the SigV4 Signer to use the STSAssumeRole Provider and provide it
       * with both the role to be assumed, the original STS client, and a session name (which can be
       * arbitrary.)
       */
      Cluster cluster = Cluster.build()
                   .addContactPoint("neptune-cluster.us-west-2.neptune.amazonaws.com")
                   .enableSsl(true)
                   .port(8182)
                   .requestInterceptor( r ->
                    {
                      try {
                        NeptuneNettyHttpSigV4Signer sigV4Signer =
                          // new NeptuneNettyHttpSigV4Signer("us-west-2", DefaultCredentialsProvider.create());
                          new NeptuneNettyHttpSigV4Signer(
                                  "us-west-2",  
                                   new STSAssumeRoleSessionCredentialsProvider
                                      .Builder(roleArnToAssume, crossAccountSessionName)
                                          .withStsClient(client)
                                          .build());
                        sigV4Signer.signRequest(r);
                      } catch (NeptuneSigV4SignerException e) {
                        throw new RuntimeException("Exception occurred while signing the request", e);
                      }
                      return r;
                    }
                   ).create();
  
      GraphTraversalSource g = traversal().withRemote(DriverRemoteConnection.using(cluster));
  
      /* whatever application code is necessary */
  
      cluster.close();
    }
  ```

# Connecting to Amazon Neptune databases using IAM authentication with Java and SPARQL
<a name="iam-auth-connecting-sparql-java"></a>

This section shows how to connect to Neptune using either RDF4J or Apache Jena with Signature Version 4 authentication.

**Prerequisites**
+ Java 8 or higher.
+ Apache Maven 3.3 or higher.

  For information about installing these prerequisites on an EC2 instance running Amazon Linux, see [Prerequisites for connecting Amazon Neptune databases using IAM authentication](iam-auth-connect-prerq.md).
+ IAM credentials to sign the requests. For more information, see [Using the Default Credential Provider Chain](https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/credentials.html#credentials-default) in the *AWS SDK for Java Developer Guide*.
**Note**  
If you are using temporary credentials, they expire after a specified interval, *including the session token*.  
You must update your session token when you request new credentials. For more information, see [Using Temporary Security Credentials to Request Access to AWS Resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html) in the *IAM User Guide*.
+ Set the `SERVICE_REGION` variable to one of the following, indicating the Region of your Neptune DB instance:
  + US East (N. Virginia):   `us-east-1`
  + US East (Ohio):   `us-east-2`
  + US West (N. California):   `us-west-1`
  + US West (Oregon):   `us-west-2`
  + Canada (Central):   `ca-central-1`
  + Canada West (Calgary):   `ca-west-1`
  + South America (São Paulo):   `sa-east-1`
  + Europe (Stockholm):   `eu-north-1`
  + Europe (Spain):   `eu-south-2`
  + Europe (Ireland):   `eu-west-1`
  + Europe (London):   `eu-west-2`
  + Europe (Paris):   `eu-west-3`
  + Europe (Frankfurt):   `eu-central-1`
  + Middle East (Bahrain):   `me-south-1`
  + Middle East (UAE):   `me-central-1`
  + Israel (Tel Aviv):   `il-central-1`
  + Africa (Cape Town):   `af-south-1`
  + Asia Pacific (Hong Kong):   `ap-east-1`
  + Asia Pacific (Tokyo):   `ap-northeast-1`
  + Asia Pacific (Seoul):   `ap-northeast-2`
  + Asia Pacific (Osaka):   `ap-northeast-3`
  + Asia Pacific (Singapore):   `ap-southeast-1`
  + Asia Pacific (Sydney):   `ap-southeast-2`
  + Asia Pacific (Jakarta):   `ap-southeast-3`
  + Asia Pacific (Melbourne):   `ap-southeast-4`
  + Asia Pacific (Malaysia):   `ap-southeast-5`
  + Asia Pacific (Mumbai):   `ap-south-1`
  + Asia Pacific (Hyderabad):   `ap-south-2`
  + China (Beijing):   `cn-north-1`
  + China (Ningxia):   `cn-northwest-1`
  + AWS GovCloud (US-West):   `us-gov-west-1`
  + AWS GovCloud (US-East):   `us-gov-east-1`

**To connect to Neptune using either RDF4J or Apache Jena with Signature Version 4 signing**

1. Clone the sample repository from GitHub.

   ```
   git clone https://github.com/aws/amazon-neptune-sparql-java-sigv4.git
   ```

1. Change into the cloned directory.

   ```
   cd amazon-neptune-sparql-java-sigv4
   ```

1. Get the latest version of the project by checking out the branch with the latest tag.

   ```
   git checkout $(git describe --tags `git rev-list --tags --max-count=1`)
   ```

1. Enter one of the following commands to compile and run the example code.

   Replace *your-neptune-endpoint* with the hostname or IP address of your Neptune DB instance. The default port is 8182.
**Note**  
For information about finding the hostname of your Neptune DB instance, see the [Connecting to Amazon Neptune Endpoints](feature-overview-endpoints.md) section.

**Eclipse RDF4J**  
Enter the following to run the RDF4J example.

   ```
   mvn compile exec:java \
       -Dexec.mainClass="com.amazonaws.neptune.client.rdf4j.NeptuneRdf4JSigV4Example" \
       -Dexec.args="https://your-neptune-endpoint:portsparql region-name"
   ```

**Apache Jena**  
Enter the following to run the Apache Jena example.

   ```
   mvn compile exec:java \
       -Dexec.mainClass="com.amazonaws.neptune.client.jena.NeptuneJenaSigV4Example" \
       -Dexec.args="https://your-neptune-endpoint:port"
   ```

1. To view the source code for the example, see the examples in the `src/main/java/com/amazonaws/neptune/client/` directory.

To use the SigV4 signing driver in your own Java application, add the `amazon-neptune-sigv4-signer` Maven package to the `<dependencies>` section of your `pom.xml`. We recommend that you use the examples as a starting point.

# Connecting to Amazon Neptune databases using IAM authentication with SPARQL and Node.js
<a name="iam-auth-connecting-sparql-node"></a>

## Querying using Signature V4 signing and the AWS SDK for Javascript V3
<a name="iam-auth-querying-sparql-js-sdk-v3"></a>

Here is an example of how to connect to Neptune SPARQL using Node.js with Signature Version 4 authentication and the AWS SDK for Javascript V3:

```
const { HttpRequest }  = require('@smithy/protocol-http');
const { fromNodeProviderChain } = require('@aws-sdk/credential-providers');
const { SignatureV4 } = require('@smithy/signature-v4');
const { Sha256 } = require('@aws-crypto/sha256-universal');
const https = require('https');

var region = 'us-west-2'; // e.g. us-west-1
var neptune_endpoint = 'your-Neptune-cluster-endpoint';  // like: 'cluster-id.region.neptune.amazonaws.com'
var query = `query=PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX class: <http://aws.amazon.com/neptune/csv2rdf/class/>
PREFIX resource: <http://aws.amazon.com/neptune/csv2rdf/resource/>
PREFIX prop: <http://aws.amazon.com/neptune/csv2rdf/datatypeProperty/>
PREFIX objprop: <http://aws.amazon.com/neptune/csv2rdf/objectProperty/>

SELECT ?movies ?title WHERE {
  ?jel prop:name "James Earl Jones" .
  ?movies ?p2 ?jel .
  ?movies prop:title ?title
} LIMIT 10`;

runQuery(query);

function runQuery(q) {
  var request = new HttpRequest({
    hostname: neptune_endpoint,
    port: 8182,
    path: 'sparql',
    body: encodeURI(query),
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'host': neptune_endpoint + ':8182',
    },
    method: 'POST',
  });

  const credentialProvider = fromNodeProviderChain();
  let credentials = credentialProvider();
  credentials.then(
    (cred)=>{
      var signer = new SignatureV4({credentials: cred, region: region, sha256: Sha256, service: 'neptune-db'});
      signer.sign(request).then(
        (req)=>{
          var responseBody = '';
          var sendreq = https.request(
            {
              host: req.hostname,
              port: req.port,
              path: req.path,
              method: req.method,
              headers: req.headers,
            },
          (res) => {
            res.on('data', (chunk) => { responseBody += chunk; });
            res.on('end', () => {
                console.log(JSON.parse(responseBody));
            });
          });
          sendreq.write(req.body);
          sendreq.end();
        }
      );
    },
    (err)=>{
      console.error(err);
    }
  );
}
```

## Querying using Signature V4 signing and the AWS SDK for Javascript V2
<a name="iam-auth-querying-sparql-js-sdk-v2"></a>

Here is an example of how to connect to Neptune SPARQL using Node.js with Signature Version 4 authentication and the AWS SDK for Javascript V2:

```
var AWS = require('aws-sdk');

var region = 'us-west-2'; // e.g. us-west-1
var neptune_endpoint = 'your-Neptune-cluster-endpoint';  // like: 'cluster-id.region.neptune.amazonaws.com'
var query = `query=PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
PREFIX class: <http://aws.amazon.com/neptune/csv2rdf/class/>
PREFIX resource: <http://aws.amazon.com/neptune/csv2rdf/resource/>
PREFIX prop: <http://aws.amazon.com/neptune/csv2rdf/datatypeProperty/>
PREFIX objprop: <http://aws.amazon.com/neptune/csv2rdf/objectProperty/>

SELECT ?movies ?title WHERE {
    ?jel prop:name "James Earl Jones" .
    ?movies ?p2 ?jel .
    ?movies prop:title ?title
} LIMIT 10`;

runQuery(query);

function runQuery(q) {

    var endpoint = new AWS.Endpoint(neptune_endpoint);
    endpoint.port = 8182;
    var request = new AWS.HttpRequest(endpoint, region);
    request.path += 'sparql';
    request.body = encodeURI(query);
    request.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    request.headers['host'] = neptune_endpoint;
    request.method = 'POST';

    var credentials = new AWS.CredentialProviderChain();
    credentials.resolve((err, cred)=>{
        var signer = new AWS.Signers.V4(request, 'neptune-db');
        signer.addAuthorization(cred, new Date());
    });

    var client = new AWS.HttpClient();
    client.handleRequest(request, null, function(response) {
        console.log(response.statusCode + ' ' + response.statusMessage);
        var responseBody = '';
        response.on('data', function (chunk) {
            responseBody += chunk;
        });
        response.on('end', function (chunk) {
            console.log('Response body: ' + responseBody);
        });
    }, function(error) {
        console.log('Error: ' + error);
    });
}
```

# Connecting to Amazon Neptune databases using IAM authentication with Python
<a name="iam-auth-connecting-python"></a>

The `boto3` `neptunedata` client provides the simplest way to connect to an IAM-enabled Neptune database from Python. The client handles Signature Version 4 signing automatically, so you don't need to sign requests yourself.

## Prerequisites
<a name="iam-auth-connecting-python-prereqs"></a>
+ Python 3.x
+ The `boto3` library: `pip install boto3`
+ AWS credentials configured through any standard method (environment variables, AWS config file, instance profile, or Lambda execution role)
+ An IAM policy that allows `neptune-db:*` actions on your Neptune cluster

## Connecting with default credentials
<a name="iam-auth-connecting-python-default"></a>

This approach works when `boto3` can resolve credentials automatically, such as on Amazon Elastic Compute Cloud instances with instance profiles, in AWS Lambda functions, or with configured AWS profiles.

Replace the endpoint URL with your Neptune cluster endpoint.

**Gremlin and openCypher**

```
import boto3
from botocore.config import Config

cfg = Config(retries={"total_max_attempts": 1, "mode": "standard"}, read_timeout=None)

neptune = boto3.client('neptunedata', config=cfg,
    region_name='us-east-1',
    endpoint_url='https://your-neptune-endpoint:8182')

# Gremlin
resp = neptune.execute_gremlin_query(gremlinQuery='g.V().limit(1)')
print(resp['result'])

# openCypher
resp = neptune.execute_open_cypher_query(openCypherQuery='MATCH (n) RETURN n LIMIT 1')
print(resp['results'])
```

**SPARQL**

The `boto3` `neptunedata` client does not currently support SPARQL. To send SPARQL queries to an IAM-enabled Neptune database, sign requests manually by using Signature Version 4 with the `botocore` request-signing utilities and the `requests` library (`pip install boto3 requests`).

```
import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.session import Session

endpoint = 'https://your-neptune-endpoint:8182'
region = 'us-east-1'

query = 'SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 1'

request = AWSRequest(method='POST', url=f'{endpoint}/sparql/',
    data={'query': query})
SigV4Auth(Session().get_credentials(), 'neptune-db', region).add_auth(request)

resp = requests.post(f'{endpoint}/sparql/', headers=request.headers,
    data={'query': query})
print(resp.json())
```

**Note**  
This example uses `botocore.session.Session` to resolve AWS credentials automatically from environment variables, AWS config files, instance profiles, or Lambda execution roles. You don't need to set credentials explicitly.

## Using temporary credentials
<a name="iam-auth-connecting-python-temp-creds"></a>

For cross-account access, time-limited sessions, or as a security best practice to avoid long-lived credentials, use AWS STS to obtain temporary credentials and create a `boto3.Session`.

**Gremlin and openCypher**

```
import boto3
from botocore.config import Config

sts = boto3.client('sts')
creds = sts.assume_role(
    RoleArn='arn:aws:iam::123456789012:role/NeptuneRole',
    RoleSessionName='neptune-session'
)['Credentials']

session = boto3.Session(
    aws_access_key_id=creds['AccessKeyId'],
    aws_secret_access_key=creds['SecretAccessKey'],
    aws_session_token=creds['SessionToken'],
    region_name='us-east-1'
)

cfg = Config(retries={"total_max_attempts": 1, "mode": "standard"}, read_timeout=None)

neptune = session.client('neptunedata', config=cfg,
    endpoint_url='https://your-neptune-endpoint:8182')

# Gremlin
resp = neptune.execute_gremlin_query(gremlinQuery='g.V().limit(1)')
print(resp['result'])

# openCypher
resp = neptune.execute_open_cypher_query(openCypherQuery='MATCH (n) RETURN n LIMIT 1')
print(resp['results'])
```

**Note**  
Temporary credentials expire after a specified interval (the default is 1 hour) and are not automatically refreshed by the client. For long-running applications, use profile-based credentials or instance profiles instead.

**SPARQL**

Because the `boto3` `neptunedata` client does not currently support SPARQL, you must sign requests manually with the temporary credentials.

```
import boto3
import requests
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import ReadOnlyCredentials

sts = boto3.client('sts')
creds = sts.assume_role(
    RoleArn='arn:aws:iam::123456789012:role/NeptuneRole',
    RoleSessionName='neptune-session'
)['Credentials']

endpoint = 'https://your-neptune-endpoint:8182'
region = 'us-east-1'

query = 'SELECT ?s ?p ?o WHERE { ?s ?p ?o } LIMIT 1'

request = AWSRequest(method='POST', url=f'{endpoint}/sparql/',
    data={'query': query})
SigV4Auth(ReadOnlyCredentials(
    creds['AccessKeyId'], creds['SecretAccessKey'], creds['SessionToken']
), 'neptune-db', region).add_auth(request)

resp = requests.post(f'{endpoint}/sparql/', headers=request.headers,
    data={'query': query})
print(resp.json())
```

## Using with AWS Lambda
<a name="iam-auth-connecting-python-lambda"></a>

In Lambda, the execution role provides credentials automatically through `boto3`. The default credentials example works without modification.

For a complete Lambda example with connection management and retry logic, see [AWS Lambda function examples for Amazon Neptune](lambda-functions-examples.md).

# Connecting to Amazon Neptune databases using IAM authentication with Gremlin Python
<a name="gremlin-python-iam-auth"></a>

## Overview
<a name="gremlin-python-iam-auth-overview"></a>

 This guide demonstrates how to connect to an Amazon Neptune database with IAM authentication enabled using the Gremlin Python driver, with Signature Version 4 authentication and the AWS SDK for Python (Boto3). 

## Create a basic connection
<a name="gremlin-python-iam-auth-basic-connection"></a>

 Use the following code example as guidance on how to establish basic connection with IAM authentication using the Gremlin Python driver. 

```
from boto3 import Session
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest

from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection

def main():
    endpoint = 'your.cluster.endpoint.neptune.amazonaws.com'
    conn_string = 'wss://' + endpoint + ':8182/gremlin'
    default_region = 'us-east-1'
    service = 'neptune-db'

    credentials = Session().get_credentials()
    if credentials is None:
        raise Exception("No AWS credentials found")
    creds = credentials.get_frozen_credentials()
    # region set inside config profile or via AWS_DEFAULT_REGION environment variable will be loaded
    region = Session().region_name if Session().region_name else default_region

    request = AWSRequest(method='GET', url=conn_string, data=None)
    SigV4Auth(creds, service, region).add_auth(request)

    rc = DriverRemoteConnection(conn_string, 'g', headers=request.headers.items())
    g = traversal().with_remote(rc)

    # simple query to verify connection
    count = g.V().count().next()
    print('Vertex count: ' + str(count))

    # cleanup
    rc.close()

if __name__ == "__main__":
    main()
```

# Connecting to Amazon Neptune databases using IAM authentication with Gremlin JavaScript
<a name="gremlin-javascript-iam-auth"></a>

## Overview
<a name="gremlin-javascript-iam-auth-overview"></a>

 This guide demonstrates how to connect to an Amazon Neptune database with IAM authentication enabled using the Gremlin JavaScript driver, with Signature Version 4 authentication and the AWS SDK for Javascript v3. 

## Prerequisites
<a name="gremlin-javascript-iam-auth-prereqs"></a>
+  An Amazon Neptune cluster with IAM authentication enabled. 
+  Node 13 or later (refer to minimal versions for Gremlin JavaScript and [AWS SDK for Javascript v3](https://docs.aws.amazon.com//AWSJavaScriptSDK/v3/latest/introduction/#release-cadence)). 
+  AWS credentials configured (via environment variables, shared credentials file, or IAM role). 

## Create a basic connection
<a name="gremlin-javascript-iam-auth-basic-connection"></a>

 Use the following code example as guidance on how to establish a basic connection with IAM authentication using the Gremlin JavaScript driver. 

```
const { fromNodeProviderChain } = require('@aws-sdk/credential-providers');
const { getUrlAndHeaders } = require('gremlin-aws-sigv4/lib/utils');
const { loadConfig } = require("@smithy/node-config-provider");
const { NODE_REGION_CONFIG_FILE_OPTIONS, NODE_REGION_CONFIG_OPTIONS } = require("@smithy/config-resolver");

const gremlin = require('gremlin');
const DriverRemoteConnection = gremlin.driver.DriverRemoteConnection;
const traversal = gremlin.process.AnonymousTraversalSource.traversal;

const DEFAULT_REGION = 'us-east-1';

const getCredentials = async () => {
    try {
        // Loads the default credential provider chain
        return await fromNodeProviderChain();
    } catch (e) {
        console.error("No credentials found", e);
        throw e;
    }
};

(main = async () => {
    console.log('Starting');

    const credentials = await getCredentials();
    try {
        // region set inside config profile or via AWS_REGION environment variable will be loaded
        credentials['region'] = await loadConfig(NODE_REGION_CONFIG_OPTIONS, NODE_REGION_CONFIG_FILE_OPTIONS)();
    } catch (e) {
        credentials['region'] = DEFAULT_REGION
    }

    const connInfo = getUrlAndHeaders(
        'you.cluster.endpoint.neptune.amazonaws.com',
        '8182',
        credentials,
        '/gremlin',
        'wss');

    const dc = new DriverRemoteConnection(connInfo['url'], {headers: connInfo['headers']});
    const g = traversal().withRemote(dc);

    const query = g.V().limit(5).count();
    const count = await query.next();
    console.log("Vertex count: " + count.value);

    await dc.close();
})

main();
```

# Connecting to Amazon Neptune databases using IAM authentication with Gremlin Go
<a name="gremlin-go-iam-auth"></a>

## Overview
<a name="gremlin-go-iam-auth-overview"></a>

 This guide demonstrates how to connect to a Amazon Neptune database with IAM authentication enabled using the Gremlin Go driver, with Signature Version 4 authentication and the AWS SDK for GO v2. 

## Prerequisites
<a name="gremlin-go-iam-auth-prereqs"></a>
+  An Amazon Neptune cluster with IAM authentication enabled. 
+  Go 1.22 or later (refer to minimal supported versions for [ Gremlin Go](https://pkg.go.dev/github.com/apache/tinkerpop/gremlin-go/v3/driver) and [AWS SDK for Go v2](https://pkg.go.dev/github.com/aws/aws-sdk-go-v2)). 
+  AWS credentials configured (via environment variables, shared credentials file, or IAM role) 

## Create a basic connection
<a name="gremlin-go-iam-auth-basic-connection"></a>

 Use the following code example as guidance on how to establish a basic connection with IAM authentication using the Gremlin Go driver. 

```
package main

import (
	"context"
	"fmt"
	"github.com/aws/aws-sdk-go-v2/config"
	"net/http"
	"strings"
	"time"

	gremlingo "github.com/apache/tinkerpop/gremlin-go/v3/driver"
	v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)

const emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`

func main() {
	neptuneEndpoint := "you.cluster.endpoint.neptune.amazonaws.com"
	connString := "wss://" + neptuneEndpoint + ":8182/gremlin"
	service := "neptune-db"
	defaultRegion := "us-east-1"

	// Create request to sign
	req, err := http.NewRequest(http.MethodGet, connString, strings.NewReader(""))
	if err != nil {
		fmt.Println(err)
		return
	}

	// Loads the default config with default credentials provider
	// See https://github.com/aws/aws-sdk-go-v2 for additional docs on API usage
	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		fmt.Println(err)
		return
	}
	// Retrieve loaded credentials 
	cr, err := cfg.Credentials.Retrieve(context.TODO())
	if err != nil {
		fmt.Println(err)
		return
	}

	region := defaultRegion
	if cfg.Region != "" {
		// region set inside config profile, or via AWS_REGION or AWS_DEFAULT_REGION environment variable will be loaded
		region = cfg.Region
	}

	signer := v4.NewSigner()
	// Sign request
	err = signer.SignHTTP(context.TODO(), cr, req, emptyStringSHA256, service, "us-east-2", time.Now())
	if err != nil {
		fmt.Println(err)
		return
	}

	// Pass the signed request header into gremlingo.HeaderAuthInfo()
	driverRemoteConnection, err := gremlingo.NewDriverRemoteConnection(connString,
		func(settings *gremlingo.DriverRemoteConnectionSettings) {
			settings.TraversalSource = "g"
			settings.AuthInfo = gremlingo.HeaderAuthInfo(req.Header)
			// settings.TlsConfig = &tls.Config{InsecureSkipVerify: true} // Use this only if you're on a Mac running Go 1.18+ doing local dev. See https://github.com/golang/go/issues/51991
		})
	if err != nil {
		fmt.Println(err)
		return
	}

	// Cleanup
	defer driverRemoteConnection.Close()

	// Creating graph traversal
	g := gremlingo.Traversal_().WithRemote(driverRemoteConnection)

	// Query execution
	count, err := g.V().Limit(5).Count().Next()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Vertex count:", *count)
}
```

## Gremlin Go Dynamic Credential Refresh
<a name="gremlin-go-iam-auth-go-credential-refresh"></a>

 Gremlin Go has DynamicAuth which allows the injection of a function pointer to retrieve credentials and generate the header, which prevents header expiry with long-running connections. 

```
package main

import (
	"context"
	"crypto/tls"
	"fmt"
	"github.com/aws/aws-sdk-go-v2/config"
	"net/http"
	"strings"
	"time"

	gremlingo "github.com/apache/tinkerpop/gremlin-go/v3/driver"
	v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
)

const emptyStringSHA256 = `e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855`

func main() {
	neptuneEndpoint := "you.cluster.endpoint.neptune.amazonaws.com"
	connString := "wss://" + neptuneEndpoint + ":8182/gremlin"
	service := "neptune-db"
	defaultRegion := "us-east-1"

	//Create the request to sign
	req, err := http.NewRequest(http.MethodGet, connString, strings.NewReader(""))
	if err != nil {
		fmt.Println(err)
		return
	}

	// Loads the default config with default credentials provider
	// See https://github.com/aws/aws-sdk-go-v2 for additional docs on API usage
	cfg, err := config.LoadDefaultConfig(context.TODO())
	if err != nil {
		fmt.Println(err)
		return
	}

	region := defaultRegion
	if cfg.Region != "" {
		// region set inside config profile, or via AWS_REGION or AWS_DEFAULT_REGION environment variable will be loaded
		region = cfg.Region
	}
	
	signer := v4.NewSigner()

	// This is the function that will be used for dynamic refreseh of credentials and signed headers
	gen := func() gremlingo.AuthInfoProvider {
		// Retrieve loaded credentials 
		cr, err := cfg.Credentials.Retrieve(context.TODO())
		fmt.Println("AWS Credentials: ", cr)
		if err != nil {
			fmt.Println(err)
			return
		}
		// Sign request
		err = signer.SignHTTP(context.TODO(), cr, req, emptyStringSHA256, service, region, time.Now())
		if err != nil {
			fmt.Println(err)
			return
		}
		fmt.Println(req.Header)
		return gremlingo.HeaderAuthInfo(req.Header)
	}

	// Pass the function into gremlingo.NewDynamicAuth(), which will generate the AuthInfoProvider to pass into gremlingo.DriverRemoteConnectionSettings below
	auth := gremlingo.NewDynamicAuth(gen)

	driverRemoteConnection, err := gremlingo.NewDriverRemoteConnection(connString,
		func(settings *gremlingo.DriverRemoteConnectionSettings) {
			settings.TraversalSource = "g"
			settings.AuthInfo = auth
			// settings.TlsConfig = &tls.Config{InsecureSkipVerify: true} // Use this only if you're on a Mac running Go 1.18+ doing local dev. See https://github.com/golang/go/issues/51991

		})
	if err != nil {
		fmt.Println(err)
		return
	}

	// Cleanup
	defer driverRemoteConnection.Close()

	// Creating graph traversal
	g := gremlingo.Traversal_().WithRemote(driverRemoteConnection)

	// Query execution
	count, err := g.V().Limit(5).Count().Next()
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println("Vertex count:", *count)
}
```

# Connecting to Amazon Neptune databases using IAM authentication with Gremlin .NET
<a name="gremlin-dotnet-iam-auth"></a>

## Overview
<a name="gremlin-dotnet-iam-auth-overview"></a>

 This guide demonstrates how to connect to a Amazon Neptune database with IAM authentication enabled using the Gremlin .NET driver, with Signature Version 4 authentication and the AWS SDK for .NET v3. 

## Create a basic connection
<a name="gremlin-dotnet-iam-auth-basic-connection"></a>

 To connect with Gremlin .NET, use the `SigV4RequestSigner` source file from the custom library [ https://github.com/aws/amazon-neptune-gremlin-dotnet-sigv4](https://github.com/aws/amazon-neptune-gremlin-dotnet-sigv4). An example project set-up is located in [ https://github.com/aws/amazon-neptune-gremlin-dotnet-sigv4/tree/main/example](https://github.com/aws/amazon-neptune-gremlin-dotnet-sigv4/tree/main/example), and reflected below. 

Project File:

```
<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp8.0</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Compile Include="../src/SigV4RequestSigner.cs" Link="SigV4RequestSigner.cs" />
    <PackageReference Include="AWSSDK.Core" Version="3.7.402.24" />
    <PackageReference Include="gremlin.net" Version="3.7.3" />
  </ItemGroup>

</Project>
```

Example Program:

```
using System;
using System.Collections.Generic;
using System.Net.WebSockets;
using System.Linq;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using Gremlin.Net;
using Gremlin.Net.Driver;
using Gremlin.Net.Driver.Remote;
using Gremlin.Net.Process;
using Gremlin.Net.Process.Traversal;
using Gremlin.Net.Structure;
using static Gremlin.Net.Process.Traversal.AnonymousTraversalSource;
using static Gremlin.Net.Process.Traversal.__;
using static Gremlin.Net.Process.Traversal.P;
using static Gremlin.Net.Process.Traversal.Order;
using static Gremlin.Net.Process.Traversal.Operator;
using static Gremlin.Net.Process.Traversal.Pop;
using static Gremlin.Net.Process.Traversal.Scope;
using static Gremlin.Net.Process.Traversal.TextP;
using static Gremlin.Net.Process.Traversal.Column;
using static Gremlin.Net.Process.Traversal.Direction;
using static Gremlin.Net.Process.Traversal.T;
using Amazon.Runtime.CredentialManagement;
using Amazon.Runtime;
using Amazon;
using Amazon.Util;
using Amazon.Neptune.Gremlin.Driver;

namespace NeptuneExample
{
    class Program
    {
        static void Main(string[] args)
        {
            /*
                Include your Neptune endpoint and port below.
            */
            var neptune_host = "neptune-endpoint"; // ex: mycluster.cluster.us-east-1.neptune.amazonaws.com
            var neptune_port = 8182;

            var gremlinServer = new GremlinServer(neptune_host, neptune_port);
            var gremlinClient = new GremlinClient(gremlinServer, webSocketConfiguration: new SigV4RequestSigner().signRequest(neptune_host, neptune_port));
            var remoteConnection = new DriverRemoteConnection(gremlinClient);
            var g = Traversal().WithRemote(remoteConnection);

            /* Example code to pull the first 5 vertices in a graph. */
            Console.WriteLine("Get List of Node Labels:");
            Int32 limitValue = 5;
            var output = g.V().Limit<Vertex>(limitValue).ToList();
            foreach(var item in output) {
                Console.WriteLine(item);
            }
        }
    }
}
```

# Managing access to Amazon Neptune databases using IAM policies
<a name="security-iam-access-manage"></a>

[IAM policies](https://docs.aws.amazon.com/kms/latest/developerguide/iam-policies.html) are JSON objects that define permissions to use actions and resources.

You control access in AWS by creating policies and attaching them to AWS identities or resources. A policy defines permissions when associated with an identity or resource. AWS evaluates these policies when a principal makes a request. Most policies are stored in AWS as JSON documents. For more information about JSON policy documents, see [Overview of JSON policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies.html#access_policies-json) in the *IAM User Guide*.

Using policies, administrators specify who has access to what by defining which **principal** can perform **actions** on what **resources**, and under what **conditions**.

By default, users and roles have no permissions. An IAM administrator creates IAM policies and adds them to roles, which users can then assume. IAM policies define permissions regardless of the method used to perform the operation.

## Identity-Based Policies
<a name="security_iam_access-manage-id-based-policies"></a>

Identity-based policies are JSON permissions policy documents that you attach to an identity (user, group, or role). These policies control what actions identities can perform, on which resources, and under what conditions. To learn how to create an identity-based policy, see [Define custom IAM permissions with customer managed policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_create.html) in the *IAM User Guide*.

Identity-based policies can be *inline policies* (embedded directly into a single identity) or *managed policies* (standalone policies attached to multiple identities). To learn how to choose between managed and inline policies, see [Choose between managed policies and inline policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies-choosing-managed-or-inline.html) in the *IAM User Guide*.

## Using Service Control Policies (SCP) with AWS organizations
<a name="security_iam_access-manage-scp"></a>

Service control policies (SCPs) are JSON policies that specify the maximum permissions for an organization or organizational unit (OU) in [AWS Organizations](https://aws.amazon.com/organizations/). AWS Organizations is a service for grouping and centrally managing multiple AWS accounts that your business owns. If you enable all features in an organization, then you can apply service control policies (SCPs) to any or all of your accounts. The SCP limits permissions for entities in member accounts, including each AWS account root user. For more information about Organizations and SCPs, see [How SCPs work](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_about-scps.html) in the AWS Organizations User Guide.

Customers deploying Amazon Neptune in an AWS Account within an AWS Organization can leverage SCPs to control which accounts can use Neptune. To ensure access to Neptune within a member account, be sure to:
+  Allow access to `rds:*` and `neptune-db:*` for Neptune database operations. Refer to [Why are Amazon RDS permissions and resources required to use Neptune Database?](https://aws.amazon.com/neptune/faqs/) for details on why Amazon RDS permissions are needed for Neptune database. 
+  Allow access to `neptune-graph:*` for Neptune Analytics operations. 

## Permissions Required to Use the Amazon Neptune Console
<a name="security-iam-access-manage-console"></a>

For a user to work with the Amazon Neptune console, that user must have a minimum set of permissions. These permissions allow the user to describe the Neptune resources for their AWS account and to provide other related information, including Amazon EC2 security and network information.

If you create an IAM policy that is more restrictive than the minimum required permissions, the console won't function as intended for users with that IAM policy. To ensure that those users can still use the Neptune console, also attach the `NeptuneReadOnlyAccess` managed policy to the user, as described in [Using AWS managed policies to access Amazon Neptune databases](security-iam-access-managed-policies.md).

You don't need to allow minimum console permissions for users that are making calls only to the AWS CLI or the Amazon Neptune API.

## Attaching an IAM Policy to an IAM user
<a name="iam-auth-policy-attaching"></a>

To apply a managed or custom policy, you attach it to an IAM user. For a tutorial on this topic, see [Create and Attach Your First Customer Managed Policy](https://docs.aws.amazon.com/IAM/latest/UserGuide/tutorial_managed-policies.html) in the *IAM User Guide*.

As you work through the tutorial, you can use one of the policy examples shown in this section as a starting point and tailor it to your needs. At the end of the tutorial, you have an IAM user with an attached policy that can use the `neptune-db:*` action.

**Important**  
Changes to an IAM policy take up to 10 minutes to apply to the specified Neptune resources.
IAM policies applied to a Neptune DB cluster apply to all instances in that cluster.

## Using different kinds of IAM policies for controlling access to Neptune
<a name="iam-auth-policy"></a>

To provide access to Neptune administrative actions or to data in a Neptune DB cluster, you attach policies to an IAM user or role. For information about how to attach an IAM policy to a user, see [Attaching an IAM Policy to an IAM user](#iam-auth-policy-attaching). For information about attaching a policy to a role, see [Adding and Removing IAM Policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_manage-attach-detach.html) in the *IAM User Guide*.

For general access to Neptune, you can use one of Neptune's [managed policies](security-iam-access-managed-policies.md). For more restricted access, you can create your own custom policy using the [administrative actions](neptune-iam-admin-actions.md) and [resources](iam-admin-resources.md) that Neptune supports..

In a custom IAM policy, you can use two different kinds of policy statement that control different modes of access to a Neptune DB cluster:
+ [Administrative policy statements](iam-admin-policies.md)   –   Administrative policy statements provide access to the [Neptune management APIs](api.md) that you use to create, configure and manage a DB cluster and its instances.

  Because Neptune shares functionality with Amazon RDS, administrative actions, resources, and condition keys in Neptune policies use an `rds:` prefix by design.
+ [Data-access policy statements](iam-data-access-policies.md)   –   Data-access policy statements use [data-access actions](iam-dp-actions.md), [resources](iam-data-resources.md), and [condition keys](iam-data-condition-keys.md#iam-neptune-condition-keys) to control access the data that a DB cluster contains.

  Neptune data-access actions, resources and condition keys use a `neptune-db:` prefix.

## Using IAM condition context keys in Amazon Neptune
<a name="iam-using-condition-keys"></a>

You can specify conditions in an IAM policy statement that controls access to Neptune. The policy statement then takes effect only when the conditions are true.

For example, you might want a policy statement to take effect only after a specific date, or allows access only when a specific value is present in the request.

To express conditions, you use predefined condition keys in the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) element of a policy statement, together with [IAM condition policy operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html) such as equals or less than.

If you specify multiple `Condition` elements in a statement, or multiple keys in a single `Condition` element, AWS evaluates them using a logical `AND` operation. If you specify multiple values for a single condition key, AWS evaluates the condition using a logical `OR` operation. All of the conditions must be met before the statement's permissions are granted.

 You can also use placeholder variables when you specify conditions. For example, you can grant an IAM user permission to access a resource only if it is tagged with their IAM user name. For more information, see [IAM Policy Elements: Variables and Tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html) in the *IAM User Guide*.

The data type of a condition key determines which condition operators you can use to compare values in the request with the values in the policy statement. If you use a condition operator that is not compatible with that data type, the match always fails and the policy statement never applies.

Neptune supports different sets of condition keys for administrative policy statements than for data-access policy statements:
+ [Condition keys for administrative policy statements](iam-admin-condition-keys.md)
+ [Condition keys for data-access policy statements](iam-data-condition-keys.md#iam-neptune-condition-keys)

## Support for IAM policy and access-control features in Amazon Neptune
<a name="neptune-iam-policy-support"></a>

The following table shows what IAM features Neptune supports for administrative policy statements and data-access policy statements:


**IAM features you can use with Neptune**  

| IAM feature | Administrative | Data-access | 
| --- | --- | --- | 
| [Identity-based policies](#security_iam_access-manage-id-based-policies) | Yes | Yes | 
| [Resource-based policies](https://docs.aws.amazon.com/IAM/latest/UserGuide/access_policies_identity-vs-resource.html) | No | No | 
| [Policy actions](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_action.html) | Yes | Yes | 
| [Policy resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html) | Yes | Yes | 
| [Global condition keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) | Yes | (a subset) | 
| [Tag-based condition keys](iam-admin-condition-keys.md#iam-rds-tag-based-condition-keys) | Yes | No | 
| [Access Control Lists (ACLs)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/acls.html) | No | No | 
| [Service control policies (SCPs)](#security_iam_access-manage-scp) | Yes | Yes | 
| [Service linked roles](security-iam-service-linked-roles.md) | Yes | No | 

## IAM Policy Limitations
<a name="iam-policy-limits"></a>

Changes to an IAM policy take up to 10 minutes to apply to the specified Neptune resources.

IAM policies applied to a Neptune DB cluster apply to all instances in that cluster.

Neptune does not currently support cross-account access control at the data plane level. Cross-account access control is only supported when bulk-loading and by using role chaining. For more information, see [ Bulk load tutorial ](https://docs.aws.amazon.com//neptune/latest/userguide/bulk-load-tutorial-chain-roles.html#bulk-load-tutorial-chain-cross-account).

# Using AWS managed policies to access Amazon Neptune databases
<a name="security-iam-access-managed-policies"></a>

AWS addresses many common use cases by providing standalone IAM policies that are created and administered by AWS. Managed policies grant necessary permissions for common use cases so you can avoid having to investigate what permissions are needed. 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*.

The following AWS managed policies, which you can attach to users in your account, are for using Amazon Neptune management APIs:
+ **[NeptuneReadOnlyAccess](read-only-access-iam-managed-policy.md)** — Grants read-only access to all Neptune resources for both administrative and data-access purposes in the root AWS account.
+ **[NeptuneFullAccess](full-access-iam-managed-policy.md)** — Grants full access to all Neptune resources for both administrative and data-access purposes in the root AWS account. This is recommended if you need full Neptune access from the AWS CLI or SDK, but not for AWS Management Console access.
+ **[NeptuneConsoleFullAccess](console-full-access-iam-managed-policy.md)** — Grants full access in the root AWS account to all Neptune administrative actions and resources, but not to any data-access actions or resources. It also includes additional permissions to simplify Neptune access from the console, including limited IAM and Amazon EC2 (VPC) permissions.
+ **[NeptuneGraphReadOnlyAccess ](graph-read-only-access-iam-managed-policy.md)** — Provides read-only access to all Amazon Neptune Analytics resources along with read-only permissions for dependent services
+ **[AWSServiceRoleForNeptuneGraphPolicy](aws-service-role-for-neptune-graph-policy.md)** — Lets Neptune Analytics graphs to publish CloudWatch operational and usage metrics and logs.

Neptune IAM roles and policies grant some access to Amazon RDS resources, because Neptune shares operational technology with Amazon RDS for certain management features. This includes administrative API permissions, which is why Neptune administrative actions have an `rds:` prefix.

## Updates to Neptune AWS managed policies
<a name="neptune-managed-policy-updates"></a>

The following table tracks updates to Neptune managed policies starting from the time Neptune began tracking these changes:


| Policy | Description | Date | 
| --- | --- | --- | 
| AWS managed policies for Amazon Neptune - update to existing policies | The `NeptuneReadOnlyAcess` and `NeptuneFullAccess` managed policies now include `Sid` (statement ID) as an identifier in the policy statement. | 2024-01-22 | 
| [NeptuneGraphReadOnlyAccess](read-only-access-iam-managed-policy.md) (released) | Released to provide read-only access to Neptune Analytics graphs and resources. | 2023-11-29 | 
| [AWSServiceRoleForNeptuneGraphPolicy](aws-service-role-for-neptune-graph-policy.md) (released) | Released to allow Neptune Analytics graphs access to CloudWatch to publish operational and usage metrics and logs. See [Using service-linked roles (SLRs) in Neptune Analytics](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/nan-service-linked-roles.html). | 2023-11-29 | 
| [NeptuneConsoleFullAccess](console-full-access-iam-managed-policy.md) (added permissions) | Added permissions provide all access needed to interact with Neptune Analytics graphs. | 2023-11/29 | 
| [NeptuneFullAccess](full-access-iam-managed-policy.md) (added permissions) | Added data-access permissions, and permissions for new global database APIs. | 2022-07-28 | 
| [NeptuneConsoleFullAccess](console-full-access-iam-managed-policy.md) (added permissions) | Added permissions for new global database APIs. | 2022-07-21 | 
| Neptune started tracking changes | Neptune began tracking changes to its AWS managed policies. | 2022-07-21 | 

# Granting `NeptuneReadOnlyAccess` to Amazon Neptune databases using AWS managed policy
<a name="read-only-access-iam-managed-policy"></a>

The [NeptuneReadOnlyAccess](https://console.aws.amazon.com/iam/home#policies/NeptuneReadOnlyAccess) managed policy below grants read-only access to all Neptune actions and resources for both administrative and data-access purposes.

**Note**  
This policy was updated on 2022-07-21 to include read-only data-access permissions as well as read-only administrative permissions and to include permissions for global database actions.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowReadOnlyPermissionsForRDS",
            "Effect": "Allow",
            "Action": [
                "rds:DescribeAccountAttributes",
                "rds:DescribeCertificates",
                "rds:DescribeDBClusterParameterGroups",
                "rds:DescribeDBClusterParameters",
                "rds:DescribeDBClusterSnapshotAttributes",
                "rds:DescribeDBClusterSnapshots",
                "rds:DescribeDBClusters",
                "rds:DescribeDBEngineVersions",
                "rds:DescribeDBInstances",
                "rds:DescribeDBLogFiles",
                "rds:DescribeDBParameterGroups",
                "rds:DescribeDBParameters",
                "rds:DescribeDBSubnetGroups",
                "rds:DescribeEventCategories",
                "rds:DescribeEventSubscriptions",
                "rds:DescribeEvents",
                "rds:DescribeGlobalClusters",
                "rds:DescribeOrderableDBInstanceOptions",
                "rds:DescribePendingMaintenanceActions",
                "rds:DownloadDBLogFilePortion",
                "rds:ListTagsForResource"
            ],
            "Resource": "*"
        },
        {
            "Sid": "AllowReadOnlyPermissionsForCloudwatch",
            "Effect": "Allow",
            "Action": [
                "cloudwatch:GetMetricStatistics",
                "cloudwatch:ListMetrics"
            ],
            "Resource": "*"
        },
        {
            "Sid": "AllowReadOnlyPermissionsForEC2",
            "Effect": "Allow",
            "Action": [
                "ec2:DescribeAccountAttributes",
                "ec2:DescribeAvailabilityZones",
                "ec2:DescribeInternetGateways",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSubnets",
                "ec2:DescribeVpcAttribute",
                "ec2:DescribeVpcs"
            ],
            "Resource": "*"
        },
        {
            "Sid": "AllowReadOnlyPermissionsForKMS",
            "Effect": "Allow",
            "Action": [
                "kms:ListKeys",
                "kms:ListRetirableGrants",
                "kms:ListAliases",
                "kms:ListKeyPolicies"
            ],
            "Resource": "*"
        },
        {
            "Sid": "AllowReadOnlyPermissionsForLogs",
            "Effect": "Allow",
            "Action": [
                "logs:DescribeLogStreams",
                "logs:GetLogEvents"
            ],
            "Resource": [
                "arn:aws:logs:*:*:log-group:/aws/rds/*:log-stream:*",
                "arn:aws:logs:*:*:log-group:/aws/neptune/*:log-stream:*"
            ]
        },
        {
            "Sid": "AllowReadOnlyPermissionsForNeptuneDB",
            "Effect": "Allow",
            "Action": [
                "neptune-db:Read*",
                "neptune-db:Get*",
                "neptune-db:List*"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

------

# Granting `NeptuneFullAccess` to Amazon Neptune databases using AWS managed policy
<a name="full-access-iam-managed-policy"></a>

The [NeptuneFullAccess](https://console.aws.amazon.com/iam/home#policies/NeptuneFullAccess) managed policy below grants full access to all Neptune actions and resources for both administrative and data-access purposes. It is recommended if you need full access from the AWS CLI or from an SDK, but not from the AWS Management Console.

**Note**  
This policy was updated on 2022-07-21 to include full data-access permissions as well as full administrative permissions and to include permissions for global database actions.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowNeptuneCreate",
            "Effect": "Allow",
            "Action": [
                "rds:CreateDBCluster",
                "rds:CreateDBInstance"
            ],
            "Resource": [
                "arn:aws:rds:*:*:*"
            ],
            "Condition": {
                "StringEquals": {
                    "rds:DatabaseEngine": [
                        "graphdb",
                        "neptune"
                    ]
                }
            }
        },
        {
            "Sid": "AllowManagementPermissionsForRDS",
            "Effect": "Allow",
            "Action": [
                "rds:AddRoleToDBCluster",
                "rds:AddSourceIdentifierToSubscription",
                "rds:AddTagsToResource",
                "rds:ApplyPendingMaintenanceAction",
                "rds:CopyDBClusterParameterGroup",
                "rds:CopyDBClusterSnapshot",
                "rds:CopyDBParameterGroup",
                "rds:CreateDBClusterEndpoint",
                "rds:CreateDBClusterParameterGroup",
                "rds:CreateDBClusterSnapshot",
                "rds:CreateDBParameterGroup",
                "rds:CreateDBSubnetGroup",
                "rds:CreateEventSubscription",
                "rds:CreateGlobalCluster",
                "rds:DeleteDBCluster",
                "rds:DeleteDBClusterEndpoint",
                "rds:DeleteDBClusterParameterGroup",
                "rds:DeleteDBClusterSnapshot",
                "rds:DeleteDBInstance",
                "rds:DeleteDBParameterGroup",
                "rds:DeleteDBSubnetGroup",
                "rds:DeleteEventSubscription",
                "rds:DeleteGlobalCluster",
                "rds:DescribeDBClusterEndpoints",
                "rds:DescribeAccountAttributes",
                "rds:DescribeCertificates",
                "rds:DescribeDBClusterParameterGroups",
                "rds:DescribeDBClusterParameters",
                "rds:DescribeDBClusterSnapshotAttributes",
                "rds:DescribeDBClusterSnapshots",
                "rds:DescribeDBClusters",
                "rds:DescribeDBEngineVersions",
                "rds:DescribeDBInstances",
                "rds:DescribeDBLogFiles",
                "rds:DescribeDBParameterGroups",
                "rds:DescribeDBParameters",
                "rds:DescribeDBSecurityGroups",
                "rds:DescribeDBSubnetGroups",
                "rds:DescribeEngineDefaultClusterParameters",
                "rds:DescribeEngineDefaultParameters",
                "rds:DescribeEventCategories",
                "rds:DescribeEventSubscriptions",
                "rds:DescribeEvents",
                "rds:DescribeGlobalClusters",
                "rds:DescribeOptionGroups",
                "rds:DescribeOrderableDBInstanceOptions",
                "rds:DescribePendingMaintenanceActions",
                "rds:DescribeValidDBInstanceModifications",
                "rds:DownloadDBLogFilePortion",
                "rds:FailoverDBCluster",
                "rds:FailoverGlobalCluster",
                "rds:ListTagsForResource",
                "rds:ModifyDBCluster",
                "rds:ModifyDBClusterEndpoint",
                "rds:ModifyDBClusterParameterGroup",
                "rds:ModifyDBClusterSnapshotAttribute",
                "rds:ModifyDBInstance",
                "rds:ModifyDBParameterGroup",
                "rds:ModifyDBSubnetGroup",
                "rds:ModifyEventSubscription",
                "rds:ModifyGlobalCluster",
                "rds:PromoteReadReplicaDBCluster",
                "rds:RebootDBInstance",
                "rds:RemoveFromGlobalCluster",
                "rds:RemoveRoleFromDBCluster",
                "rds:RemoveSourceIdentifierFromSubscription",
                "rds:RemoveTagsFromResource",
                "rds:ResetDBClusterParameterGroup",
                "rds:ResetDBParameterGroup",
                "rds:RestoreDBClusterFromSnapshot",
                "rds:RestoreDBClusterToPointInTime",
                "rds:StartDBCluster",
                "rds:StopDBCluster"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Sid": "AllowOtherDepedentPermissions",
            "Effect": "Allow",
            "Action": [
                "cloudwatch:GetMetricStatistics",
                "cloudwatch:ListMetrics",
                "ec2:DescribeAccountAttributes",
                "ec2:DescribeAvailabilityZones",
                "ec2:DescribeSecurityGroups",
                "ec2:DescribeSubnets",
                "ec2:DescribeVpcAttribute",
                "ec2:DescribeVpcs",
                "kms:ListAliases",
                "kms:ListKeyPolicies",
                "kms:ListKeys",
                "kms:ListRetirableGrants",
                "logs:DescribeLogStreams",
                "logs:GetLogEvents",
                "sns:ListSubscriptions",
                "sns:ListTopics",
                "sns:Publish"
            ],
            "Resource": [
                "*"
            ]
        },
        {
            "Sid": "AllowPassRoleForNeptune",
            "Effect": "Allow",
            "Action": "iam:PassRole",
            "Resource": "*",
            "Condition": {
                "StringEquals": {
                    "iam:passedToService": "rds.amazonaws.com"
                }
            }
        },
        {
            "Sid": "AllowCreateSLRForNeptune",
            "Effect": "Allow",
            "Action": "iam:CreateServiceLinkedRole",
            "Resource": "arn:aws:iam::*:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS",
            "Condition": {
                "StringLike": {
                    "iam:AWSServiceName": "rds.amazonaws.com"
                }
            }
        },
        {
            "Sid": "AllowDataAccessForNeptune",
            "Effect": "Allow",
            "Action": [
                "neptune-db:*"
            ],
            "Resource": [
                "*"
            ]
        }
    ]
}
```

------

# Granting `NeptuneConsoleFullAccess` using AWS managed policy
<a name="console-full-access-iam-managed-policy"></a>

The [NeptuneConsoleFullAccess](https://console.aws.amazon.com/iam/home#policies/NeptuneConsoleFullAccess) managed policy below grants full access to all Neptune actions and resources for administrative purposes, but not for data-access purposes. It also includes additional permissions to simplify Neptune access from the console, including limited IAM and Amazon EC2 (VPC) permissions.

**Note**  
This policy was updated on 2023-11-29 to include permissions needed to interact with Neptune Analytics graphs.  
It was updated on 2022-07-21 to include permissions for global database actions.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowNeptuneCreate",
      "Effect": "Allow",
      "Action": [
        "rds:CreateDBCluster",
        "rds:CreateDBInstance"
      ],
      "Resource": [
        "arn:aws:rds:*:*:*"
      ],
      "Condition": {
        "StringEquals": {
          "rds:DatabaseEngine": [
            "graphdb",
            "neptune"
          ]
        }
      }
    },
    {
      "Sid": "AllowManagementPermissionsForRDS",
      "Action": [
        "rds:AddRoleToDBCluster",
        "rds:AddSourceIdentifierToSubscription",
        "rds:AddTagsToResource",
        "rds:ApplyPendingMaintenanceAction",
        "rds:CopyDBClusterParameterGroup",
        "rds:CopyDBClusterSnapshot",
        "rds:CopyDBParameterGroup",
        "rds:CreateDBClusterParameterGroup",
        "rds:CreateDBClusterSnapshot",
        "rds:CreateDBParameterGroup",
        "rds:CreateDBSubnetGroup",
        "rds:CreateEventSubscription",
        "rds:DeleteDBCluster",
        "rds:DeleteDBClusterParameterGroup",
        "rds:DeleteDBClusterSnapshot",
        "rds:DeleteDBInstance",
        "rds:DeleteDBParameterGroup",
        "rds:DeleteDBSubnetGroup",
        "rds:DeleteEventSubscription",
        "rds:DescribeAccountAttributes",
        "rds:DescribeCertificates",
        "rds:DescribeDBClusterParameterGroups",
        "rds:DescribeDBClusterParameters",
        "rds:DescribeDBClusterSnapshotAttributes",
        "rds:DescribeDBClusterSnapshots",
        "rds:DescribeDBClusters",
        "rds:DescribeDBEngineVersions",
        "rds:DescribeDBInstances",
        "rds:DescribeDBLogFiles",
        "rds:DescribeDBParameterGroups",
        "rds:DescribeDBParameters",
        "rds:DescribeDBSecurityGroups",
        "rds:DescribeDBSubnetGroups",
        "rds:DescribeEngineDefaultClusterParameters",
        "rds:DescribeEngineDefaultParameters",
        "rds:DescribeEventCategories",
        "rds:DescribeEventSubscriptions",
        "rds:DescribeEvents",
        "rds:DescribeOptionGroups",
        "rds:DescribeOrderableDBInstanceOptions",
        "rds:DescribePendingMaintenanceActions",
        "rds:DescribeValidDBInstanceModifications",
        "rds:DownloadDBLogFilePortion",
        "rds:FailoverDBCluster",
        "rds:ListTagsForResource",
        "rds:ModifyDBCluster",
        "rds:ModifyDBClusterParameterGroup",
        "rds:ModifyDBClusterSnapshotAttribute",
        "rds:ModifyDBInstance",
        "rds:ModifyDBParameterGroup",
        "rds:ModifyDBSubnetGroup",
        "rds:ModifyEventSubscription",
        "rds:PromoteReadReplicaDBCluster",
        "rds:RebootDBInstance",
        "rds:RemoveRoleFromDBCluster",
        "rds:RemoveSourceIdentifierFromSubscription",
        "rds:RemoveTagsFromResource",
        "rds:ResetDBClusterParameterGroup",
        "rds:ResetDBParameterGroup",
        "rds:RestoreDBClusterFromSnapshot",
        "rds:RestoreDBClusterToPointInTime"
      ],
      "Effect": "Allow",
      "Resource": [
        "*"
      ]
    },
    {
      "Sid": "AllowOtherDepedentPermissions",
      "Action": [
        "cloudwatch:GetMetricStatistics",
        "cloudwatch:ListMetrics",
        "ec2:AllocateAddress",
        "ec2:AssignIpv6Addresses",
        "ec2:AssignPrivateIpAddresses",
        "ec2:AssociateAddress",
        "ec2:AssociateRouteTable",
        "ec2:AssociateSubnetCidrBlock",
        "ec2:AssociateVpcCidrBlock",
        "ec2:AttachInternetGateway",
        "ec2:AttachNetworkInterface",
        "ec2:CreateCustomerGateway",
        "ec2:CreateDefaultSubnet",
        "ec2:CreateDefaultVpc",
        "ec2:CreateInternetGateway",
        "ec2:CreateNatGateway",
        "ec2:CreateNetworkInterface",
        "ec2:CreateRoute",
        "ec2:CreateRouteTable",
        "ec2:CreateSecurityGroup",
        "ec2:CreateSubnet",
        "ec2:CreateVpc",
        "ec2:CreateVpcEndpoint",
        "ec2:CreateVpcEndpoint",
        "ec2:DescribeAccountAttributes",
        "ec2:DescribeAccountAttributes",
        "ec2:DescribeAddresses",
        "ec2:DescribeAvailabilityZones",
        "ec2:DescribeAvailabilityZones",
        "ec2:DescribeCustomerGateways",
        "ec2:DescribeInstances",
        "ec2:DescribeNatGateways",
        "ec2:DescribeNetworkInterfaces",
        "ec2:DescribePrefixLists",
        "ec2:DescribeRouteTables",
        "ec2:DescribeSecurityGroupReferences",
        "ec2:DescribeSecurityGroups",
        "ec2:DescribeSecurityGroups",
        "ec2:DescribeSubnets",
        "ec2:DescribeSubnets",
        "ec2:DescribeVpcAttribute",
        "ec2:DescribeVpcAttribute",
        "ec2:DescribeVpcEndpoints",
        "ec2:DescribeVpcs",
        "ec2:DescribeVpcs",
        "ec2:ModifyNetworkInterfaceAttribute",
        "ec2:ModifySubnetAttribute",
        "ec2:ModifyVpcAttribute",
        "ec2:ModifyVpcEndpoint",
        "iam:ListRoles",
        "kms:ListAliases",
        "kms:ListKeyPolicies",
        "kms:ListKeys",
        "kms:ListRetirableGrants",
        "logs:DescribeLogStreams",
        "logs:GetLogEvents",
        "sns:ListSubscriptions",
        "sns:ListTopics",
        "sns:Publish"
      ],
      "Effect": "Allow",
      "Resource": [
        "*"
      ]
    },
    {
      "Sid": "AllowPassRoleForNeptune",
      "Action": "iam:PassRole",
      "Effect": "Allow",
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "iam:passedToService": "rds.amazonaws.com"
        }
      }
    },
    {
      "Sid": "AllowCreateSLRForNeptune",
      "Action": "iam:CreateServiceLinkedRole",
      "Effect": "Allow",
      "Resource": "arn:aws:iam::*:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS",
      "Condition": {
        "StringLike": {
          "iam:AWSServiceName": "rds.amazonaws.com"
        }
      }
    },
    {
      "Sid": "AllowManagementPermissionsForNeptuneAnalytics",
      "Effect": "Allow",
      "Action": [
        "neptune-graph:CreateGraph",
        "neptune-graph:DeleteGraph",
        "neptune-graph:GetGraph",
        "neptune-graph:ListGraphs",
        "neptune-graph:UpdateGraph",
        "neptune-graph:ResetGraph",
        "neptune-graph:CreateGraphSnapshot",
        "neptune-graph:DeleteGraphSnapshot",
        "neptune-graph:GetGraphSnapshot",
        "neptune-graph:ListGraphSnapshots",
        "neptune-graph:RestoreGraphFromSnapshot",
        "neptune-graph:CreatePrivateGraphEndpoint",
        "neptune-graph:GetPrivateGraphEndpoint",
        "neptune-graph:ListPrivateGraphEndpoints",
        "neptune-graph:DeletePrivateGraphEndpoint",
        "neptune-graph:CreateGraphUsingImportTask",
        "neptune-graph:GetImportTask",
        "neptune-graph:ListImportTasks",
        "neptune-graph:CancelImportTask"
      ],
      "Resource": [
        "arn:aws:neptune-graph:*:*:*"
      ]
    },
    {
      "Sid": "AllowPassRoleForNeptuneAnalytics",
      "Effect": "Allow",
      "Action": "iam:PassRole",
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "iam:passedToService": "neptune-graph.amazonaws.com"
        }
      }
    },
    {
      "Sid": "AllowCreateSLRForNeptuneAnalytics",
      "Effect": "Allow",
      "Action": "iam:CreateServiceLinkedRole",
      "Resource": "arn:aws:iam::*:role/aws-service-role/neptune-graph.amazonaws.com/AWSServiceRoleForNeptuneGraph",
      "Condition": {
        "StringLike": {
          "iam:AWSServiceName": "neptune-graph.amazonaws.com"
        }
      }
    }
  ]
}
```

------

# Granting `NeptuneGraphReadOnlyAccess` using AWS managed policy
<a name="graph-read-only-access-iam-managed-policy"></a>

The [NeptuneGraphReadOnlyAccess](https://console.aws.amazon.com/iam/home#policies/NeptuneGraphReadOnlyAccess) managed policy below provides read only access to all Amazon Neptune Analytics resources along with read only permissions for dependent services.

This policy includes permissions to do the following:
+ **For Amazon EC2** – Retrieve information about VPCs, subnets, security groups and availability zones.
+ **For AWS KMS** – Retrieve information about KMS keys and aliases.
+ **For CloudWatch** – Retrieve information about CloudWatch metrics.
+ **For CloudWatch Logs** – Retrieve information about CloudWatch log streams and events.

**Note**  
This policy was released on 2023-11-29.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowReadOnlyPermissionsForNeptuneGraph",
      "Effect": "Allow",
      "Action": [
        "neptune-graph:Get*",
        "neptune-graph:List*",
        "neptune-graph:Read*"
      ],
      "Resource": "*"
    },
    {
      "Sid": "AllowReadOnlyPermissionsForEC2",
      "Effect": "Allow",
      "Action": [
        "ec2:DescribeVpcEndpoints",
        "ec2:DescribeVpcAttribute",
        "ec2:DescribeSecurityGroups",
        "ec2:DescribeSubnets",
        "ec2:DescribeVpcs",
        "ec2:DescribeAvailabilityZones"
      ],
      "Resource": "*"
    },
    {
      "Sid": "AllowReadOnlyPermissionsForKMS",
      "Effect": "Allow",
      "Action": [
        "kms:ListKeys",
        "kms:ListAliases"
      ],
      "Resource": "*"
    },
    {
      "Sid": "AllowReadOnlyPermissionsForCloudwatch",
      "Effect": "Allow",
      "Action": [
        "cloudwatch:GetMetricData",
        "cloudwatch:ListMetrics",
        "cloudwatch:GetMetricStatistics"
      ],
      "Resource": "*"
    },
    {
      "Sid": "AllowReadOnlyPermissionsForLogs",
      "Effect": "Allow",
      "Action": [
        "logs:DescribeLogStreams",
        "logs:GetLogEvents"
      ],
      "Resource": [
        "arn:aws:logs:*:*:log-group:/aws/neptune/*:log-stream:*"
      ]
    }
  ]
}
```

------

# Granting access to Neptune graph using `AWSServiceRoleForNeptuneGraphPolicy`
<a name="aws-service-role-for-neptune-graph-policy"></a>

The [AWSServiceRoleForNeptuneGraphPolicy](https://console.aws.amazon.com/iam/home#policies/AWSServiceRoleForNeptuneGraphPolicy) managed policy below gives graphs access to CloudWatch to publish operational and usage metrics and logs. See [nan-service-linked-roles](https://docs.aws.amazon.com/neptune-analytics/latest/userguide/nan-service-linked-roles.html).

**Note**  
This policy was released on 2023-11-29.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "GraphMetrics",
      "Effect": "Allow",
      "Action": [
        "cloudwatch:PutMetricData"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "cloudwatch:namespace": [
            "AWS/Neptune",
            "AWS/Usage"
          ]
        }
      }
    },
    {
      "Sid": "GraphLogGroup",
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogGroup"
      ],
      "Resource": [
        "arn:aws:logs:*:*:log-group:/aws/neptune/*"
      ],
      "Condition": {
        "StringEquals": {
          "aws:ResourceAccount": "${aws:PrincipalAccount}"
        }
      }
    },
    {
      "Sid": "GraphLogEvents",
      "Effect": "Allow",
      "Action": [
        "logs:CreateLogStream",
        "logs:PutLogEvents",
        "logs:DescribeLogStreams"
      ],
      "Resource": [
        "arn:aws:logs:*:*:log-group:/aws/neptune/*:log-stream:*"
      ],
      "Condition": {
        "StringEquals": {
          "aws:ResourceAccount": "${aws:PrincipalAccount}"
        }
      }
    }
  ]
}
```

------



# Customizing access to Amazon Neptune resources using IAM condition context keys
<a name="iam-condition-keys"></a>

You can specify conditions in IAM policies that control access to Neptune management actions and resources. The policy statement then takes effect only when the conditions are true.

For example, you might want a policy statement to take effect only after a specific date, or allow access only when a specific value is present in the API request.

To express conditions, you use predefined condition keys in the [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition.html) element of a policy statement, together with [IAM condition policy operators](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_condition_operators.html) such as equals or less than.

If you specify multiple `Condition` elements in a statement, or multiple keys in a single `Condition` element, AWS evaluates them using a logical `AND` operation. If you specify multiple values for a single condition key, AWS evaluates the condition using a logical `OR` operation. All of the conditions must be met before the statement's permissions are granted.

 You can also use placeholder variables when you specify conditions. For example, you can grant an IAM user permission to access a resource only if it is tagged with their IAM user name. For more information, see [IAM Policy Elements: Variables and Tags](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_variables.html) in the *IAM User Guide*.

The data type of a condition key determines which condition operators you can use to compare values in the request with the values in the policy statement. If you use a condition operator that is not compatible with that data type, the match always fails and the policy statement never applies. 

**IAM condition keys for Neptune administrative policy statements**
+ [Global condition keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html)   –   You can use most AWS global condition keys in Neptune administrative policy statements.
+ [Service-specific condition keys](iam-admin-condition-keys.md)   –   These are keys that are defined for specific AWS services. The ones that Neptune supports for administrative policy statements are listed in [IAM condition keys for administering Amazon Neptune](iam-admin-condition-keys.md).

**IAM condition keys for Neptune data-access policy statements**
+ [Global condition keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html)   –   The subset of these keys that Neptune supports in data-access policy statements is listed in [AWS global condition context keys supported by Neptune in data-access policy statements](iam-data-condition-keys.md#iam-data-global-condition-keys).
+ Service-specific condition keys that Neptune defines for data-access policy statements are listed in [Condition Keys](iam-data-condition-keys.md).

# Creating custom IAM policy statements to administer Amazon Neptune
<a name="iam-admin-policies"></a>

Administrative policy statements let you control what an IAM user can do to manage a Neptune database.

A Neptune administrative policy statement grants access to one or more [administrative actions](neptune-iam-admin-actions.md) and [administrative resources](iam-admin-resources.md) that Neptune supports. You can also use [Condition Keys](iam-admin-condition-keys.md) to make the administrative permissions more specific.

**Note**  
Because Neptune shares functionality with Amazon RDS, administrative actions, resources, and service-specific condition keys in administrative policy statements use an `rds:` prefix by design.

**Topics**
+ [IAM actions for administering Amazon Neptune](neptune-iam-admin-actions.md)
+ [IAM resource types for administering Amazon Neptune](iam-admin-resources.md)
+ [IAM condition keys for administering Amazon Neptune](iam-admin-condition-keys.md)
+ [Creating IAM administrative policy statements for Amazon Neptune](iam-admin-policy-examples.md)

# IAM actions for administering Amazon Neptune
<a name="neptune-iam-admin-actions"></a>

You can use the administrative actions listed below in the `Action` element of an IAM policy statement to control access to the [Neptune management APIs](api.md). When you use an action in a policy, you usually allow or deny access to the API operation or CLI command with the same name. However, in some cases, a single action controls access to more than one operation. Alternatively, some operations require several different actions.

The `Resource type` field in the list below indicates whether each action supports resource-level permissions. If there is no value in this field, you must specify all resources ("\$1") in the `Resource` element of your policy statement. If the column includes a resource type, then you can specify a resource ARN of that type in a statement with that action. Neptune administrative resource types are listed on [this page](iam-admin-resources.md).

Required resources are indicated in the list below with an asterisk (\$1). If you specify a resource-level permission ARN in a statement using this action, then it must be of this type. Some actions support multiple resource types. If a resource types is optional (in other words, is not marked with an asterisk), then you do not have to include it.

For more information about the fields listed here, see [action table](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_actions-resources-contextkeys.html#actions_table) in the [IAM User Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/).

## rds:AddRoleToDBCluster
<a name="neptune-iam-admin-actions-AddRoleToDBCluster"></a>

`AddRoleToDBCluster` associates an IAM role with a Neptune DB cluster.

*Access level:* `Write`.

*Dependent actions:* `iam:PassRole`.

*Resource type:* [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).

## rds:AddSourceIdentifierToSubscription
<a name="neptune-iam-admin-actions-AddSourceIdentifierToSubscription"></a>

`AddSourceIdentifierToSubscription` adds a source identifier to an existing Neptune event notification subscription.

*Access level:* `Write`.

*Resource type:* [es](iam-admin-resources.md#neptune-es-resource) (required).

## rds:AddTagsToResource
<a name="neptune-iam-admin-actions-AddTagsToResource"></a>

`AddTagsToResource` associates an IAM role with a Neptune DB cluster.

*Access level:* `Write`.

*Resource types:*
+ [db](iam-admin-resources.md#neptune-db-resource)
+ [es](iam-admin-resources.md#neptune-es-resource)
+ [pg](iam-admin-resources.md#neptune-pg-resource)
+ [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource)
+ [subgrp](iam-admin-resources.md#neptune-subgrp-resource)

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:ApplyPendingMaintenanceAction
<a name="neptune-iam-admin-actions-ApplyPendingMaintenanceAction"></a>

`ApplyPendingMaintenanceAction` applies a pending maintenance action to a resource.

*Access level:* `Write`.

*Resource type:* [db](iam-admin-resources.md#neptune-db-resource) (required).

## rds:CopyDBClusterParameterGroup
<a name="neptune-iam-admin-actions-CopyDBClusterParameterGroup"></a>

`CopyDBClusterParameterGroup` copies the specified DB cluster parameter group.

*Access level:* `Write`.

*Resource type:* [cluster-pg](iam-admin-resources.md#neptune-cluster-pg-resource) (required).

## rds:CopyDBClusterSnapshot
<a name="neptune-iam-admin-actions-CopyDBClusterSnapshot"></a>

`CopyDBClusterSnapshot` copies a snapshot of a DB cluster.

*Access level:* `Write`.

*Resource type:* [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource) (required).

## rds:CopyDBParameterGroup
<a name="neptune-iam-admin-actions-CopyDBParameterGroup"></a>

`CopyDBParameterGroup` copies the specified DB parameter group.

*Access level:* `Write`.

*Resource type:* [pg](iam-admin-resources.md#neptune-pg-resource) (required).

## rds:CreateDBCluster
<a name="neptune-iam-admin-actions-CreateDBCluster"></a>

`CreateDBCluster` creates a new Neptune DB cluster.

*Access level:* `Tagging`.

*Dependent actions:* `iam:PassRole`.

*Resource types:*
+ [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).
+ [cluster-pg](iam-admin-resources.md#neptune-cluster-pg-resource) (required).
+ [subgrp](iam-admin-resources.md#neptune-subgrp-resource) (required).

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)
+ [neptune-rds\$1DatabaseEngine](iam-admin-condition-keys.md#admin-rds_DatabaseEngine)

## rds:CreateDBClusterParameterGroup
<a name="neptune-iam-admin-actions-CreateDBClusterParameterGroup"></a>

`CreateDBClusterParameterGroup` creates a new DB cluster parameter group.

*Access level:* `Tagging`.

*Resource type:* [cluster-pg](iam-admin-resources.md#neptune-cluster-pg-resource) (required).

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:CreateDBClusterSnapshot
<a name="neptune-iam-admin-actions-CreateDBClusterSnapshot"></a>

`CreateDBClusterSnapshot` creates a snapshot of a DB cluster.

*Access level:* `Tagging`.

*Resource types:*
+ [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).
+ [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource) (required).

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:CreateDBInstance
<a name="neptune-iam-admin-actions-CreateDBInstance"></a>

`CreateDBInstance` creates a new DB instance.

*Access level:* `Tagging`.

*Dependent actions:* `iam:PassRole`.

*Resource types:*
+ [db](iam-admin-resources.md#neptune-db-resource) (required).
+ [pg](iam-admin-resources.md#neptune-pg-resource) (required).
+ [subgrp](iam-admin-resources.md#neptune-subgrp-resource) (required).

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:CreateDBParameterGroup
<a name="neptune-iam-admin-actions-CreateDBParameterGroup"></a>

`CreateDBParameterGroup` creates a new DB parameter group.

*Access level:* `Tagging`.

*Resource type:* [pg](iam-admin-resources.md#neptune-pg-resource) (required).

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:CreateDBSubnetGroup
<a name="neptune-iam-admin-actions-CreateDBSubnetGroup"></a>

`CreateDBSubnetGroup` creates a new DB subnet group.

*Access level:* `Tagging`.

*Resource type:* [subgrp](iam-admin-resources.md#neptune-subgrp-resource) (required).

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:CreateEventSubscription
<a name="neptune-iam-admin-actions-CreateEventSubscription"></a>

`CreateEventSubscription` creates a Neptune event notification subscription.

*Access level:* `Tagging`.

*Resource type:* [es](iam-admin-resources.md#neptune-es-resource) (required).

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:DeleteDBCluster
<a name="neptune-iam-admin-actions-DeleteDBCluster"></a>

`DeleteDBCluster` deletes an existing Neptune DB cluster.

*Access level:* `Write`.

*Resource types:*
+ [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).
+ [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource) (required).

## rds:DeleteDBClusterParameterGroup
<a name="neptune-iam-admin-actions-DeleteDBClusterParameterGroup"></a>

`DeleteDBClusterParameterGroup` deletes a specified DB cluster parameter group.

*Access level:* `Write`.

*Resource type:* [cluster-pg](iam-admin-resources.md#neptune-cluster-pg-resource) (required).

## rds:DeleteDBClusterSnapshot
<a name="neptune-iam-admin-actions-DeleteDBClusterSnapshot"></a>

`DeleteDBClusterSnapshot` deletes a DB cluster snapshot.

*Access level:* `Write`.

*Resource type:* [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource) (required).

## rds:DeleteDBInstance
<a name="neptune-iam-admin-actions-DeleteDBInstance"></a>

`DeleteDBInstance` deletes a specified DB instance.

*Access level:* `Write`.

*Resource type:* [db](iam-admin-resources.md#neptune-db-resource) (required).

## rds:DeleteDBParameterGroup
<a name="neptune-iam-admin-actions-DeleteDBParameterGroup"></a>

`DeleteDBParameterGroup` deletes a specified DBParameterGroup.

*Access level:* `Write`.

*Resource type:* [pg](iam-admin-resources.md#neptune-pg-resource) (required).

## rds:DeleteDBSubnetGroup
<a name="neptune-iam-admin-actions-DeleteDBSubnetGroup"></a>

`DeleteDBSubnetGroup` deletes a DB subnet group.

*Access level:* `Write`.

*Resource type:* [subgrp](iam-admin-resources.md#neptune-subgrp-resource) (required).

## rds:DeleteEventSubscription
<a name="neptune-iam-admin-actions-DeleteEventSubscription"></a>

`DeleteEventSubscription` deletes an event notification subscription.

*Access level:* `Write`.

*Resource type:* [es](iam-admin-resources.md#neptune-es-resource) (required).

## rds:DescribeDBClusterParameterGroups
<a name="neptune-iam-admin-actions-DescribeDBClusterParameterGroups"></a>

`DescribeDBClusterParameterGroups` returns a list of DBClusterParameterGroup descriptions.

*Access level:* `List`.

*Resource type:* [cluster-pg](iam-admin-resources.md#neptune-cluster-pg-resource) (required).

## rds:DescribeDBClusterParameters
<a name="neptune-iam-admin-actions-DescribeDBClusterParameters"></a>

`DescribeDBClusterParameters` returns the detailed parameter list for a particular DB cluster parameter group.

*Access level:* `List`.

*Resource type:* [cluster-pg](iam-admin-resources.md#neptune-cluster-pg-resource) (required).

## rds:DescribeDBClusterSnapshotAttributes
<a name="neptune-iam-admin-actions-DescribeDBClusterSnapshotAttributes"></a>

`DescribeDBClusterSnapshotAttributes` returns a list of DB cluster snapshot attribute names and values for a manual DB cluster snapshot.

*Access level:* `List`.

*Resource type:* [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource) (required).

## rds:DescribeDBClusterSnapshots
<a name="neptune-iam-admin-actions-DescribeDBClusterSnapshots"></a>

`DescribeDBClusterSnapshots` returns information about DB cluster snapshots.

*Access level:* `Read`.

## rds:DescribeDBClusters
<a name="neptune-iam-admin-actions-DescribeDBClusters"></a>

`DescribeDBClusters` returns information about a provisioned Neptune DB cluster.

*Access level:* `List`.

*Resource type:* [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).

## rds:DescribeDBEngineVersions
<a name="neptune-iam-admin-actions-DescribeDBEngineVersions"></a>

`DescribeDBEngineVersions` returns a list of the available DB engines.

*Access level:* `List`.

*Resource type:* [pg](iam-admin-resources.md#neptune-pg-resource) (required).

## rds:DescribeDBInstances
<a name="neptune-iam-admin-actions-DescribeDBInstances"></a>

`DescribeDBInstances` returns information about DB instances.

*Access level:* `List`.

*Resource type:* [es](iam-admin-resources.md#neptune-es-resource) (required).

## rds:DescribeDBParameterGroups
<a name="neptune-iam-admin-actions-DescribeDBParameterGroups"></a>

`DescribeDBParameterGroups` returns a list of DBParameterGroup descriptions.

*Access level:* `List`.

*Resource type:* [pg](iam-admin-resources.md#neptune-pg-resource) (required).

## rds:DescribeDBParameters
<a name="neptune-iam-admin-actions-DescribeDBParameters"></a>

`DescribeDBParameters` returns a detailed parameter list for a particular DB parameter group.

*Access level:* `List`.

*Resource type:* [pg](iam-admin-resources.md#neptune-pg-resource) (required).

## rds:DescribeDBSubnetGroups
<a name="neptune-iam-admin-actions-DescribeDBSubnetGroups"></a>

`DescribeDBSubnetGroups` returns a list of DBSubnetGroup descriptions.

*Access level:* `List`.

*Resource type:* [subgrp](iam-admin-resources.md#neptune-subgrp-resource) (required).

## rds:DescribeEventCategories
<a name="neptune-iam-admin-actions-DescribeEventCategories"></a>

`DescribeEventCategories` returns a list of categories for all event source types, or, if specified, for a specified source type.

*Access level:* `List`.

## rds:DescribeEventSubscriptions
<a name="neptune-iam-admin-actions-DescribeEventSubscriptions"></a>

`DescribeEventSubscriptions` lists all the subscription descriptions for a customer account.

*Access level:* `List`.

*Resource type:* [es](iam-admin-resources.md#neptune-es-resource) (required).

## rds:DescribeEvents
<a name="neptune-iam-admin-actions-DescribeEvents"></a>

`DescribeEvents` returns events related to DB instances, DB security groups, and DB parameter groups for the past 14 days.

*Access level:* `List`.

*Resource type:* [es](iam-admin-resources.md#neptune-es-resource) (required).

## rds:DescribeOrderableDBInstanceOptions
<a name="neptune-iam-admin-actions-DescribeOrderableDBInstanceOptions"></a>

`DescribeOrderableDBInstanceOptions` returns a list of orderable DB instance options for the specified engine.

*Access level:* `List`.

## rds:DescribePendingMaintenanceActions
<a name="neptune-iam-admin-actions-DescribePendingMaintenanceActions"></a>

`DescribePendingMaintenanceActions` returns a list of resources (for example, DB instances) that have at least one pending maintenance action.

*Access level:* `List`.

*Resource type:* [db](iam-admin-resources.md#neptune-db-resource) (required).

## rds:DescribeValidDBInstanceModifications
<a name="neptune-iam-admin-actions-DescribeValidDBInstanceModifications"></a>

`DescribeValidDBInstanceModifications` lists available modifications you can make to your DB instance.

*Access level:* `List`.

*Resource type:* [db](iam-admin-resources.md#neptune-db-resource) (required).

## rds:FailoverDBCluster
<a name="neptune-iam-admin-actions-FailoverDBCluster"></a>

`FailoverDBCluster` forces a failover for a DB cluster.

*Access level:* `Write`.

*Resource type:* [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).

## rds:ListTagsForResource
<a name="neptune-iam-admin-actions-ListTagsForResource"></a>

`ListTagsForResource` lists all tags on a Neptune resource.

*Access level:* `Read`.

*Resource types:*
+ [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource)
+ [db](iam-admin-resources.md#neptune-db-resource)
+ [es](iam-admin-resources.md#neptune-es-resource)
+ [pg](iam-admin-resources.md#neptune-pg-resource)
+ [subgrp](iam-admin-resources.md#neptune-subgrp-resource)

## rds:ModifyDBCluster
<a name="neptune-iam-admin-actions-ModifyDBCluster"></a>

`ModifyDBCluster`

Modifies a setting for a Neptune DB cluster.

*Access level:* `Write`.

*Dependent actions:* `iam:PassRole`.

*Resource types:*
+ [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).
+ [cluster-pg](iam-admin-resources.md#neptune-cluster-pg-resource) (required).

## rds:ModifyDBClusterParameterGroup
<a name="neptune-iam-admin-actions-ModifyDBClusterParameterGroup"></a>

`ModifyDBClusterParameterGroup` modifies the parameters of a DB cluster parameter group.

*Access level:* `Write`.

*Resource type:* [cluster-pg](iam-admin-resources.md#neptune-cluster-pg-resource) (required).

## rds:ModifyDBClusterSnapshotAttribute
<a name="neptune-iam-admin-actions-ModifyDBClusterSnapshotAttribute"></a>

`ModifyDBClusterSnapshotAttribute` adds an attribute and values to, or removes an attribute and values from, a manual DB cluster snapshot.

*Access level:* `Write`.

*Resource type:* [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource) (required).

## rds:ModifyDBInstance
<a name="neptune-iam-admin-actions-ModifyDBInstance"></a>

`ModifyDBInstance` modifies settings for a DB instance.

*Access level:* `Write`.

*Dependent actions:* `iam:PassRole`.

*Resource types:*
+ [db](iam-admin-resources.md#neptune-db-resource) (required).
+ [pg](iam-admin-resources.md#neptune-pg-resource) (required).

## rds:ModifyDBParameterGroup
<a name="neptune-iam-admin-actions-ModifyDBParameterGroup"></a>

`ModifyDBParameterGroup` modifies the parameters of a DB parameter group.

*Access level:* `Write`.

*Resource type:* [pg](iam-admin-resources.md#neptune-pg-resource) (required).

## rds:ModifyDBSubnetGroup
<a name="neptune-iam-admin-actions-ModifyDBSubnetGroup"></a>

`ModifyDBSubnetGroup` modifies an existing DB subnet group.

*Access level:* `Write`.

*Resource type:* [subgrp](iam-admin-resources.md#neptune-subgrp-resource) (required).

## rds:ModifyEventSubscription
<a name="neptune-iam-admin-actions-ModifyEventSubscription"></a>

`ModifyEventSubscription` modifies an existing Neptune event notification subscription.

*Access level:* `Write`.

*Resource type:* [es](iam-admin-resources.md#neptune-es-resource) (required).

## rds:RebootDBInstance
<a name="neptune-iam-admin-actions-RebootDBInstance"></a>

`RebootDBInstance` restarts the database engine service for the instance.

*Access level:* `Write`.

*Resource type:* [db](iam-admin-resources.md#neptune-db-resource) (required).

## rds:RemoveRoleFromDBCluster
<a name="neptune-iam-admin-actions-RemoveRoleFromDBCluster"></a>

`RemoveRoleFromDBCluster` disassociates an AWS Identity and Access Management (IAM) role from an Amazon Neptune DB cluster.

*Access level:* `Write`.

*Dependent actions:* `iam:PassRole`.

*Resource type:* [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).

## rds:RemoveSourceIdentifierFromSubscription
<a name="neptune-iam-admin-actions-RemoveSourceIdentifierFromSubscription"></a>

`RemoveSourceIdentifierFromSubscription` removes a source identifier from an existing Neptune event notification subscription.

*Access level:* `Write`.

*Resource type:* [es](iam-admin-resources.md#neptune-es-resource) (required).

## rds:RemoveTagsFromResource
<a name="neptune-iam-admin-actions-RemoveTagsFromResource"></a>

`RemoveTagsFromResource` removes metadata tags from a Neptune resource.

*Access level:* `Tagging`.

*Resource types:*
+ [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource)
+ [db](iam-admin-resources.md#neptune-db-resource)
+ [es](iam-admin-resources.md#neptune-es-resource)
+ [pg](iam-admin-resources.md#neptune-pg-resource)
+ [subgrp](iam-admin-resources.md#neptune-subgrp-resource)

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:ResetDBClusterParameterGroup
<a name="neptune-iam-admin-actions-ResetDBClusterParameterGroup"></a>

`ResetDBClusterParameterGroup` modifies the parameters of a DB cluster parameter group to the default value.

*Access level:* `Write`.

*Resource type:* [cluster-pg](iam-admin-resources.md#neptune-cluster-pg-resource) (required).

## rds:ResetDBParameterGroup
<a name="neptune-iam-admin-actions-ResetDBParameterGroup"></a>

`ResetDBParameterGroup` modifies the parameters of a DB parameter group to the engine/system default value.

*Access level:* `Write`.

*Resource type:* [pg](iam-admin-resources.md#neptune-pg-resource) (required).

## rds:RestoreDBClusterFromSnapshot
<a name="neptune-iam-admin-actions-RestoreDBClusterFromSnapshot"></a>

`RestoreDBClusterFromSnapshot` creates a new DB cluster from a DB cluster snapshot.

*Access level:* `Write`.

*Dependent actions:* `iam:PassRole`.

*Resource types:*
+ [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).
+ [cluster-snapshot](iam-admin-resources.md#neptune-cluster-snapshot-resource) (required).

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:RestoreDBClusterToPointInTime
<a name="neptune-iam-admin-actions-RestoreDBClusterToPointInTime"></a>

`RestoreDBClusterToPointInTime` restores a DB cluster to an arbitrary point in time.

*Access level:* `Write`.

*Dependent actions:* `iam:PassRole`.

*Resource types:*
+ [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).
+ [subgrp](iam-admin-resources.md#neptune-subgrp-resource) (required).

*Condition Keys:*
+ [aws:RequestTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_RequestTag)
+ [aws:TagKeys](iam-admin-condition-keys.md#admin-aws_TagKeys)

## rds:StartDBCluster
<a name="neptune-iam-admin-actions-StartDBCluster"></a>

`StartDBCluster` starts the specified DB cluster.

*Access level:* `Write`.

*Resource type:* [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).

## rds:StopDBCluster
<a name="neptune-iam-admin-actions-StopDBCluster"></a>

`StopDBCluster` stops the specified DB cluster.

*Access level:* `Write`.

*Resource type:* [cluster](iam-admin-resources.md#neptune-cluster-resource) (required).

# IAM resource types for administering Amazon Neptune
<a name="iam-admin-resources"></a>

Neptune supports the resource types in the following table for use in the `Resource` element of IAM administration policy statements. For more information about the `Resource` element, see [IAM JSON Policy Elements: Resource](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_elements_resource.html).

The [list of Neptune administration actions](neptune-iam-admin-actions.md) identifies the resource types that can be specified with each action. A resource type also determines which condition keys you can include in a policy, as specified in the last column of the table below.

The `ARN` column in the table below specifies the Amazon Resource Name (ARN) format that you must use to reference resources of this type. The portions that are preceded by a ` $ ` must be replaced by the actual values for your scenario. For example, if you see `$user-name` in an ARN, you must replace that string either with the actual IAM user's name or with a policy variable that contains an IAM user name. For more information about ARNs, see [IAM ARNs](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_identifiers.html#identifiers-arns), and [Working with administrative ARNs in Amazon Neptune](tagging-arns.md).

The` Condition Keys `column specifies condition context keys that you can include in an IAM policy statement only when both this resource and a compatible supporting action are included in the statement.


****  

| Resource Types | ARN | Condition Keys | 
| --- | --- | --- | 
|  `cluster` (a DB cluster)  | arn:partition:rds:region:account-id:cluster:instance-name |  [aws:ResourceTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_ResourceTag) [rds:cluster-tag/*tag-key*](iam-admin-condition-keys.md#admin-rds_cluster-tag)  | 
|  `cluster-pg` (a DB cluster parameter group)  | arn:partition:rds:region:account-id:cluster-pg:neptune-DBClusterParameterGroupName |  [aws:ResourceTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_ResourceTag)  | 
|  `cluster-snapshot` (a DB cluster snapshot)  | arn:partition:rds:region:account-id:cluster-snapshot:neptune-DBClusterSnapshotName |  [aws:ResourceTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_ResourceTag) [rds:cluster-snapshot-tag/*tag-key*](iam-admin-condition-keys.md#admin-rds_cluster-snapshot-tag)  | 
|  `db` (a DB instance)  | arn:partition:rds:region:account-id:db:neptune-DbInstanceName |  [aws:ResourceTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_ResourceTag) [rds:DatabaseClass](iam-admin-condition-keys.md#admin-rds_DatabaseClass) [rds:DatabaseEngine](iam-admin-condition-keys.md#admin-rds_DatabaseEngine) [rds:db-tag/*tag-key*](iam-admin-condition-keys.md#admin-rds_db-tag)  | 
|  `es` (an event subscription)  | arn:partition:rds:region:account-id:es:neptune-CustSubscriptionId  |  [aws:ResourceTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_ResourceTag) [rds:es-tag/*tag-key*](iam-admin-condition-keys.md#admin-rds_es-tag)  | 
|  `pg` (a DB parameter group)  | arn:partition:rds:region:account-id:pg:neptune-ParameterGroupName |  [aws:ResourceTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_ResourceTag) [rds:pg-tag/*tag-key*](iam-admin-condition-keys.md#admin-rds_pg-tag)  | 
|  `subgrp` (a DB subnet group)  | arn:partition:rds:region:account-id:subgrp:neptune-DBSubnetGroupName\$1 |  [aws:ResourceTag/*tag-key*](iam-admin-condition-keys.md#admin-aws_ResourceTag) [rds:subgrp-tag/*tag-key*](iam-admin-condition-keys.md#admin-rds_subgrp-tag)  | 

# IAM condition keys for administering Amazon Neptune
<a name="iam-admin-condition-keys"></a>

[Using condition keys](security-iam-access-manage.md#iam-using-condition-keys), you can specify conditions in an IAM policy statement so that the statement takes effect only when the conditions are true. The condition keys that you can use in Neptune administrative policy statements fall into the following categories:
+ [Global condition keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html)   –   These are defined by AWS for general use with AWS services. Most can be used in Neptune administrative policy statements.
+ [Administrative resource property condition keys](#iam-rds-property-condition-keys)   –   These keys, listed [below](#iam-rds-property-condition-keys), are based on properties of administrative resources.
+ [Tag-based access condition keys](#iam-rds-tag-based-condition-keys)   –   These keys, listed [below](#iam-rds-tag-based-condition-keys), are based on [AWS tags](https://docs.aws.amazon.com/general/latest/gr/aws_tagging.html) attached to administrative resources.

## Neptune administrative resource property condition keys
<a name="iam-rds-property-condition-keys"></a>


| Condition keys | Description | Type | 
| --- | --- | --- | 
| rds:DatabaseClass | Filters access by the type of DB instance class. | String | 
| rds:DatabaseEngine | Filters access by the database engine. For possible values refer to the engine parameter in CreateDBInstance API | String | 
| rds:DatabaseName | Filters access by the user-defined name of the database on the DB instance | String | 
| rds:EndpointType | Filters access by the type of the endpoint. One of: READER, WRITER, CUSTOM | String | 
| rds:Vpc | Filters access by the value that specifies whether the DB instance runs in an Amazon Virtual Private Cloud (Amazon VPC). To indicate that the DB instance runs in an Amazon VPC, specify true. | Boolean | 

## Administrative tag-based condition keys
<a name="iam-rds-tag-based-condition-keys"></a>

Amazon Neptune supports specifying conditions in an IAM policy using custom tags, to control access to Neptune through the [Management API reference](api.md).

For example, if you add a tag named `environment` to your DB instances, with values such as `beta`, `staging`, and `production`, you can then create a policy that restricts access to the instances based on the value of that tag.

**Important**  
If you manage access to your Neptune resources using tagging, be sure to secure access to the tags. You can restrict access to the tags by creating policies for the `AddTagsToResource` and `RemoveTagsFromResource` actions.  
For example, you could use the following policy to deny users the ability to add or remove tags for all resources. Then, you could create policies to allow specific users to add or remove tags.  

****  

```
{ "Version":"2012-10-17",		 	 	 
  "Statement":[
    { "Sid": "DenyTagUpdates",
      "Effect": "Deny",
      "Action": [
        "rds:AddTagsToResource",
        "rds:RemoveTagsFromResource"
      ],
      "Resource":"*"
    }
  ]
}
```

The following tag-based condition keys only work with administrative resources in administrative policy statements.


**Tag-based administrative condition keys**  

| Condition keys | Description | Type | 
| --- | --- | --- | 
|   [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requesttag)  | Filters access based on the presence of tag key-value pairs in the request. | String | 
|   [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-resourcetag)  | Filters access based on tag key-value pairs attached to the resource. | String | 
|   [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keyss](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keyss)  | Filters access based on the presence of tag keys in the request. | String | 
| rds:cluster-pg-tag/\$1\$1TagKey\$1 | Filters access by the tag attached to a DB cluster parameter group. | String | 
| rds:cluster-snapshot-tag/\$1\$1TagKey\$1 | Filters access by the tag attached to a DB cluster snapshot. | String | 
| rds:cluster-tag/\$1\$1TagKey\$1 | Filters access by the tag attached to a DB cluster. | String | 
| rds:db-tag/\$1\$1TagKey\$1 | Filters access by the tag attached to a DB instance. | String | 
| rds:es-tag/\$1\$1TagKey\$1 | Filters access by the tag attached to an event subscription. | String | 
| rds:pg-tag/\$1\$1TagKey\$1 | Filters access by the tag attached to a DB parameter group. | String | 
| rds:req-tag/\$1\$1TagKey\$1 | Filters access by the set of tag keys and values that can be used to tag a resource. | String | 
| rds:secgrp-tag/\$1\$1TagKey\$1 | Filters access by the tag attached to a DB security group. | String | 
| rds:snapshot-tag/\$1\$1TagKey\$1 | Filters access by the tag attached to a DB snapshot. | String | 
| rds:subgrp-tag/\$1\$1TagKey\$1 | Filters access by the tag attached to a DB subnet group | String | 

# Creating IAM administrative policy statements for Amazon Neptune
<a name="iam-admin-policy-examples"></a>

## General administrative policy examples
<a name="iam-admin-policy-general-examples"></a>

The following examples show how to create Neptune administrative policies that grant permissions to take various management actions on a DB cluster.

### Policy that prevents an IAM user from deleting a specified DB instance
<a name="iam-admin-policy-not-delete-instance"></a>

The following is an example policy that prevents an IAM user from deleting a specified Neptune DB instance:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "DenyDeleteOneInstance",
      "Effect": "Deny",
      "Action": "rds:DeleteDBInstance",
      "Resource": "arn:aws:rds:us-west-2:123456789012:db:my-instance-name"
    }
  ]
}
```

------

### Policy that grants permission to create new DB instances
<a name="iam-admin-policy-to-create-instances"></a>

The following is an example policy that allows an IAM user to create DB instances in a specified Neptune DB cluster:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowCreateInstance",
      "Effect": "Allow",
      "Action": "rds:CreateDBInstance",
      "Resource": "arn:aws:rds:us-west-2:123456789012:cluster:my-cluster"
    }
  ]
}
```

------

### Policy that grants permission to create new DB instances that use a specific DB parameter group
<a name="iam-admin-policy-to-create-instances-with-pg"></a>

The following is an example policy that allows an IAM user to create DB instances in a specified DB cluster (here `us-west-2`) in a specified Neptune DB cluster using only a specified DB parameter group.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowCreateInstanceWithPG",
      "Effect": "Allow",
      "Action": "rds:CreateDBInstance",
      "Resource": [
        "arn:aws:rds:us-west-2:123456789012:cluster:my-cluster",
        "arn:aws:rds:us-west-2:123456789012:pg:my-instance-pg"
      ]
    }
  ]
}
```

------

### Policy that grants permission to describe any resource
<a name="iam-admin-policy-to-describe"></a>

The following is an example policy that allows an IAM user to describe any Neptune resource.

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

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Sid": "AllowDescribe",
            "Effect": "Allow",
            "Action": "rds:Describe*",
            "Resource": "*"
        }
    ]
}
```

------

## Tag-based administrative policy examples
<a name="iam-admin-policy-tagging-examples"></a>

The following examples show how to create Neptune administrative policies that tags to filter permissions for various management actions on a DB cluster.

### Example 1: Grant permission for actions on a resource using a custom tag that can take multiple values
<a name="security-iam-tag-examples-1"></a>

The policy below allows use of the `ModifyDBInstance`, `CreateDBInstance` or `DeleteDBInstance` API on any DB instance that has the `env` tag set to either `dev` or `test`:

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

****  

```
{ "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowDevTestAccess",
      "Effect": "Allow",
      "Action": [
        "rds:ModifyDBInstance",
        "rds:CreateDBInstance",
        "rds:DeleteDBInstance"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "rds:db-tag/env": [
              "dev",
              "test"
          ],
          "rds:DatabaseEngine": "neptune"
        }
      }
    }
  ]
}
```

------

### Example 2: Limit the set of tag keys and values that can be used to tag a resource
<a name="security-iam-tag-examples-2"></a>

This policy uses a `Condition` key to allow a tag that has the key `env` and a value of `test`, `qa`, or `dev` to be added to a resource:

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

****  

```
{ "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowTagAccessForDevResources",
      "Effect": "Allow",
      "Action": [
        "rds:AddTagsToResource",
        "rds:RemoveTagsFromResource"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "rds:req-tag/env": [
            "test",
            "qa",
            "dev"
          ],
          "rds:DatabaseEngine": "neptune"
        }
      }
    }
  ]
}
```

------

### Example 3: Allow full access to Neptune resources based on `aws:ResourceTag`
<a name="security-iam-tag-examples-3"></a>

The following policy is similar to the first example above, but uses the `aws:ResourceTag` instead:

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

****  

```
{ "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "AllowFullAccessToDev",
      "Effect": "Allow",
      "Action": [
        "rds:*"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:ResourceTag/env": "dev",
          "rds:DatabaseEngine": "neptune"
        }
      }
    }
  ]
}
```

------

# Creating custom IAM policy statements to access data in Amazon Neptune
<a name="iam-data-access-policies"></a>

Neptune data-access policy statements use [data-access actions](iam-dp-actions.md), [resources](iam-data-resources.md), and [condition keys](iam-data-condition-keys.md#iam-neptune-condition-keys), all of which are preceded by a `neptune-db:` prefix.

**Topics**
+ [Using query actions in Neptune data-access policy statements](#iam-data-query-actions)
+ [IAM actions for data access in Amazon Neptune](iam-dp-actions.md)
+ [IAM resource types for accessing data in Amazon Neptune](iam-data-resources.md)
+ [IAM condition keys for accessing data in Amazon Neptune](iam-data-condition-keys.md)
+ [Creating IAM data-access policies in Amazon Neptune](iam-data-access-examples.md)

## Using query actions in Neptune data-access policy statements
<a name="iam-data-query-actions"></a>

There are three Neptune query actions that can be used in data-access policy statements, namely `ReadDataViaQuery`, `WriteDataViaQuery`, and `DeleteDataViaQuery`. A particular query may need permissions to perform more than one of these actions, and it may not always be obvious what combination of these actions must be permitted in order to run a query.

Before running a query, Neptune determines the permissions needed to run each step of the query, and combines these into the full set of permissions that the query requires. Note that this full set of permissions includes all actions that the query *might* perform, which is not necessarily the set of actions that the query actually will perform when it runs over your data.

This means that to permit a given query to run, you must provide permissions for every action that the query could possibly perform, whether or not it actually performs them.

Here are some sample Gremlin queries where this is explained in more detail:
+ 

  ```
  g.V().count()
  ```

  `g.V()` and `count()` only require read access, so the query as a whole only requires `ReadDataViaQuery` access.
+ 

  ```
  g.addV()
  ```

  `addV()` needs to check whether a vertex with a given ID exists or not before inserting a new one. This means that it requires both `ReadDataViaQuery` and `WriteDataViaQuery` access.
+ 

  ```
  g.V('1').as('a').out('created').addE('createdBy').to('a')
  ```

  `g.V('1').as('a')` and `out('created')` only require read access, but `addE().from('a')` requires both read and write access because `addE()` needs to read the `from` and `to` vertices and check whether an edge with the same ID already exists before adding a new one. The query as a whole therefore needs both `ReadDataViaQuery` and `WriteDataViaQuery` access.
+ 

  ```
  g.V().drop()
  ```

  `g.V()` only requires read access. `drop()` needs both read and delete access because it needs to read a vertex or edge before deleting it, so the query as a whole requires both `ReadDataViaQuery` and `DeleteDataViaQuery` access.
+ 

  ```
  g.V('1').property(single, 'key1', 'value1')
  ```

  `g.V('1')` only requires read access, but `property(single, 'key1', 'value1')` requires read, write, and delete access. Here, the `property()` step inserts the key and value if they do not already exist in the vertex, but if they do already exist, it deletes the existing property value and inserts a new value in its place. Therefore, the query as a whole requires `ReadDataViaQuery`, `WriteDataViaQuery`, and `DeleteDataViaQuery` access.

  Any query that contains a `property()` step will need `ReadDataViaQuery`, `WriteDataViaQuery`, and `DeleteDataViaQuery` permissions.

Here are some openCypher examples:
+ 

  ```
  MATCH (n)
  RETURN n
  ```

  This query reads all nodes in the database and returns them, which only requires `ReadDataViaQuery` access.
+ 

  ```
  MATCH (n:Person)
  SET n.dept = 'AWS'
  ```

  This query requires `ReadDataViaQuery`, `WriteDataViaQuery`, and `DeleteDataViaQuery` access. It reads all nodes with the label 'Person' and either adds a new property with the key `dept` and value `AWS` to them, or if the `dept` property already exists, it deletes the old value and inserts `AWS` instead. Also, if the value to be set is `null`, `SET` deletes the property altogether.

   Because the `SET` clause may in some cases need to delete an existing value, it **always** needs `DeleteDataViaQuery` permissions as well as `ReadDataViaQuery` and `WriteDataViaQuery` permissions.
+ 

  ```
  MATCH (n:Person)
  DETACH DELETE n
  ```

  This query needs `ReadDataViaQuery` and `DeleteDataViaQuery` permissions. It finds all the nodes with The label `Person` and deletes them along with the edges connected to those nodes and any associated labels and properties.
+ 

  ```
  MERGE (n:Person {name: 'John'})-[:knows]->(:Person {name: 'Peter'})
  RETURN n
  ```

  This query needs `ReadDataViaQuery` and `WriteDataViaQuery` permissions. The `MERGE` clause either matches a specified pattern or creates it. Since, a write can occur if the pattern is not matched, write permissions are needed as well as read permissions.

# IAM actions for data access in Amazon Neptune
<a name="iam-dp-actions"></a>

Note that Neptune data-access actions have the prefix `neptune-db:`, whereas administrative actions in Neptune have the prefix `rds:`.

The Amazon Resource Name (ARN) for a data resource in IAM is not the same as the ARN assigned to a cluster on creation. You must construct the ARN as shown in [Specifying data resources](iam-data-resources.md). Such data resource ARNs can use wildcards to include multiple resources.

Data-access policy statements can also include the [neptune-db:QueryLanguage](iam-data-condition-keys.md#iam-neptune-condition-keys) condition key to restrict access by query language.

Starting with [Release: 1.2.0.0 (2022-07-21)](engine-releases-1.2.0.0.md), Neptune supports restricting permissions to one or more [specific Neptune actions](https://docs.aws.amazon.com/service-authorization/latest/reference/list_amazonneptune.html). This provides more granular access control than was previously possible.

**Important**  
Changes to an IAM policy take up to 10 minutes to apply to the specified Neptune resources.
IAM policies that are applied to a Neptune DB cluster apply to all instances in that cluster.

## *Query-based data-access actions*
<a name="iam-dp-actions-queries"></a>

**Note**  
It isn't always obvious what permissions are needed to run a given query, because queries can potentially take more than one action depending on the data that they process. See [Using query actions](iam-data-access-policies.md#iam-data-query-actions) for more information.

## `neptune-db:ReadDataViaQuery`
<a name="readdataviaquery"></a>

`ReadDataViaQuery` allows the user to read data from the Neptune database by submitting queries.

*Action groups:* read-only, read-write.

*Action context keys:* `neptune-db:QueryLanguage`.

*Required resources:* database.

## `neptune-db:WriteDataViaQuery`
<a name="writedataviaquery"></a>

`WriteDataViaQuery` allows the user to write data to the Neptune database by submitting queries.

*Action groups:* read-write.

*Action context keys:* `neptune-db:QueryLanguage`.

*Required resources:* database.

## `neptune-db:DeleteDataViaQuery`
<a name="deletedataviaquery"></a>

`DeleteDataViaQuery` allows the user to delete data from the Neptune database by submitting queries.

*Action groups:* read-write.

*Action context keys:* `neptune-db:QueryLanguage`.

*Required resources:* database.

## `neptune-db:GetQueryStatus`
<a name="getquerystatus"></a>

`GetQueryStatus` allows the user to check the status of all active queries.

*Action groups:* read-only, read-write.

*Action context keys:* `neptune-db:QueryLanguage`.

*Required resources:* database.

## `neptune-db:GetStreamRecords`
<a name="getstreamrecords"></a>

`GetStreamRecords` allows the user to fetch stream records from Neptune.

*Action groups:* read-write.

*Action context keys:* `neptune-db:QueryLanguage`.

*Required resources:* database.

## `neptune-db:CancelQuery`
<a name="cancelquery"></a>

`CancelQuery` allows the user to to cancel a query.

*Action groups:* read-write.

*Required resources:* database.

## *General data-access actions*
<a name="iam-dp-actions-general"></a>

## `neptune-db:GetEngineStatus`
<a name="getenginestatus"></a>

`GetEngineStatus` allows the user to check the status of the Neptune engine.

*Action groups:* read-only, read-write.

*Required resources:* database.

## `neptune-db:GetStatisticsStatus`
<a name="getstatisticsstatus"></a>

`GetStatisticsStatus` allows the user to check the status of statistics being collected for the database.

*Action groups:* read-only, read-write.

*Required resources:* database.

## `neptune-db:GetGraphSummary`
<a name="getgraphsummary"></a>

`GetGraphSummary` The graph summary API enables you to retrieve a read-only summary of your graph.

*Action groups:* read-only, read-write.

*Required resources:* database.

## `neptune-db:ManageStatistics`
<a name="managestatistics"></a>

`ManageStatistics` allows the user to to manage the collection of statistics for the database.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:DeleteStatistics`
<a name="deletestatistics"></a>

`DeleteStatistics` allows the user to delete all the statistics in the database.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:ResetDatabase`
<a name="resetdatabase"></a>

`ResetDatabase` allows the user to get the token needed for a reset and to reset the Neptune database.

*Action groups:* read-write.

*Required resources:* database.

## *Bulk-loader data-access actions*
<a name="iam-dp-actions-loader"></a>

## `neptune-db:StartLoaderJob`
<a name="startloaderjob"></a>

`StartLoaderJob` allows the user to start a bulk-loader job.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:GetLoaderJobStatus`
<a name="getloaderjobstatus"></a>

`GetLoaderJobStatus` allows the user to check the status of a bulk-loader job.

*Action groups:* read-only, read-write.

*Required resources:* database.

## `neptune-db:ListLoaderJobs`
<a name="listloaderjobs"></a>

`ListLoaderJobs` allows the user to list all the bulk-loader jobs.

*Action groups:* list-only, read-only, read-write.

*Required resources:* database.

## `neptune-db:CancelLoaderJob`
<a name="cancelloaderjob"></a>

`CancelLoaderJob` allows the user to cancel a loader job.

*Action groups:* read-write.

*Required resources:* database.

## *Machine-learning data-access actions*
<a name="iam-dp-actions-ml"></a>

## `neptune-db:StartMLDataProcessingJob`
<a name="startmldataprocessingjob"></a>

`StartMLDataProcessingJob` allows a user to start a Neptune ML data processing job.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:StartMLModelTrainingJob`
<a name="startmlmodeltrainingjob"></a>

`StartMLModelTrainingJob` allows a user to start an ML model training job.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:StartMLModelTransformJob`
<a name="startmlmodeltransformjob"></a>

`StartMLModelTransformJob` allows a user to start an ML model transform job.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:CreateMLEndpoint`
<a name="createmlendpoint"></a>

`CreateMLEndpoint` allows a user to create a Neptune ML endpoint.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:GetMLDataProcessingJobStatus`
<a name="getmldataprocessingjobstatus"></a>

`GetMLDataProcessingJobStatus` allows a user to check the status of a Neptune ML data processing job.

*Action groups:* read-only, read-write.

*Required resources:* database.

## `neptune-db:GetMLModelTrainingJobStatus`
<a name="getmlmodeltrainingjobstatus"></a>

`GetMLModelTrainingJobStatus` allows a user to check the status of a Neptune ML model training job.

*Action groups:* read-only, read-write.

*Required resources:* database.

## `neptune-db:GetMLModelTransformJobStatus`
<a name="getmlmodeltransformjobstatus"></a>

`GetMLModelTransformJobStatus` allows a user to check the status of a Neptune ML model transform job.

*Action groups:* read-only, read-write.

*Required resources:* database.

## `neptune-db:GetMLEndpointStatus`
<a name="getmlendpointstatus"></a>

`GetMLEndpointStatus` allows a user to check the status of a Neptune ML endpoint.

*Action groups:* read-only, read-write.

*Required resources:* database.

## `neptune-db:ListMLDataProcessingJobs`
<a name="listmldataprocessingjobs"></a>

`ListMLDataProcessingJobs` allows a user to list all the Neptune ML data processing jobs.

*Action groups:* list-only, read-only, read-write.

*Required resources:* database.

## `neptune-db:ListMLModelTrainingJobs`
<a name="listmlmodeltrainingjobs"></a>

`ListMLModelTrainingJobs` allows a user to list all the Neptune ML model training jobs.

*Action groups:* list-only, read-only, read-write.

*Required resources:* database.

## `neptune-db:ListMLModelTransformJobs`
<a name="listmlmodeltransformjobs"></a>

`ListMLModelTransformJobs` allows a user to list all the ML model transform jobs.

*Action groups:* list-only, read-only, read-write.

*Required resources:* database.

## `neptune-db:ListMLEndpoints`
<a name="listmlendpoints"></a>

`ListMLEndpoints` allows a user to list all the Neptune ML endpoints.

*Action groups:* list-only, read-only, read-write.

*Required resources:* database.

## `neptune-db:CancelMLDataProcessingJob`
<a name="cancelmldataprocessingjob"></a>

`CancelMLDataProcessingJob` allows a user to cancel a Neptune ML data processing job.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:CancelMLModelTrainingJob`
<a name="cancelmlmodeltrainingjob"></a>

`CancelMLModelTrainingJob` allows a user to cancel a Neptune ML model training job.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:CancelMLModelTransformJob`
<a name="cancelmlmodeltransformjob"></a>

`CancelMLModelTransformJob` allows a user to cancel a Neptune ML model transform job.

*Action groups:* read-write.

*Required resources:* database.

## `neptune-db:DeleteMLEndpoint`
<a name="deletemlendpoint"></a>

`DeleteMLEndpoint` allows a user to delete a Neptune ML endpoint.

*Action groups:* read-write.

*Required resources:* database.

# IAM resource types for accessing data in Amazon Neptune
<a name="iam-data-resources"></a>

Data resources, like data actions, have a `neptune-db:` prefix.

In a Neptune data-access policy, you specify the DB cluster that you are giving access to in an ARN with the following format:

```
arn:aws:neptune-db:region:account-id:cluster-resource-id/*
```

Such a resource ARN contains the following parts:
+ `region` is the AWS Region for the Amazon Neptune DB cluster.
+ `account-id` is the AWS account number for the DB cluster.
+ `cluster-resource-id` is a resource id for the DB cluster.
**Important**  
The `cluster-resource-id` is different from the cluster identifier. To find a cluster resource ID in the Neptune AWS Management Console, look in the **Configuration** section for the DB cluster in question.

# IAM condition keys for accessing data in Amazon Neptune
<a name="iam-data-condition-keys"></a>

[Using condition keys](security-iam-access-manage.md#iam-using-condition-keys), you can specify conditions in an IAM policy statement so that the statement takes effect only when the conditions are true.

The condition keys that you can use in Neptune data-access policy statements fall into the following categories:
+ [Global condition keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html)   –   The subset of AWS global condition keys that Neptune supports in data-access policy statements is listed [below](#iam-data-global-condition-keys).
+ [Service-specific condition keys](#iam-neptune-condition-keys)   –   These are keys defined by Neptune specifically for use in data-access policy statements. At present there is only one, [neptune-db:QueryLanguage](#neptune-db-query-language), which grants access only if a specific query language is being used.

## AWS global condition context keys supported by Neptune in data-access policy statements
<a name="iam-data-global-condition-keys"></a>

The following table lists the subset of [AWS global condition context keys](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html) that Amazon Neptune supports for use in data-access policy statements:


**Global condition keys that you can use in data-access policy statements**  

| Condition Keys | Description | Type | 
| --- | --- | --- | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-currenttime](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-currenttime) | Filters access by the current date and time of the request. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-epochtime](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-epochtime) | Filters access by date and time of the request expressed as a UNIX epoch value. | Numeric | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalaccount](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalaccount) | Filters access by the account to which the requesting principal belongs. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalarn](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalarn) | Filters access by the ARN of the principal that made the request. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalisawsservice](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalisawsservice) | Allows access only if the call is being made directly by an AWS service principal. | Boolean | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgid](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgid) | Filters access by the identifier of the organization in AWS Organizations to which the requesting principal belongs. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgpaths](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principalorgpaths) | Filters access by the AWS Organizations path for the principal who is making the request. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltag](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltag) | Filters access by a tag attached to the principal making the request. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltype](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-principaltype) | Filters access by the type of principal making the request. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requestedregion](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-requestedregion) | Filters access by the AWS Region that was called in the request. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-securetransport](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-securetransport) | Allows access only if the request was sent using SSL. | Boolean | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceip](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-sourceip) | Filters access by the requester's IP address. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tokenissuetime](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-tokenissuetime) | Filters access by the date and time that temporary security credentials were issued. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-useragent](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-useragent) | Filters access by the requester's client application. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-userid](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-userid) | Filters access by the requester's principal identifier. | String | 
| [https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-viaawsservice](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_policies_condition-keys.html#condition-keys-viaawsservice) | Allows access only if an AWS service made the request on your behalf. | Boolean | 

## Neptune service-specific condition keys
<a name="iam-neptune-condition-keys"></a>

Neptune supports the following service-specific condition key for IAM policies:


**Neptune service-specific condition keys**  

| Condition Keys | Description | Type | 
| --- | --- | --- | 
| neptune-db:QueryLanguage |  Filters data access by the query language being used. Valid values are: `Gremlin`, `OpenCypher`, and `Sparql`. Supported actions are `ReadDataViaQuery`, `WriteDataViaQuery`, `DeleteDataViaQuery`, `GetQueryStatus`, and `CancelQuery`.  | String | 

# Creating IAM data-access policies in Amazon Neptune
<a name="iam-data-access-examples"></a>

The following examples show how to create custom IAM policies that use fine-grained access control of data-plane APIs and actions, introduced in Neptune [engine release version 1.2.0.0](engine-releases-1.2.0.0.md). 

## Policy example allowing unrestricted access to the data in a Neptune DB cluster
<a name="iam-auth-data-policy-example-general"></a>

The following example policy allows an IAM user to connect to a Neptune DB cluster using IAM database authentication, and uses the "`*`" character to match all available actions.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "neptune-db:*",
      "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
    }
  ]
}
```

------

The preceding example includes a resource ARN in a format that is particular to Neptune IAM authentication. To construct the ARN, see [Specifying data resources](iam-data-resources.md). Note that the ARN used for an IAM authorization `Resource` is not the same as the ARN assigned to the cluster on creation.

## Policy example allowing read-only access to a Neptune DB cluster
<a name="iam-auth-data-policy-example-read-only"></a>

The following policy grants permission for full read-only access to data in a Neptune DB cluster: 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement":[
    {
      "Effect": "Allow",
      "Action": [
        "neptune-db:Read*",
        "neptune-db:Get*",
        "neptune-db:List*"
      ],
      "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
    }
  ]
}
```

------

## Policy example denying all access to a Neptune DB cluster
<a name="iam-auth-data-policy-example-deny"></a>

The default IAM action is to deny access to a DB cluster unless an `Allow` *Effect* is granted. However, the following policy denies all access to a DB cluster for a particular AWS account and Region, which then takes precedence over any `Allow` effect.

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Deny",
      "Action": "neptune-db:*",
      "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
    }
  ]
}
```

------

## Policy example granting read access through queries
<a name="iam-auth-data-policy-example-read-query"></a>

The following policy only grants permission to read from a Neptune DB cluster using a query: 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "neptune-db:ReadDataViaQuery",
      "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
    }
  ]
}
```

------

## Policy example that only allows Gremlin queries
<a name="iam-auth-data-policy-example-gremlin-only"></a>

The following policy uses the `neptune-db:QueryLanguage` condition key to grant permission to query Neptune only using the Gremlin query language: 

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "neptune-db:ReadDataViaQuery",
        "neptune-db:WriteDataViaQuery",
        "neptune-db:DeleteDataViaQuery"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "neptune-db:QueryLanguage": "Gremlin"
        }
      }
    }
  ]
}
```

------

## Policy example allowing all access except to Neptune ML model management
<a name="iam-auth-data-policy-example-all-but-ml"></a>

The following policy grants full access to Neptune graph operations except for the Neptune ML model-management features:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement":[
    {
      "Effect": "Allow",
      "Action": [
        "neptune-db:CancelLoaderJob",
        "neptune-db:CancelQuery",
        "neptune-db:DeleteDataViaQuery",
        "neptune-db:DeleteStatistics",
        "neptune-db:GetEngineStatus",
        "neptune-db:GetLoaderJobStatus",
        "neptune-db:GetQueryStatus",
        "neptune-db:GetStatisticsStatus",
        "neptune-db:GetStreamRecords",
        "neptune-db:ListLoaderJobs",
        "neptune-db:ManageStatistics",
        "neptune-db:ReadDataViaQuery",
        "neptune-db:ResetDatabase",
        "neptune-db:StartLoaderJob",
        "neptune-db:WriteDataViaQuery"
      ],
      "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
    }
  ]
}
```

------

## Policy example allowing access to Neptune ML model management
<a name="iam-auth-data-policy-example-ml"></a>

This policy grants access to the Neptune ML model-management features:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement":[
    {
      "Effect": "Allow",
      "Action": [
        "neptune-db:CancelMLDataProcessingJob",
        "neptune-db:CancelMLModelTrainingJob",
        "neptune-db:CancelMLModelTransformJob",
        "neptune-db:CreateMLEndpoint",
        "neptune-db:DeleteMLEndpoint",
        "neptune-db:GetMLDataProcessingJobStatus",
        "neptune-db:GetMLEndpointStatus",
        "neptune-db:GetMLModelTrainingJobStatus",
        "neptune-db:GetMLModelTransformJobStatus",
        "neptune-db:ListMLDataProcessingJobs",
        "neptune-db:ListMLEndpoints",
        "neptune-db:ListMLModelTrainingJobs",
        "neptune-db:ListMLModelTransformJobs",
        "neptune-db:StartMLDataProcessingJob",
        "neptune-db:StartMLModelTrainingJob",
        "neptune-db:StartMLModelTransformJob"
      ],
      "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
    }
  ]
}
```

------

## Policy example granting full query access
<a name="iam-auth-data-policy-example-full-query"></a>

The following policy grants full access to Neptune graph query operations, but not to features like fast reset, streams, the bulk loader, Neptune ML model management, and so forth:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement":[
    {
      "Effect": "Allow",
      "Action": [
        "neptune-db:ReadDataViaQuery",
        "neptune-db:WriteDataViaQuery",
        "neptune-db:DeleteDataViaQuery",
        "neptune-db:GetEngineStatus",
        "neptune-db:GetQueryStatus",
        "neptune-db:CancelQuery"
      ],
      "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
    }
  ]
}
```

------

## Policy example granting full access for Gremlin queries only
<a name="iam-auth-data-policy-example-full-gremlin-access"></a>

The following policy grants full access to Neptune graph query operations using the Gremlin query language, but not to queries in other languages, and not to features like fast reset, streams, the bulk loader, Neptune ML model management, and so on:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement":[
    {
      "Effect": "Allow",
      "Action": [
        "neptune-db:ReadDataViaQuery",
        "neptune-db:WriteDataViaQuery",
        "neptune-db:DeleteDataViaQuery",
        "neptune-db:GetEngineStatus",
        "neptune-db:GetQueryStatus",
        "neptune-db:CancelQuery"
      ],
      "Resource": [
        "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
      ],
      "Condition": {
        "StringEquals": {
           "neptune-db:QueryLanguage":"Gremlin"
        }
      }
    }
  ]
}
```

------

## Policy example granting full access except for fast reset
<a name="iam-auth-data-policy-example-all-but-fast-reset"></a>

The following policy grants full access to a Neptune DB cluster except for using fast reset:

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Action": "neptune-db:*",
      "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
    },
    {
      "Effect": "Deny",
      "Action": "neptune-db:ResetDatabase",
      "Resource": "arn:aws:neptune-db:us-east-1:123456789012:cluster-ABCD1234EFGH5678IJKL90MNOP/*"
    }
  ]
}
```

------

# Using service-linked roles for Amazon Neptune
<a name="security-iam-service-linked-roles"></a>

Amazon Neptune uses AWS Identity and Access Management (IAM)[ service-linked roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_terms-and-concepts.html#iam-term-service-linked-role). A service-linked role is a unique type of IAM role that is linked directly to Neptune. Service-linked roles are predefined by Neptune and include all the permissions that the service requires to call other AWS services on your behalf. 

**Important**  
For certain management features, Amazon Neptune uses operational technology that is shared with Amazon RDS. This includes the *service-linked role* and management API permissions.

A service-linked role makes using Neptune easier because you don’t have to manually add the necessary permissions. Neptune defines the permissions of its service-linked roles, and unless defined otherwise, only Neptune can assume its roles. The defined permissions include the trust policy and the permissions policy, and that permissions policy cannot be attached to any other IAM entity.

You can delete the roles only after first deleting their related resources. This protects your Neptune resources because you can't inadvertently remove permission to access the resources.

For information about other services that support service-linked roles, see [AWS Services That Work with IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/reference_aws-services-that-work-with-iam.html), and look for the services that have **Yes **in the **Service-Linked Role** column. Choose a **Yes** with a link to view the service-linked role documentation for that service.

## Service-Linked Role Permissions for Neptune
<a name="service-linked-role-permissions"></a>

Neptune uses the `AWSServiceRoleForRDS` service-linked role to allow Neptune and Amazon RDS to call AWS services on behalf of your database instances. The `AWSServiceRoleForRDS` service-linked role trusts the `rds.amazonaws.com` service to assume the role.

The role permissions policy allows Neptune to complete the following actions on the specified resources:
+ Actions on `ec2`:
  + `AssignPrivateIpAddresses`
  + `AuthorizeSecurityGroupIngress`
  + `CreateNetworkInterface`
  + `CreateSecurityGroup`
  + `DeleteNetworkInterface`
  + `DeleteSecurityGroup`
  + `DescribeAvailabilityZones`
  + `DescribeInternetGateways`
  + `DescribeSecurityGroups`
  + `DescribeSubnets`
  + `DescribeVpcAttribute`
  + `DescribeVpcs`
  + `ModifyNetworkInterfaceAttribute`
  + `RevokeSecurityGroupIngress`
  + `UnassignPrivateIpAddresses`
+ Actions on `sns`:
  + `ListTopic`
  + `Publish`
+ Actions on `cloudwatch`:
  + `PutMetricData`
  + `GetMetricData`
  + `CreateLogStream`
  + `PullLogEvents`
  + `DescribeLogStreams`
  + `CreateLogGroup`

**Note**  
You must configure permissions to allow an IAM entity (such as a user, group, or role) to create, edit, or delete a service-linked role. You might encounter the following error message:  
Unable to create the resource. Verify that you have permission to create service linked role. Otherwise wait and try again later.  
If you see this message, make sure that you have the following permissions enabled:   

```
{
    "Action": "iam:CreateServiceLinkedRole",
    "Effect": "Allow",
    "Resource": "arn:aws:iam::*:role/aws-service-role/rds.amazonaws.com/AWSServiceRoleForRDS",
    "Condition": {
        "StringLike": {
            "iam:AWSServiceName":"rds.amazonaws.com"
        }
    }
}
```
 For more information, see [Service-Linked Role Permissions](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#service-linked-role-permissions) in the *IAM User Guide*.

## Creating a Service-Linked Role for Neptune
<a name="create-service-linked-role"></a>

You don't need to manually create a service-linked role. When you create an instance or a cluster, Neptune creates the service-linked role for you.

**Important**  
To learn more, see [A New Role Appeared in My IAM Account](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot_roles.html#troubleshoot_roles_new-role-appeared) in the *IAM User Guide*.

If you delete this service-linked role and then need to create it again, you can use the same process to re-create the role in your account. When you create an instance or a cluster, Neptune creates the service-linked role for you again.

## Editing a Service-Linked Role for Neptune
<a name="edit-service-linked-role"></a>

Neptune does not allow you to edit the `AWSServiceRoleForRDS` service-linked role. After you create a service-linked role, you cannot change the name of the role because various entities might reference the role. However, you can edit the description of the role using IAM. For more information, see [Editing a Service-Linked Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#edit-service-linked-role) in the *IAM User Guide*.

## Deleting a Service-Linked Role for Neptune
<a name="delete-service-linked-role"></a>

If you no longer need to use a feature or service that requires a service-linked role, we recommend that you delete that role. That way you don’t have an unused entity that is not actively monitored or maintained. However, you must delete all of your instances and clusters before you can delete the associated service-linked role.

### Cleaning Up a Service-Linked Role Before Deleting
<a name="delete-service-linked-role-cleanup"></a>

Before you can use IAM to delete a service-linked role, you must first confirm that the role has no active sessions and remove any resources used by the role.

**To check whether the service-linked role has an active session in the IAM console**

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 of the IAM console, choose **Roles**. Then choose the name (not the check box) of the `AWSServiceRoleForRDS` role.

1. On the **Summary** page for the selected role, choose the **Access Advisor** tab.

1. On the **Access Advisor** tab, review recent activity for the service-linked role.
**Note**  
If you are unsure whether Neptune is using the `AWSServiceRoleForRDS` role, you can try to delete the role. If the service is using the role, then the deletion fails and you can view the Regions where the role is being used. If the role is being used, then you must wait for the session to end before you can delete the role. You cannot revoke the session for a service-linked role. 

If you want to remove the `AWSServiceRoleForRDS` role, you must first delete *all* of your instances and clusters.

#### Deleting All of Your Instances
<a name="delete-service-linked-role-instances"></a>

Use one of these procedures to delete each of your instances.

**To delete an instance (console)**

1. Open the Amazon RDS console at [https://console.aws.amazon.com/rds/](https://console.aws.amazon.com/rds/).

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

1. In the **Instances** list, choose the instance that you want to delete.

1. Choose **Instance actions**, and then choose **Delete**.

1. If you are prompted for **Create final Snapshot?**, choose **Yes** or **No**.

1. If you chose **Yes** in the previous step, for **Final snapshot name** enter the name of your final snapshot.

1. Choose **Delete**.

**To delete an instance (AWS CLI)**  
See `[delete-db-instance](https://docs.aws.amazon.com/cli/latest/reference/neptune/delete-db-instance.html)` in the *AWS CLI Command Reference*.

**To delete an instance (API)**  
See `[DeleteDBInstance](&doc-domaiAPI_DeleteDBInstance.html)`.

#### Deleting All of Your Clusters
<a name="delete-service-linked-role-clusters"></a>

Use one of the following procedures to delete a single cluster, and then repeat the procedure for each of your clusters.

**To delete a cluster (console)**

1. Sign in to the AWS Management Console, and open the Amazon Neptune console at [https://console.aws.amazon.com/neptune/home](https://console.aws.amazon.com/neptune/home).

1. In the **Clusters** list, choose the cluster that you want to delete.

1. Choose **Cluster Actions**, and then choose **Delete**.

1. Choose **Delete**.

**To delete a cluster (CLI)**  
See `[delete-db-cluster](https://docs.aws.amazon.com/cli/latest/reference/neptune/delete-db-cluster.html)` in the *AWS CLI Command Reference*.

**To delete a cluster (API)**  
See `[DeleteDBCluster](API_DeleteDBCluster.html)`

You can use the IAM console, the IAM CLI, or the IAM API to delete the `AWSServiceRoleForRDS` service-linked role. For more information, see [Deleting a Service-Linked Role](https://docs.aws.amazon.com/IAM/latest/UserGuide/using-service-linked-roles.html#delete-service-linked-role) in the *IAM User Guide*.

# Using temporary credentials to connect to Amazon Neptune
<a name="iam-auth-temporary-credentials"></a>

Amazon Neptune supports IAM authentication using temporary credentials.

You can use an assumed role to authenticate using an IAM authentication policy, like one of the example policies in the previous sections.

If you are using temporary credentials, you must specify `AWS_SESSION_TOKEN` in addition to `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `SERVICE_REGION`.

**Note**  
The temporary credentials expire after a specified interval, *including the session token*.  
You must update your session token when you request new credentials. For more information, see [Using Temporary Security Credentials to Request Access to AWS Resources](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_credentials_temp_use-resources.html).

The following sections describe how to allow access and retrieve temporary credentials.

**To authenticate using temporary credentials**

1. Create an IAM role with permission to access a Neptune cluster. For information about creating this role, see [Using different kinds of IAM policies for controlling access to Neptune](security-iam-access-manage.md#iam-auth-policy).

1. Add a trust relationship to the role that allows access to the credentials.

   Retrieve the temporary credentials, including the `AWS_ACCESS_KEY_ID`, `AWS_SECRET_ACCESS_KEY`, and `AWS_SESSION_TOKEN`.

1. Connect to the Neptune cluster and sign the requests using the temporary credentials. For more information about connecting and signing requests, see [Connecting to your Amazon Neptune database using AWS Identity and Access Management authentication](iam-auth-connecting.md).

There are various methods for retrieving temporary credentials depending on the environment.

**Topics**
+ [Getting Temporary Credentials Using the AWS CLI](#iam-auth-temporary-credentials-cli)
+ [Setting Up AWS Lambda for Neptune IAM Authentication](#iam-auth-temporary-credentials-lambda)
+ [Setting Up Amazon EC2 for Neptune IAM Authentication](#iam-auth-temporary-credentials-ec2)

## Getting Temporary Credentials Using the AWS CLI
<a name="iam-auth-temporary-credentials-cli"></a>

To get credentials using the AWS Command Line Interface (AWS CLI), first you need to add a trust relationship that grants permission to assume the role to the AWS user that will run the AWS CLI command.

Add the following trust relationship to the Neptune IAM authentication role. If you don't have a Neptune IAM authentication role, see [Using different kinds of IAM policies for controlling access to Neptune](security-iam-access-manage.md#iam-auth-policy).

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456789012:user/test"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

------

For information about adding the trust relationship to the role, see [Editing the Trust Relationship for an Existing Role](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/edit_trust.html) in the *AWS Directory Service Administration Guide*.

If the Neptune policy is not yet attached to a role, create a new role. Attach the Neptune IAM authentication policy, and then add the trust policy. For information about creating a new role, see [Creating a New Role](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/create_role.html).

**Note**  
The following sections assume that you have the AWS CLI installed.

**To run the AWS CLI manually**

1. Enter the following command to request the credentials using the AWS CLI. Replace the role ARN, session name, and profile with your own values.

   ```
   aws sts assume-role  --role-arn  arn:aws:iam::123456789012:role/NeptuneIAMAuthRole --role-session-name test --profile testprofile
   ```

1. The following is example output from the command. The `Credentials` section contains the values that you need.
**Note**  
Record the `Expiration` value because you need to get new credentials after this time.

   ```
   {
       "AssumedRoleUser": {
           "AssumedRoleId": "AROA3XFRBF535PLBIFPI4:s3-access-example",
           "Arn": "arn:aws:sts::123456789012:assumed-role/xaccounts3access/s3-access-example"
       },
       "Credentials": {
           "SecretAccessKey": "9drTJvcXLB89EXAMPLELB8923FB892xMFI",
           "SessionToken": "AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=",
           "Expiration": "2016-03-15T00:05:07Z",
           "AccessKeyId": "ASIAJEXAMPLEXEG2JICEA"
       }
   }
   ```

1. Set the environment variables using the returned credentials.

   ```
   export AWS_ACCESS_KEY_ID=ASIAJEXAMPLEXEG2JICEA
   export AWS_SECRET_ACCESS_KEY=9drTJvcXLB89EXAMPLELB8923FB892xMFI
   export AWS_SESSION_TOKEN=AQoXdzELDDY//////////wEaoAK1wvxJY12r2IrDFT2IvAzTCn3zHoZ7YNtpiQLF0MqZye/qwjzP2iEXAMPLEbw/m3hsj8VBTkPORGvr9jM5sgP+w9IZWZnU+LWhmg+a5fDi2oTGUYcdg9uexQ4mtCHIHfi4citgqZTgco40Yqr4lIlo4V2b2Dyauk0eYFNebHtYlFVgAUj+7Indz3LU0aTWk1WKIjHmmMCIoTkyYp/k7kUG7moeEYKSitwQIi6Gjn+nyzM+PtoA3685ixzv0R7i5rjQi0YE0lf1oeie3bDiNHncmzosRM6SFiPzSvp6h/32xQuZsjcypmwsPSDtTPYcs0+YN/8BRi2/IcrxSpnWEXAMPLEXSDFTAQAM6Dl9zR0tXoybnlrZIwMLlMi1Kcgo5OytwU=
   
   export SERVICE_REGION=us-east-1 or us-east-2 or us-west-1 or us-west-2 or ca-central-1 or
                         ca-west-1 or sa-east-1 or eu-north-1 or eu-south-2 or eu-west-1 or eu-west-2 or eu-west-3 or
                         eu-central-1 or me-south-1 or me-central-1 or il-central-1 or af-south-1 or ap-east-1 or
                         ap-northeast-1 or ap-northeast-2 or ap-northeast-3 or ap-southeast-1 or ap-southeast-2 or
                         ap-southeast-3 or ap-southeast-4 or ap-southeast-5 or ap-south-1 or ap-south-2 or
                         cn-north-1 or cn-northwest-1 or
                         us-gov-east-1 or us-gov-west-1
   ```

1. Connect using one of the following methods.
   + [Connecting to Amazon Neptune databases using IAM authentication with Gremlin console](iam-auth-connecting-gremlin-console.md)
   + [Connecting to Amazon Neptune databases using IAM with Gremlin Java](iam-auth-connecting-gremlin-java.md)
   + [Connecting to Amazon Neptune databases using IAM authentication with Java and SPARQL](iam-auth-connecting-sparql-java.md)
   + [Connecting to Amazon Neptune databases using IAM authentication with Python](iam-auth-connecting-python.md)

**To use a script to get the credentials**

1. Run the following command to install the **jq** command. The script uses this command to parse the output of the AWS CLI command.

   ```
   sudo yum -y install jq
   ```

1. Create a file named `credentials.sh` in a text editor and add the following text. Replace the service Region, role ARN, session name, and profile with your own values.

   ```
   #!/bin/bash
   
   creds_json=$(aws sts assume-role  --role-arn  arn:aws:iam::123456789012:role/NeptuneIAMAuthRole --role-session-name test --profile testprofile)
   
   export AWS_ACCESS_KEY_ID=$(echo "$creds_json" | jq .Credentials.AccessKeyId |tr -d '"')
   export AWS_SECRET_ACCESS_KEY=$(echo "$creds_json" | jq .Credentials.SecretAccessKey| tr -d '"')
   export AWS_SESSION_TOKEN=$(echo "$creds_json" | jq .Credentials.SessionToken|tr -d '"')
   
   export SERVICE_REGION=us-east-1 or us-east-2 or us-west-1 or us-west-2 or ca-central-1 or
                         ca-west-1 or sa-east-1 or eu-north-1 or eu-south-2 or eu-west-1 or eu-west-2 or eu-west-3 or
                         eu-central-1 or me-south-1 or me-central-1 or il-central-1 or af-south-1 or ap-east-1 or
                         ap-northeast-1 or ap-northeast-2 or ap-northeast-3 or ap-southeast-1 or ap-southeast-2 or
                         ap-southeast-3 or ap-southeast-4 or ap-southeast-5 or ap-south-1 or ap-south-2 or
                         cn-north-1 or cn-northwest-1 or
                         us-gov-east-1 or us-gov-west-1
   ```

1. Connect using one of the following methods.
   + [Connecting to Amazon Neptune databases using IAM authentication with Gremlin console](iam-auth-connecting-gremlin-console.md)
   + [Connecting to Amazon Neptune databases using IAM with Gremlin Java](iam-auth-connecting-gremlin-java.md)
   + [Connecting to Amazon Neptune databases using IAM authentication with Java and SPARQL](iam-auth-connecting-sparql-java.md)
   + [Connecting to Amazon Neptune databases using IAM authentication with Python](iam-auth-connecting-python.md)

## Setting Up AWS Lambda for Neptune IAM Authentication
<a name="iam-auth-temporary-credentials-lambda"></a>

AWS Lambda includes credentials automatically each time the Lambda function is run.

First you add a trust relationship that grants permission to assume the role to the Lambda service.

Add the following trust relationship to the Neptune IAM authentication role. If you don't have a Neptune IAM authentication role, see [Using different kinds of IAM policies for controlling access to Neptune](security-iam-access-manage.md#iam-auth-policy).

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "lambda.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

------

For information about adding the trust relationship to the role, see [Editing the Trust Relationship for an Existing Role](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/edit_trust.html) in the *AWS Directory ServiceAdministration Guide*.

If the Neptune policy is not yet attached to a role, create a new role. Attach the Neptune IAM authentication policy, and then add the trust policy. For information about creating a new role, see [Creating a New Role](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/create_role.html) in the *AWS Directory Service Administration Guide*.

**To access Neptune from Lambda**

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

1. Create a new Lambda function for Python version 3.6.

1. Assign the `AWSLambdaVPCAccessExecutionRole` role to the Lambda function. This is required to access Neptune resources, which are VPC only.

1. Assign the Neptune authentication IAM role to the Lambda function.

   For more information, see [AWS Lambda Permissions](https://docs.aws.amazon.com/lambda/latest/dg/intro-permission-model.html) in the *AWS Lambda Developer Guide*.

1.  Copy the IAM authentication Python sample into the Lambda function code.

   For more information about the sample and the sample code, see [Connecting to Amazon Neptune databases using IAM authentication with Python](iam-auth-connecting-python.md).

## Setting Up Amazon EC2 for Neptune IAM Authentication
<a name="iam-auth-temporary-credentials-ec2"></a>

Amazon EC2 allows you to use instance profiles to automatically provide credentials. For more information, see [Using Instance Profiles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2_instance-profiles.html) in the *IAM User Guide*.

First you add a trust relationship that grants permission to assume the role to the Amazon EC2 service.

Add the following trust relationship to the Neptune IAM authentication role. If you don't have a Neptune IAM authentication role, see [Using different kinds of IAM policies for controlling access to Neptune](security-iam-access-manage.md#iam-auth-policy).

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

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
```

------

For information about adding the trust relationship to the role, see [Editing the Trust Relationship for an Existing Role](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/edit_trust.html) in the *AWS Directory Service Administration Guide*.

If the Neptune policy is not yet attached to a role, create a new role. Attach the Neptune IAM authentication policy, and then add the trust policy. For information about creating a new role, see [Creating a New Role](https://docs.aws.amazon.com/directoryservice/latest/admin-guide/create_role.html) in the *AWS Directory Service Administration Guide*.

**To use a script to get the credentials**

1. Run the following command to install the **jq** command. The script uses this command to parse the output of the **curl** command.

   ```
   sudo yum -y install jq
   ```

1. Create a file named `credentials.sh` in a text editor and add the following text. Replace the service Region with your own value.

   ```
   TOKEN=$( curl -X PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600" )
   role_name=$( curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/ )
   creds_json=$( curl -H "X-aws-ec2-metadata-token: $TOKEN" http://169.254.169.254/latest/meta-data/iam/security-credentials/${role_name} )
   
   export AWS_ACCESS_KEY_ID=$(echo "$creds_json" | jq .AccessKeyId |tr -d '"')
   export AWS_SECRET_ACCESS_KEY=$(echo "$creds_json" | jq .SecretAccessKey| tr -d '"')
   export AWS_SESSION_TOKEN=$(echo "$creds_json" | jq .Token|tr -d '"')
   
   export SERVICE_REGION=us-east-1 or us-east-2 or us-west-1 or us-west-2 or ca-central-1 or
                         ca-west-1 or sa-east-1 or eu-north-1 or eu-south-2 or eu-west-1 or eu-west-2 or eu-west-3 or
                         eu-central-1 or me-south-1 or me-central-1 or il-central-1 or af-south-1 or ap-east-1 or
                         ap-northeast-1 or ap-northeast-2 or ap-northeast-3 or ap-southeast-1 or ap-southeast-2 or
                         ap-southeast-3 or ap-southeast-4 or ap-southeast-5 or ap-south-1 or ap-south-2 or
                         cn-north-1 or cn-northwest-1 or
                         us-gov-east-1 or us-gov-west-1
   ```

1. Run the script in the `bash` shell using the `source` command:

   ```
   source credentials.sh
   ```

   Even better is to add the commands in this script to the `.bashrc` file on your EC2 instance so that they will be invoked automatically when you log in, making temporary credentials available to the Gremlin console.

1. Connect using one of the following methods.
   + [Connecting to Amazon Neptune databases using IAM authentication with Gremlin console](iam-auth-connecting-gremlin-console.md)
   + [Connecting to Amazon Neptune databases using IAM with Gremlin Java](iam-auth-connecting-gremlin-java.md)
   + [Connecting to Amazon Neptune databases using IAM authentication with Java and SPARQL](iam-auth-connecting-sparql-java.md)
   + [Connecting to Amazon Neptune databases using IAM authentication with Python](iam-auth-connecting-python.md)

# Logging and monitoring usage and performance in Amazon Neptune
<a name="security-monitoring"></a>

Amazon Neptune supports various methods for monitoring performance and usage:
+ **Cluster status** – Check the health of a Neptune cluster's graph database engine. For more information, see [Check the Health Status of a Neptune Instance](access-graph-status.md).
+ **Amazon CloudWatch** – Neptune automatically sends metrics to CloudWatch and also supports CloudWatch Alarms. For more information, see [Monitoring Neptune Using Amazon CloudWatch](cloudwatch.md).
+ **Audit log files** – View, download, or watch database log files using the Neptune console. For more information, see [Using Audit Logs with Amazon Neptune Clusters](auditing.md).
+ **Publishing logs to Amazon CloudWatch Logs** – You can configure a Neptune DB cluster to publish audit log data to a log group in Amazon CloudWatch Logs. With CloudWatch Logs, you can perform real-time analysis of the log data, use CloudWatch to create alarms and view metrics, and use CloudWatch Logs to store your log records in highly durable storage. For more information, see [Neptune CloudWatch Logs](cloudwatch-logs.md).
+ **AWS CloudTrail** – Neptune supports API logging using CloudTrail. For more information, see [Logging Amazon Neptune API Calls with AWS CloudTrail](cloudtrail.md).
+ **Tagging** – Use tags to add metadata to your Neptune resources and track usage based on tags. For more information, see [Tagging Amazon Neptune resources](tagging.md).

# Amazon Neptune and interface VPC endpoints (AWS PrivateLink)
<a name="vpc-interface-endpoints"></a>

You can use [AWS PrivateLink](https://aws.amazon.com/privatelink/) to create a private connection between your VPC and Amazon Neptune API endpoints. You can access Amazon Neptune API operations as though they were in your VPC, without the use of an internet gateway, NAT device, VPN connection, or connection. Traffic between your VPC and Amazon Neptune stays within the Amazon network.

Amazon Neptune shares API infrastructure with Amazon Relational Database Service. To set up interface VPC endpoints for Amazon Neptune, follow the instructions in [Amazon RDS API and interface VPC endpoints (AWS PrivateLink)](https://docs.aws.amazon.com/AmazonRDS/latest/AuroraUserGuide/vpc-interface-endpoints.html) in the *Amazon Aurora User Guide*.

# Compliance considerations for Amazon Neptune
<a name="neptune-compliance"></a>

To learn whether an AWS service is within the scope of specific compliance programs, see [AWS services in Scope by Compliance Program](https://aws.amazon.com/compliance/services-in-scope/) and choose the compliance program that you are interested in. For general information, see [AWS Compliance Programs](https://aws.amazon.com/compliance/programs/).

You can download third-party audit reports using AWS Artifact. For more information, see [Downloading Reports in AWS Artifact](https://docs.aws.amazon.com/artifact/latest/ug/downloading-documents.html).

Your compliance responsibility when using AWS services is determined by the sensitivity of your data, your company's compliance objectives, and applicable laws and regulations. For more information about your compliance responsibility when using AWS services, see [AWS Security Documentation](https://docs.aws.amazon.com/security/).

# Building resilient and disaster-tolerant Amazon Neptune deployments
<a name="disaster-recovery-resiliency"></a>

The AWS global infrastructure is built around AWS Regions and Availability Zones. AWS Regions provide multiple physically separated and isolated Availability Zones, which are connected with low-latency, high-throughput, and highly redundant networking. With Availability Zones, you can design and operate applications and databases that automatically fail over between Availability Zones without interruption. Availability Zones are more highly available, fault tolerant, and scalable than traditional single or multiple data center infrastructures. 

An Amazon Neptune DB cluster can only be created in an Amazon VPC that has at least two subnets in at least two Availability Zones. By distributing your cluster instances across at least two Availability Zones, Neptune helps ensure that there are instances available in your DB cluster in the unlikely event of an Availability Zone failure. The cluster volume for your Neptune DB cluster always spans three Availability Zones to provide durable storage with less possibility of data loss.

For more information about AWS Regions and Availability Zones, see [AWS Global Infrastructure](https://aws.amazon.com/about-aws/global-infrastructure/).