

# Getting started with Amazon RDS
<a name="CHAP_GettingStarted"></a>

In the following examples, you can find how to create and connect to a DB instance using Amazon Relational Database Service (Amazon RDS). You can create a DB instance that uses Db2, MariaDB, MySQL, Microsoft SQL Server, Oracle, or PostgreSQL.

**Important**  
Before you can create or connect to a DB instance, make sure to complete the tasks in [Setting up your Amazon RDS environment](CHAP_SettingUp.md).

Creating a DB instance and connecting to a database on a DB instance is slightly different for each of the DB engines. Choose one of the following DB engines that you want to use for detailed information on creating and connecting to the DB instance. After you have created and connected to your DB instance, there are instructions to help you delete the DB instance.

**Topics**
+ [

# Creating and connecting to a MariaDB DB instance
](CHAP_GettingStarted.CreatingConnecting.MariaDB.md)
+ [

# Creating and connecting to a Microsoft SQL Server DB instance
](CHAP_GettingStarted.CreatingConnecting.SQLServer.md)
+ [

# Creating and connecting to a MySQL DB instance
](CHAP_GettingStarted.CreatingConnecting.MySQL.md)
+ [

# Creating and connecting to an Oracle DB instance
](CHAP_GettingStarted.CreatingConnecting.Oracle.md)
+ [

# Creating and connecting to a PostgreSQL DB instance
](CHAP_GettingStarted.CreatingConnecting.PostgreSQL.md)
+ [

# Tutorial: Create a web server and an Amazon RDS DB instance
](TUT_WebAppWithRDS.md)
+ [

# Tutorial: Using a Lambda function to access an Amazon RDS database
](rds-lambda-tutorial.md)

# Creating and connecting to a MariaDB DB instance
<a name="CHAP_GettingStarted.CreatingConnecting.MariaDB"></a>

This tutorial creates an EC2 instance and an RDS for MariaDB DB instance. The tutorial shows you how to access the DB instance from the EC2 instance using a standard MySQL client. As a best practice, this tutorial creates a private DB instance in a virtual private cloud (VPC). In most cases, other resources in the same VPC, such as EC2 instances, can access the DB instance, but resources outside of the VPC can't access it.

After you complete the tutorial, there is a public and private subnet in each Availability Zone in your VPC. In one Availability Zone, the EC2 instance is in the public subnet, and the DB instance is in the private subnet.

**Important**  
There's no charge for creating an AWS account. However, by completing this tutorial, you might incur costs for the resources you use. You can delete these resources after you complete the tutorial if they are no longer needed.

The following diagram shows the configuration when the tutorial is complete.

![\[EC2 instance and MariaDB DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-mariadb.png)


This tutorial allows you to create your resources by using one of the following methods:

1. Use the AWS Management Console ‐ [Create an EC2 instance](#CHAP_GettingStarted.Creating.MariaDB.EC2) and [Create a MariaDB DB instance](#CHAP_GettingStarted.Creating.MariaDB) 

1. Use CloudFormation to create the database instance and EC2 instance ‐ [(Optional) Create VPC, EC2 instance, and MariaDB instance using CloudFormation](#CHAP_GettingStarted.CFN.MariaDB) 

The first method uses **Easy create** to create a private MariaDB DB instance with the AWS Management Console. Here, you specify only the DB engine type, DB instance size, and DB instance identifier. **Easy create** uses the default settings for the other configuration options. 

When you use **Standard create** instead, you can specify more configuration options when you create a DB instance. These options include settings for availability, security, backups, and maintenance. To create a public DB instance, you must use **Standard create**. For information, see [Creating an Amazon RDS DB instance](USER_CreateDBInstance.md).

**Topics**
+ [

## Prerequisites
](#CHAP_GettingStarted.Prerequisites.MariaDB)
+ [

## Create an EC2 instance
](#CHAP_GettingStarted.Creating.MariaDB.EC2)
+ [

## Create a MariaDB DB instance
](#CHAP_GettingStarted.Creating.MariaDB)
+ [

## (Optional) Create VPC, EC2 instance, and MariaDB instance using CloudFormation
](#CHAP_GettingStarted.CFN.MariaDB)
+ [

## Connect to a MariaDB DB instance
](#CHAP_GettingStarted.Connecting.MariaDB)
+ [

## Delete the EC2 instance and DB instance
](#CHAP_GettingStarted.Deleting.MariaDB)
+ [

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
](#CHAP_GettingStarted.DeletingCFN.MariaDB)
+ [

## (Optional) Connect your DB instance to a Lambda function
](#CHAP_GettingStarted.ComputeConnect.MariaDB)

## Prerequisites
<a name="CHAP_GettingStarted.Prerequisites.MariaDB"></a>

Before you begin, complete the steps in the following sections:
+ [Sign up for an AWS account](CHAP_SettingUp.md#sign-up-for-aws)
+ [Create a user with administrative access](CHAP_SettingUp.md#create-an-admin)

## Create an EC2 instance
<a name="CHAP_GettingStarted.Creating.MariaDB.EC2"></a>

Create an Amazon EC2 instance that you will use to connect to your database.

**To create an EC2 instance**

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

1. In the upper-right corner of the AWS Management Console, choose the AWS Region in which you want to create the EC2 instance.

1. Choose **EC2 Dashboard**, and then choose **Launch instance**, as shown in the following image.  
![\[EC2 Dashboard.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_11.png)

   The **Launch an instance** page opens.

1. Choose the following settings on the **Launch an instance** page.

   1. Under **Name and tags**, for **Name**, enter **ec2-database-connect**.

   1. Under **Application and OS Images (Amazon Machine Image)**, choose **Amazon Linux**, and then choose the **Amazon Linux 2023 AMI**. Keep the default selections for the other choices.  
![\[Choose an Amazon Machine Image.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_12.png)

   1. Under **Instance type**, choose **t2.micro**.

   1. Under **Key pair (login)**, choose a **Key pair name** to use an existing key pair. To create a new key pair for the Amazon EC2 instance, choose **Create new key pair** and then use the **Create key pair** window to create it.

      For more information about creating a new key pair, see [Create a key pair](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html#create-a-key-pair) in the *Amazon EC2 User Guide*.

   1. For **Allow SSH traffic** in **Network settings**, choose the source of SSH connections to the EC2 instance. 

      You can choose **My IP** if the displayed IP address is correct for SSH connections. Otherwise, you can determine the IP address to use to connect to EC2 instances in your VPC using Secure Shell (SSH). To determine your public IP address, in a different browser window or tab, you can use the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com/). An example of an IP address is 192.0.2.1/32.

       In many cases, you might connect through an internet service provider (ISP) or from behind your firewall without a static IP address. If so, make sure to determine the range of IP addresses used by client computers.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public EC2 instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using SSH.

      The following image shows an example of the **Network settings** section.  
![\[Network settings for an EC2 instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Connect_NtwkSettings.png)

   1. Leave the default values for the remaining sections.

   1. Review a summary of your EC2 instance configuration in the **Summary** panel, and when you're ready, choose **Launch instance**.

1. On the **Launch Status** page, note the identifier for your new EC2 instance, for example: `i-1234567890abcdef0`.  
![\[EC2 instance identifier on Launch Status page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-ec2-id.png)

1. Choose the EC2 instance identifier to open the list of EC2 instances, and then select your EC2 instance.

1. In the **Details** tab, note the following values, which you need when you connect using SSH:

   1. In **Instance summary**, note the value for **Public IPv4 DNS**.  
![\[EC2 public DNS name on Details tab of Instances page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-public-dns.png)

   1. In **Instance details**, note the value for **Key pair name**.  
![\[EC2 key pair name on Details tab of Instance page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-key-pair.png)

1. Wait until the **Instance state** for your EC2 instance has a status of **Running** before continuing.

## Create a MariaDB DB instance
<a name="CHAP_GettingStarted.Creating.MariaDB"></a>

The basic building block of Amazon RDS is the DB instance. This environment is where you run your MariaDB databases.

In this example, you use **Easy create** to create a DB instance running the MariaDB database engine with a db.t4g.micro DB instance class.

**To create a MariaDB DB instance with Easy create**

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

1. In the upper-right corner of the Amazon RDS console, choose the AWS Region in which you want to create the DB instance.

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

1. Choose **Create database** and select **Easy create**.   
![\[Easy create option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-option.png)

1. In **Configuration**, choose **MariaDB**.

1. For **DB instance size**, choose **Free tier** or **Sandbox**. **Free tier** appears for free plan accounts. **Sandbox** appears for paid plan accounts.

1. For **DB instance identifier**, enter **database-test1**.

1. For **Master username**, enter a name for the master user, or keep the default name.

   The **Create database** page should look similar to the following image. For free plan accounts, **Free tier **appears. For paid plan accounts, **Sandbox** appears.  
![\[Create database page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-mariadb.png)

1. To use an automatically generated master password for the DB instance, select **Auto generate a password**.

   To enter your master password, clear **Auto generate a password**, and then enter the same password in **Master password** and **Confirm master password**.

1. To set up a connection with the EC2 instance you created previously, expand **Set up EC2 connection - *optional***.

   Select **Connect to an EC2 compute resource**. Choose the EC2 instance you created previously.  
![\[Set up EC2 connection option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Setup_Conn-EasyCreate.png)

1. Expand **View default settings for Easy create**.   
![\[Easy create default settings.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-view-default-maria.png)

   You can examine the default settings used with **Easy create**. The **Editable after database is created** column shows which options you can change after you create the database.
   + If a setting has **No** in that column, and you want a different setting, you can use **Standard create** to create the DB instance.
   + If a setting has **Yes** in that column, and you want a different setting, you can either use **Standard create** to create the DB instance, or modify the DB instance after you create it to change the setting.

1. Choose **Create database**.

   To view the master username and password for the DB instance, choose **View credential details**.

   You can use the username and password that appears to connect to the DB instance as the master user.
**Important**  
You can't view the master user password again. If you don't record it, you might have to change it.   
If you need to change the master user password after the DB instance is available, you can modify the DB instance to do so. For more information about modifying a DB instance, see [Modifying an Amazon RDS DB instance](Overview.DBInstance.Modifying.md).

1. In the **Databases** list, choose the name of the new MariaDB DB instance to show its details.

   The DB instance has a status of **Creating** until it is ready to use.  
![\[DB instance details.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/MariaDB-Launch06.png)

   When the status changes to **Available**, you can connect to the DB instance. Depending on the DB instance class and the amount of storage, it can take up to 20 minutes before the new instance is available.

## (Optional) Create VPC, EC2 instance, and MariaDB instance using CloudFormation
<a name="CHAP_GettingStarted.CFN.MariaDB"></a>

Instead of using the console to create your VPC, EC2 instance, and MariaDB instance, you can use CloudFormation to provision AWS resources by treating infrastructure as code. To help you organize your AWS resources into smaller and more manageable units, you can use the CloudFormation nested stack functionality. For more information, see [ Creating a stack on the CloudFormation console](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html) and [Working with nested stacks](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html). 

**Important**  
CloudFormation is free, but the resources that CloudFormation creates are live. You incur the standard usage fees for these resources until you terminate them. For more information, see [RDS for MariaDB pricing](https://aws.amazon.com//rds/mariadb/pricing).
+ Download the CloudFormation template
+ Configure your resources using CloudFormation

### Download the CloudFormation template
<a name="CHAP_GettingStarted.CFN.MariaDB.Step1"></a>

A CloudFormation template is a JSON or YAML text file that contains the configuration information about the resources you want to create in the stack. This template also creates a VPC and a bastion host for you along with the RDS instance.

To download the template file, open the following link, [MariaDB CloudFormation template](https://github.com/aws-ia/cfn-ps-amazon-rds/blob/main/templates/rds-mariadb-main.template.yaml).

In the Github page, click the *Download raw file* button to save the template YAML file.

### Configure your resources using CloudFormation
<a name="CHAP_GettingStarted.CFN.MariabDB.Step2"></a>

**Note**  
Before starting this process, make sure you have a Key pair for an EC2 instance in your AWS account. For more information, see [Amazon EC2 key pairs and Linux instances](https://docs.aws.amazon.com//AWSEC2/latest/UserGuide/ec2-key-pairs.html).

When you use the CloudFormation template, you must select the correct parameters to make sure your resources are created properly. Follow the steps below:

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

1. Choose **Create Stack**.

1. In the Specify template section, select **Upload a template file from your computer**, and then choose **Next**.

1. In the **Specify stack details** page, set the following parameters:

   1. Set **Stack name** to **MariaDBTestStack**.

   1. Under **Parameters**, set **Availability Zones** by selecting three availability zones.

   1. Under **Linux Bastion Host configuration**, for **Key Name**, select a key pair to login to your EC2 instance.

   1. In **Linux Bastion Host configuration** settings, set the **Permitted IP range** to your IP address. To connect to EC2 instances in your VPC using Secure Shell (SSH), determine your public IP address using the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com). An example of an IP address is 192.0.2.1/32.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public EC2 instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using SSH.

   1. Under **Database General configuration**, set **Database instance class** to **db.t3.micro**.

   1. Set **Database name** to **database-test1**.

   1. For **Database master username**, enter a name for the master user.

   1. Set **Manage DB master user password with Secrets Manager** to `false` for this tutorial.

   1. For **Database password**, set a password of your choice. Remember this password for further steps in the tutorial.

   1. Under **Database Storage configuration**, set **Database storage type** to **gp2**.

   1. Under **Database Monitoring configuration**, set **Enable RDS Performance Insights** to false.

   1. Leave all other settings as the default values. Click **Next** to continue.

1. In the **Review stack** page, select **Submit** after checking the database and Linux bastion host options.

After the stack creation process completes, view the stacks with names *BastionStack* and *RDSNS* to note the information you need to connect to the database. For more information, see [ Viewing CloudFormation stack data and resources on the AWS Management Console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-view-stack-data-resources.html).

## Connect to a MariaDB DB instance
<a name="CHAP_GettingStarted.Connecting.MariaDB"></a>

You can use any standard SQL client application to connect to the DB instance. In this example, you connect to a MariaDB DB instance using the mysql command-line client.

**To connect to a MariaDB DB instance**

1. Find the endpoint (DNS name) and port number for your DB instance. 

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

   1. In the upper-right corner of the Amazon RDS console, choose the AWS Region for the DB instance.

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

   1. Choose the MariaDB DB instance name to display its details. 

   1. On the **Connectivity & security** tab, copy the endpoint. Also note the port number. You need both the endpoint and the port number to connect to the DB instance.   
![\[Connect to a MariaDB DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/MariaDBConnect1.png)

1. Connect to the EC2 instance that you created earlier by following the steps in [Connect to your Linux instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html) in the *Amazon EC2 User Guide*.

   We recommend that you connect to your EC2 instance using SSH. If the SSH client utility is installed on Windows, Linux, or Mac, you can connect to the instance using the following command format:

   ```
   ssh -i location_of_pem_file ec2-user@ec2-instance-public-dns-name
   ```

   For example, assume that `ec2-database-connect-key-pair.pem` is stored in `/dir1` on Linux, and the public IPv4 DNS for your EC2 instance is `ec2-12-345-678-90.compute-1.amazonaws.com`. Your SSH command would look as follows:

   ```
   ssh -i /dir1/ec2-database-connect-key-pair.pem ec2-user@ec2-12-345-678-90.compute-1.amazonaws.com
   ```

1. Get the latest bug fixes and security updates by updating the software on your EC2 instance. To do this, use the following command.
**Note**  
The `-y` option installs the updates without asking for confirmation. To examine updates before installing, omit this option.

   ```
   sudo dnf update -y
   ```

1. Install the mysql command-line client from MariaDB.

   To install the MariaDB command-line client on Amazon Linux 2023, run the following command:

   ```
   sudo dnf install mariadb105
   ```

1. Connect to the MariaDB DB instance. For example, enter the following command. This action lets you connect to the MariaDB DB instance using the MySQL client.

   Substitute the DB instance endpoint (DNS name) for `endpoint`, and substitute the master username that you used for `admin`. Provide the master password that you used when prompted for a password.

   ```
   mysql -h endpoint -P 3306 -u admin -p
   ```

   After you enter the password for the user, you should see output similar to the following.

   ```
   Welcome to the MariaDB monitor.  Commands end with ; or \g.
   Your MariaDB connection id is 156
   Server version: 10.6.10-MariaDB-log managed by https://aws.amazon.com/rds/
    
   Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
     
   Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
     
   MariaDB [(none)]>
   ```

   For more information about connecting to a MariaDB DB instance, see [Connecting to your MariaDB DB instance](USER_ConnectToMariaDBInstance.md). If you can't connect to your DB instance, see [Can't connect to Amazon RDS DB instance](CHAP_Troubleshooting.md#CHAP_Troubleshooting.Connecting).

   For security, it is a best practice to use encrypted connections. Only use an unencrypted MariaDB connection when the client and server are in the same VPC and the network is trusted. For information about using encrypted connections, see [Connecting to your MariaDB DB instance on Amazon RDS with SSL/TLS from the MySQL command-line client (encrypted)](USER_ConnectToMariaDBInstanceSSL.CLI.md).

1. Run SQL commands.

   For example, the following SQL command shows the current date and time:

   ```
   SELECT CURRENT_TIMESTAMP;
   ```

## Delete the EC2 instance and DB instance
<a name="CHAP_GettingStarted.Deleting.MariaDB"></a>

After you connect to and explore the sample EC2 instance and DB instance that you created, delete them so you're no longer charged for them.

If you used CloudFormation to create resources, skip this step and go to the next step.

**To delete the EC2 instance**

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

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

1. Select the EC2 instance, and choose **Instance state, Terminate instance**.

1. Choose **Terminate** when prompted for confirmation.

For more information about deleting an EC2 instance, see [Terminate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html) in the *Amazon EC2 User Guide*.

**To delete the DB instance with no final DB snapshot**

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

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

1. Choose the DB instance you want to delete.

1. For **Actions**, choose **Delete**.

1. Clear **Create final snapshot?** and **Retain automated backups**.

1. Complete the acknowledgement and choose **Delete**.

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
<a name="CHAP_GettingStarted.DeletingCFN.MariaDB"></a>

If you used CloudFormation to create resources, delete the CloudFormation stack after you connect to and explore the sample EC2 instance and DB instance, so you're no longer charged for them.

**To delete the CloudFormation resources**

1. Open the CloudFormation console.

1. On the **Stacks** page in the CloudFormation console, select the root stack (the stack without the name VPCStack, BastionStack or RDSNS).

1. Choose **Delete**.

1. Select **Delete stack** when prompted for confirmation.

For more information about deleting a stack in CloudFormation, see [Deleting a stack on the CloudFormation console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html) in the *AWS CloudFormation User Guide*.

## (Optional) Connect your DB instance to a Lambda function
<a name="CHAP_GettingStarted.ComputeConnect.MariaDB"></a>

You can also connect your RDS for MariaDB DB instance to a Lambda serverless compute resource. Lambda functions allow you to run code without provisioning or managing infrastructure. A Lambda function also allows you to automatically respond to code execution requests at any scale, from a dozen events a day to hundreds of per second. For more information, see [Automatically connecting a Lambda function and a DB instance](lambda-rds-connect.md).

# Creating and connecting to a Microsoft SQL Server DB instance
<a name="CHAP_GettingStarted.CreatingConnecting.SQLServer"></a>

This tutorial creates an EC2 instance and an RDS for Microsoft SQL Server DB instance. The tutorial shows you how to access the DB instance from the EC2 instance using the Microsoft SQL Server Management Studio client. As a best practice, this tutorial creates a private DB instance in a virtual private cloud (VPC). In most cases, other resources in the same VPC, such as EC2 instances, can access the DB instance, but resources outside of the VPC can't access it. 

After you complete the tutorial, there is a public and private subnet in each Availability Zone in your VPC. In one Availability Zone, the EC2 instance is in the public subnet, and the DB instance is in the private subnet.

**Important**  
There's no charge for creating an AWS account. However, by completing this tutorial, you might incur costs for the AWS resources you use. You can delete these resources after you complete the tutorial if they are no longer needed.

The following diagram shows the configuration when the tutorial is complete.

![\[EC2 instance and Microsoft SQL Server DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-sqlserver.png)


This tutorial allows you to create your resources by using one of the following methods:

1. Use the AWS Management Console ‐ [Create a SQL Server DB instance](#CHAP_GettingStarted.Creating.SQLServer) and [Create an EC2 instance](#CHAP_GettingStarted.Creating.SQLServer.EC2)

1. Use CloudFormation to create the database instance and EC2 instance ‐ [(Optional) Create VPC, EC2 instance, and SQL Server instance using CloudFormation](#CHAP_GettingStarted.CFN.SQLServer) 

The first method uses **Easy create** to create a private SQL Server DB instance with the AWS Management Console. Here, you specify only the DB engine type, DB instance size, and DB instance identifier. **Easy create** uses the default settings for the other configuration options. 

When you use **Standard create** instead, you can specify more configuration options when you create a DB instance. These options include settings for availability, security, backups, and maintenance. To create a public DB instance, you must use **Standard create**. For information, see [Creating an Amazon RDS DB instance](USER_CreateDBInstance.md).

**Topics**
+ [

## Prerequisites
](#CHAP_GettingStarted.Prerequisites.SQLServer)
+ [

## Create an EC2 instance
](#CHAP_GettingStarted.Creating.SQLServer.EC2)
+ [

## Create a SQL Server DB instance
](#CHAP_GettingStarted.Creating.SQLServer)
+ [

## (Optional) Create VPC, EC2 instance, and SQL Server instance using CloudFormation
](#CHAP_GettingStarted.CFN.SQLServer)
+ [

## Connect to your SQL Server DB instance
](#CHAP_GettingStarted.Connecting.SQLServer)
+ [

## Explore your sample SQL Server DB instance
](#CHAP_GettingStarted.SQLServer.Exploring)
+ [

## Delete the EC2 instance and DB instance
](#CHAP_GettingStarted.Deleting.SQLServer)
+ [

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
](#CHAP_GettingStarted.DeletingCFN.SQLServer)
+ [

## (Optional) Connect your DB instance to a Lambda function
](#CHAP_GettingStarted.ComputeConnect.SQLServer)

## Prerequisites
<a name="CHAP_GettingStarted.Prerequisites.SQLServer"></a>

Before you begin, complete the steps in the following sections:
+ [Sign up for an AWS account](CHAP_SettingUp.md#sign-up-for-aws)
+ [Create a user with administrative access](CHAP_SettingUp.md#create-an-admin)

## Create an EC2 instance
<a name="CHAP_GettingStarted.Creating.SQLServer.EC2"></a>

Create an Amazon EC2 instance that you will use to connect to your database.

**To create an EC2 instance**

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

1. In the upper-right corner of the AWS Management Console, choose the AWS Region you used for the database previously.

1. Choose **EC2 Dashboard**, and then choose **Launch instance**, as shown in the following image.  
![\[EC2 Dashboard.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_11.png)

   The **Launch an instance** page opens.

1. Choose the following settings on the **Launch an instance** page.

   1. Under **Name and tags**, for **Name**, enter **ec2-database-connect**.

   1. Under **Application and OS Images (Amazon Machine Image)**, choose **Windows**, and then choose the **Microsoft Windows Server 2022 Base**. Keep the default selections for the other choices.  
![\[Choose an Amazon Machine Image.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/tutorial_ec2_sqlserver_create1.png)

   1. Under **Instance type**, choose **t2.micro**.

   1. Under **Key pair (login)**, choose a **Key pair name** to use an existing key pair. To create a new key pair for the Amazon EC2 instance, choose **Create new key pair** and then use the **Create key pair** window to create it.

      For more information about creating a new key pair, see [Create a key pair](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/ec2-key-pairs.html) in the *Amazon EC2 User Guide for Windows Instances*.

   1. For **Firewall (security groups)** in **Network settings**, choose **Allow RDP traffic from** to connect to the EC2 instance. 

      You can choose **My IP** if the displayed IP address is correct for RDP connections. Otherwise, you can determine the IP address to use to connect to EC2 instances in your VPC using RDP. To determine your public IP address, in a different browser window or tab, you can use the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com/). An example of an IP address is 192.0.2.1/32.

       In many cases, you might connect through an internet service provider (ISP) or from behind your firewall without a static IP address. If so, make sure to determine the range of IP addresses used by client computers.
**Warning**  
If you use `0.0.0.0/0` for RDP access, you make it possible for all IP addresses to access your public EC2 instances using RDP. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using RDP.

      The following image shows an example of the **Network settings** section.  
![\[Network settings for an EC2 instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Connect_NtwkSettingsRDSMS.png)

   1. Keep the default values for the remaining sections.

   1. Review a summary of your EC2 instance configuration in the **Summary** panel, and when you're ready, choose **Launch instance**.

1. On the **Launch Status** page, note the identifier for your new EC2 instance, for example: `i-1234567890abcdef0`.  
![\[EC2 instance identifier on Launch Status page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-ec2-id.png)

1. Choose the EC2 instance identifier to open the list of EC2 instances. 

1. Wait until the **Instance state** for your EC2 instance has a status of **Running** before continuing.

## Create a SQL Server DB instance
<a name="CHAP_GettingStarted.Creating.SQLServer"></a>

The basic building block of Amazon RDS is the DB instance. This environment is where you run your SQL Server databases.

In this example, you use **Easy create** to create a DB instance running the SQL Server database engine with a db.t2.micro DB instance class.

**To create a Microsoft SQL Server DB instance with Easy create**

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

1. In the upper-right corner of the Amazon RDS console, choose the AWS Region in which you want to create the DB instance.

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

1. Choose **Create database** and make sure that **Easy create** is chosen.   
![\[Easy create option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-option.png)

1. In **Configuration**, choose **Microsoft SQL Server**.

1. For **Edition**, choose **SQL Server Express Edition**.

1. For **DB instance size**, choose **Free tier**. **Free tier** appears for free plan accounts. **Sandbox** appears for paid plan accounts.

1. For **DB instance identifier**, enter **database-test1**.

   The **Create database** page should look similar to the following image. For free plan accounts, **Free tier **appears. For paid plan accounts, **Sandbox** appears.  
![\[Engine options\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-sqlserver.png)

1. For **Master username**, enter a name for the master user, or keep the default name.

1. To set up a connection with the EC2 instance you created previously, open **Set up EC2 connection - *optional***.

   Select **Connect to an EC2 compute resource**. Choose the EC2 instance you created previously.  
![\[Set up EC2 connection option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Setup_Conn-EasyCreate.png)

1. To use an automatically generated master password for the DB instance, select the **Auto generate a password** box.

   To enter your master password, clear the **Auto generate a password** box, and then enter the same password in **Master password** and **Confirm password**.

1. Open **View default settings for Easy create**.  
![\[Easy create default settings.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-sqlserver-confirm.png)

   You can examine the default settings used with **Easy create**. The **Editable after database is created** column shows which options you can change after you create the database.
   + If a setting has **No** in that column, and you want a different setting, you can use **Standard create** to create the DB instance.
   + If a setting has **Yes** in that column, and you want a different setting, you can either use **Standard create** to create the DB instance, or modify the DB instance after you create it to change the setting.

1. Choose **Create database**.

   To view the master username and password for the DB instance, choose **View credential details**.

   You can use the username and password that appears to connect to the DB instance as the master user.
**Important**  
You can't view the master user password again. If you don't record it, you might have to change it.   
If you need to change the master user password after the DB instance is available, you can modify the DB instance to do so. For more information about modifying a DB instance, see [Modifying an Amazon RDS DB instance](Overview.DBInstance.Modifying.md).

1. In the **Databases** list, choose the name of the new SQL Server DB instance to show its details.

   The DB instance has a status of **Creating** until it is ready to use.  
![\[Screen capture of the DB instance details.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-sqlserver-launch.png)

   When the status changes to **Available**, you can connect to the DB instance. Depending on the DB instance class and the amount of storage, it can take up to 20 minutes before the new instance is available.

## (Optional) Create VPC, EC2 instance, and SQL Server instance using CloudFormation
<a name="CHAP_GettingStarted.CFN.SQLServer"></a>

Instead of using the console to create your VPC, EC2 instance, and SQL Server instance, you can use CloudFormation to provision AWS resources by treating infrastructure as code. To help you organize your AWS resources into smaller and more manageable units, you can use the CloudFormation nested stack functionality. For more information, see [ Creating a stack on the CloudFormation console](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html) and [Working with nested stacks](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html).. 

**Important**  
CloudFormation is free, but the resources that CloudFormation creates are live. You incur the standard usage fees for these resources until you terminate them. For more information, see [RDS for SQL Server pricing](https://aws.amazon.com//rds/sqlserver/pricing).

To create your resources using the CloudFormation console, complete the following steps:
+ Download the CloudFormation template
+ Configure your resources using CloudFormation

### Download the CloudFormation template
<a name="CHAP_GettingStarted.CFN.SQLServer.Step1"></a>

A CloudFormation template is a JSON or YAML text file that contains the configuration information about the resources you want to create in the stack. This template also creates a VPC and a bastion host for you along with the RDS instance.

To download the template file, open the following link, [SQL Server CloudFormation template](https://github.com/aws-ia/cfn-ps-amazon-rds/blob/main/templates/rds-sqlserver-main.template.yaml).

In the Github page, click the *Download raw file* button to save the template YAML file.

### Configure your resources using CloudFormation
<a name="CHAP_GettingStarted.CFN.SQLServer.Step2"></a>

**Note**  
Before starting this process, make sure you have a Key pair for an EC2 instance in your AWS account. For more information, see [Amazon EC2 key pairs and Linux instances](https://docs.aws.amazon.com//AWSEC2/latest/UserGuide/ec2-key-pairs.html).

When you use the CloudFormation template, you must select the correct parameters to make sure your resources are created properly. Follow the steps below:

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

1. Choose **Create Stack**.

1. In the Specify template section, select **Upload a template file from your computer**, and then choose **Next**.

1. In the **Specify stack details** page, set the following parameters:

   1. Set **Stack name** to **SQLServerTestStack**.

   1. Under **Parameters**, set **Availability Zones** by selecting three availability zones.

   1. Under **Linux Bastion Host configuration**, for **Key Name**, select a key pair to login to your EC2 instance.

   1. In **Linux Bastion Host configuration** settings, set the **Permitted IP range** to your IP address. To connect to EC2 instances in your VPC using Secure Shell (SSH), determine your public IP address using the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com). An example of an IP address is 192.0.2.1/32.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public EC2 instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using SSH.

   1. Under **Database General configuration**, set **Database instance class** to **db.t3.micro**.

   1. Set **Database name** to **database-test1**.

   1. For **Database master username**, enter a name for the master user.

   1. Set **Manage DB master user password with Secrets Manager** to `false` for this tutorial.

   1. For **Database password**, set a password of your choice. Remember this password for further steps in the tutorial.

   1. Under **Database Storage configuration**, set **Database storage type** to **gp2**.

   1. Under **Database Monitoring configuration**, set **Enable RDS Performance Insights** to false.

   1. Leave all other settings as the default values. Click **Next** to continue.

1. In the **Configure stack options** page, leave all the default options. Click **Next** to continue.

1. In the **Review stack** page, select **Submit** after checking the database and Linux bastion host options.

After the stack creation process completes, view the stacks with names *BastionStack* and *RDSNS* to note the information you need to connect to the database. For more information, see [ Viewing CloudFormation stack data and resources on the AWS Management Console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-view-stack-data-resources.html).

## Connect to your SQL Server DB instance
<a name="CHAP_GettingStarted.Connecting.SQLServer"></a>

In the following procedure, you connect to your DB instance by using Microsoft SQL Server Management Studio (SSMS).

**To connect to an RDS for SQL Server DB instance using SSMS**

1. Find the endpoint (DNS name) and port number for your DB instance. 

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

   1. In the upper-right corner of the Amazon RDS console, choose the AWS Region for the DB instance.

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

   1. Choose the SQL Server DB instance name to display its details. 

   1. On the **Connectivity** tab, copy the endpoint. Also, note the port number. You need both the endpoint and the port number to connect to the DB instance.  
![\[Connect to a Microsoft SQL Server DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/SQLServerConnect2.png)

1. Connect to the EC2 instance that you created earlier by following the steps in [Connect to your Microsoft Windows instance](https://docs.aws.amazon.com/AWSEC2/latest/WindowsGuide/EC2_GetStarted.html#ec2-connect-to-instance-windows) in the *Amazon EC2 User Guide for Windows Instances*.

1. Install the SQL Server Management Studio (SSMS) client from Microsoft.

   To download a standalone version of SSMS to your EC2 instance, see [Download SQL Server Management Studio (SSMS)](https://docs.microsoft.com/en-us/sql/ssms/download-sql-server-management-studio-ssms) in the Microsoft documentation.

   1. Use the Start menu to open Internet Explorer.

   1. Use Internet Explorer to download and install a standalone version of SSMS. If you are prompted that the site isn't trusted, add the site to the list of trusted sites.

1. Start SQL Server Management Studio (SSMS). 

   The **Connect to Server** dialog box appears. 

1. Provide the following information for your sample DB instance: 

   1. For **Server type**, choose **Database Engine**. 

   1. For **Server name**, enter the DNS name, followed by a comma and the port number (the default port is 1433). For example, your server name should look as follows:

      ```
      database-test1.0123456789012.us-west-2.rds.amazonaws.com,1433
      ```

   1. For **Authentication**, choose **SQL Server Authentication**. 

   1. For **Login**, enter the username that you chose to use for your sample DB instance. This is also known as the master username.

   1. For **Password**, enter the password that you chose earlier for your sample DB instance. This is also known as the master user password.

1. Choose **Connect**. 

   After a few moments, SSMS connects to your DB instance. For security, it is a best practice to use encrypted connections. Only use an unencrypted SQL Server connection when the client and server are in the same VPC and the network is trusted. For information about using encrypted connections, see [Using SSL with a Microsoft SQL Server DB instance](SQLServer.Concepts.General.SSL.Using.md)

For more information about connecting to a Microsoft SQL Server DB instance, see [Connecting to your Microsoft SQL Server DB instance](USER_ConnectToMicrosoftSQLServerInstance.md).

For information about connection issues, see [Can't connect to Amazon RDS DB instance](CHAP_Troubleshooting.md#CHAP_Troubleshooting.Connecting).

## Explore your sample SQL Server DB instance
<a name="CHAP_GettingStarted.SQLServer.Exploring"></a>

You can explore your sample DB instance by using Microsoft SQL Server Management Studio (SSMS).

**To explore a DB instance using SSMS**

1. Your SQL Server DB instance comes with SQL Server's standard built-in system databases (master, model, msdb, and tempdb). To explore the system databases, do the following: 

   1. In SSMS, on the **View** menu, choose **Object Explorer**.

   1. Expand your DB instance, expand **Databases**, and then expand **System Databases** as shown.   
![\[Object Explorer displaying the system databases.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/SQL-SSMS-SystemDBs.png)

   Your SQL Server DB instance also comes with a database named `rdsadmin`. Amazon RDS uses this database to store the objects that it uses to manage your database. The `rdsadmin` database also includes stored procedures that you can run to perform advanced tasks. 

1. Start creating your own databases and running queries against your DB instance and databases as usual. To run a test query against your sample DB instance, do the following: 

   1. In SSMS, on the **File** menu, point to **New** and then choose **Query with Current Connection**. 

   1. Enter the following SQL query:

      ```
      select @@VERSION
      ```

   1. Run the query. SSMS returns the SQL Server version of your Amazon RDS DB instance.   
![\[SQL Query Window.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/SQL-Connect-Query.png)

## Delete the EC2 instance and DB instance
<a name="CHAP_GettingStarted.Deleting.SQLServer"></a>

After you connect to and explore the sample EC2 instance and DB instance that you created, delete them so you're no longer charged for them.

If you used CloudFormation to create resources, skip this step and go to the next step.

**To delete the EC2 instance**

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

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

1. Select the EC2 instance, and choose **Instance state, Terminate instance**.

1. Choose **Terminate** when prompted for confirmation.

For more information about deleting an EC2 instance, see [Terminate your instance](https://docs.aws.amazon.com//AWSEC2/latest/WindowsGuide/terminating-instances.html) in the *User Guide for Windows Instances*.

**To delete the DB instance with no final DB snapshot**

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

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

1. Choose the DB instance that you want to delete.

1. For **Actions**, choose **Delete**.

1. Clear **Create final snapshot?** and **Retain automated backups**.

1. Complete the acknowledgement and choose **Delete**. 

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
<a name="CHAP_GettingStarted.DeletingCFN.SQLServer"></a>

If you used CloudFormation to create resources, delete the CloudFormation stack after you connect to and explore the sample EC2 instance and DB instance, so you're no longer charged for them.

**To delete the CloudFormation resources**

1. Open the CloudFormation console.

1. On the **Stacks** page in the CloudFormationconsole, select the root stack (the stack without the name VPCStack, BastionStack or RDSNS).

1. Choose **Delete**.

1. Select **Delete stack** when prompted for confirmation.

For more information about deleting a stack in CloudFormation, see [Deleting a stack on the CloudFormation console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html) in the *AWS CloudFormation User Guide*.

## (Optional) Connect your DB instance to a Lambda function
<a name="CHAP_GettingStarted.ComputeConnect.SQLServer"></a>

You can also connect your RDS for SQL Server DB instance to a Lambda serverless compute resource. Lambda functions allow you to run code without provisioning or managing infrastructure. A Lambda function also allows you to automatically respond to code execution requests at any scale, from a dozen events a day to hundreds of per second. For more information, see [Automatically connecting a Lambda function and a DB instance](lambda-rds-connect.md).

# Creating and connecting to a MySQL DB instance
<a name="CHAP_GettingStarted.CreatingConnecting.MySQL"></a>

This tutorial creates an EC2 instance and an RDS for MySQL DB instance. The tutorial shows you how to access the DB instance from the EC2 instance using a standard MySQL client. As a best practice, this tutorial creates a private DB instance in a virtual private cloud (VPC). In most cases, other resources in the same VPC, such as EC2 instances, can access the DB instance, but resources outside of the VPC can't access it.

After you complete the tutorial, there is a public and private subnet in each Availability Zone in your VPC. In one Availability Zone, the EC2 instance is in the public subnet, and the DB instance is in the private subnet.

**Important**  
There's no charge for creating an AWS account. However, by completing this tutorial, you might incur costs for the AWS resources you use. You can delete these resources after you complete the tutorial if they are no longer needed.

The following diagram shows the configuration when the tutorial is complete.

![\[EC2 instance and MySQL DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-mysql.png)


This tutorial allows you to create your resources by using one of the following methods:

1. Use the AWS Management Console ‐ [Create a MySQL DB instance](#CHAP_GettingStarted.Creating.MySQL) and [Create an EC2 instance](#CHAP_GettingStarted.Creating.MySQL.EC2) 

1. Use CloudFormation to create the database instance and EC2 instance ‐ [(Optional) Create VPC, EC2 instance, and MySQL instance using CloudFormation](#CHAP_GettingStarted.CFN.MySQL) 

The first method uses **Easy create** to create a private MySQL DB instance with the AWS Management Console. Here, you specify only the DB engine type, DB instance size, and DB instance identifier. **Easy create** uses the default settings for the other configuration options.

When you use **Standard create** instead, you can specify more configuration options when you create a DB instance. These options include settings for availability, security, backups, and maintenance. To create a public DB instance, you must use **Standard create**. For information, see [Creating an Amazon RDS DB instance](USER_CreateDBInstance.md).

**Topics**
+ [

## Prerequisites
](#CHAP_GettingStarted.Prerequisites.MySQL)
+ [

## Create an EC2 instance
](#CHAP_GettingStarted.Creating.MySQL.EC2)
+ [

## Create a MySQL DB instance
](#CHAP_GettingStarted.Creating.MySQL)
+ [

## (Optional) Create VPC, EC2 instance, and MySQL instance using CloudFormation
](#CHAP_GettingStarted.CFN.MySQL)
+ [

## Connect to a MySQL DB instance
](#CHAP_GettingStarted.Connecting.MySQL)
+ [

## Delete the EC2 instance and DB instance
](#CHAP_GettingStarted.Deleting.MySQL)
+ [

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
](#CHAP_GettingStarted.DeletingCFN.MySQL)
+ [

## (Optional) Connect your DB instance to a Lambda function
](#CHAP_GettingStarted.ComputeConnect.MySQL)

## Prerequisites
<a name="CHAP_GettingStarted.Prerequisites.MySQL"></a>

Before you begin, complete the steps in the following sections:
+ [Sign up for an AWS account](CHAP_SettingUp.md#sign-up-for-aws)
+ [Create a user with administrative access](CHAP_SettingUp.md#create-an-admin)

## Create an EC2 instance
<a name="CHAP_GettingStarted.Creating.MySQL.EC2"></a>

Create an Amazon EC2 instance that you will use to connect to your database.

**To create an EC2 instance**

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

1. In the upper-right corner of the AWS Management Console, choose the AWS Region in which you want to create the EC2 instance.

1. Choose **EC2 Dashboard**, and then choose **Launch instance**, as shown in the following image.  
![\[EC2 Dashboard.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_11.png)

   The **Launch an instance** page opens.

1. Choose the following settings on the **Launch an instance** page.

   1. Under **Name and tags**, for **Name**, enter **ec2-database-connect**.

   1. Under **Application and OS Images (Amazon Machine Image)**, choose **Amazon Linux**, and then choose the **Amazon Linux 2023 AMI**. Keep the default selections for the other choices.  
![\[Choose an Amazon Machine Image.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_12.png)

   1. Under **Instance type**, choose **t2.micro**.

   1. Under **Key pair (login)**, choose a **Key pair name** to use an existing key pair. To create a new key pair for the Amazon EC2 instance, choose **Create new key pair** and then use the **Create key pair** window to create it.

      For more information about creating a new key pair, see [Create a key pair](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html#create-a-key-pair) in the *Amazon EC2 User Guide*.

   1. For **Allow SSH traffic** in **Network settings**, choose the source of SSH connections to the EC2 instance. 

      You can choose **My IP** if the displayed IP address is correct for SSH connections. Otherwise, you can determine the IP address to use to connect to EC2 instances in your VPC using Secure Shell (SSH). To determine your public IP address, in a different browser window or tab, you can use the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com/). An example of an IP address is 192.0.2.1/32.

       In many cases, you might connect through an internet service provider (ISP) or from behind your firewall without a static IP address. If so, make sure to determine the range of IP addresses used by client computers.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public EC2 instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using SSH.

      The following image shows an example of the **Network settings** section.  
![\[Network settings for an EC2 instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Connect_NtwkSettings.png)

   1. Leave the default values for the remaining sections.

   1. Review a summary of your EC2 instance configuration in the **Summary** panel, and when you're ready, choose **Launch instance**.

1. On the **Launch Status** page, note the identifier for your new EC2 instance, for example: `i-1234567890abcdef0`.  
![\[EC2 instance identifier on Launch Status page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-ec2-id.png)

1. Choose the EC2 instance identifier to open the list of EC2 instances, and then select your EC2 instance.

1. In the **Details** tab, note the following values, which you need when you connect using SSH:

   1. In **Instance summary**, note the value for **Public IPv4 DNS**.  
![\[EC2 public DNS name on Details tab of Instances page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-public-dns.png)

   1. In **Instance details**, note the value for **Key pair name**.  
![\[EC2 key pair name on Details tab of Instance page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-key-pair.png)

1. Wait until the **Instance state** for your EC2 instance has a status of **Running** before continuing.

## Create a MySQL DB instance
<a name="CHAP_GettingStarted.Creating.MySQL"></a>

The basic building block of Amazon RDS is the DB instance. This environment is where you run your MySQL databases.

In this example, you use **Easy create** to create a DB instance running the MySQL database engine with a db.t3.micro DB instance class.

**To create a MySQL DB instance with Easy create**

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

1. In the upper-right corner of the Amazon RDS console, choose the AWS Region you used for the EC2 instance previously.

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

1. Choose **Create database** and make sure that **Easy create** is chosen.   
![\[Easy create option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-option.png)

1. In **Configuration**, choose **MySQL**.

1. For **DB instance size**, choose **Free tier**. **Free tier** appears for free plan accounts. **Sandbox** appears for paid plan accounts.

1. For **DB instance identifier**, enter **database-test1**.

1. For **Master username**, enter a name for the master user, or keep the default name.

   The **Create database** page should look similar to the following image. For free plan accounts, **Free tier **appears. For paid plan accounts, **Sandbox** appears.  
![\[Create database page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-mysql.png)

1. To use an automatically generated master password for the DB instance, select **Auto generate a password**.

   To enter your master password, make sure **Auto generate a password** is cleared, and then enter the same password in **Master password** and **Confirm password**.

1. To set up a connection with the EC2 instance you created previously, open **Set up EC2 connection - *optional***.

   Select **Connect to an EC2 compute resource**. Choose the EC2 instance you created previously.  
![\[Set up EC2 connection option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Setup_Conn-EasyCreate.png)

1. (Optional) Open **View default settings for Easy create**.  
![\[Easy create default settings.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-view-default-mysql.png)

   You can examine the default settings used with **Easy create**. The **Editable after database is created** column shows which options you can change after you create the database.
   + If a setting has **No** in that column, and you want a different setting, you can use **Standard create** to create the DB instance.
   + If a setting has **Yes** in that column, and you want a different setting, you can either use **Standard create** to create the DB instance, or modify the DB instance after you create it to change the setting.

1. Choose **Create database**.

   To view the master username and password for the DB instance, choose **View credential details**.

   You can use the username and password that appears to connect to the DB instance as the master user.
**Important**  
You can't view the master user password again. If you don't record it, you might have to change it.   
If you need to change the master user password after the DB instance is available, you can modify the DB instance to do so. For more information about modifying a DB instance, see [Modifying an Amazon RDS DB instance](Overview.DBInstance.Modifying.md).

1. In the **Databases** list, choose the name of the new MySQL DB instance to show its details.

   The DB instance has a status of **Creating** until it is ready to use.  
![\[DB instance details.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/MySQL-Launch06.png)

   When the status changes to **Available**, you can connect to the DB instance. Depending on the DB instance class and the amount of storage, it can take up to 20 minutes before the new instance is available.

## (Optional) Create VPC, EC2 instance, and MySQL instance using CloudFormation
<a name="CHAP_GettingStarted.CFN.MySQL"></a>

Instead of using the console to create your VPC, EC2 instance, and MySQL instance, you can use CloudFormation to provision AWS resources by treating infrastructure as code. To help you organize your AWS resources into smaller and more manageable units, you can use the CloudFormation nested stack functionality. For more information, see [ Creating a stack on the CloudFormation console](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html) and [Working with nested stacks](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html). 

**Important**  
CloudFormation is free, but the resources that CloudFormation creates are live. You incur the standard usage fees for these resources until you terminate them. For more information, see [RDS for MySQL pricing](https://aws.amazon.com//rds/mysql/pricing).

To create your resources using the CloudFormation console, complete the following steps:
+ Download the CloudFormation template
+ Configure your resources using CloudFormation

### Download the CloudFormation template
<a name="CHAP_GettingStarted.CFN.MySQL.Step1"></a>

A CloudFormation template is a JSON or YAML text file that contains the configuration information about the resources you want to create in the stack. This template also creates a VPC and a bastion host for you along with the RDS instance.

To download the template file, open the following link, [MySQL CloudFormation template](https://github.com/aws-ia/cfn-ps-amazon-rds/blob/main/templates/rds-mysql-main.template.yaml).

In the Github page, click the *Download raw file* button to save the template YAML file.

### Configure your resources using CloudFormation
<a name="CHAP_GettingStarted.CFN.MySQL.Step2"></a>

**Note**  
Before starting this process, make sure you have a Key pair for an EC2 instance in your AWS account. For more information, see [Amazon EC2 key pairs and Linux instances](https://docs.aws.amazon.com//AWSEC2/latest/UserGuide/ec2-key-pairs.html).

When you use the CloudFormation template, you must select the correct parameters to make sure your resources are created properly. Follow the steps below:

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

1. Choose **Create Stack**.

1. In the Specify template section, select **Upload a template file from your computer**, and then choose **Next**.

1. In the **Specify stack details** page, set the following parameters:

   1. Set **Stack name** to **MySQLTestStack**.

   1. Under **Parameters**, set **Availability Zones** by selecting three availability zones.

   1. Under **Linux Bastion Host configuration**, for **Key Name**, select a key pair to login to your EC2 instance.

   1. In **Linux Bastion Host configuration** settings, set the **Permitted IP range** to your IP address. To connect to EC2 instances in your VPC using Secure Shell (SSH), determine your public IP address using the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com). An example of an IP address is 192.0.2.1/32.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public EC2 instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using SSH.

   1. Under **Database General configuration**, set **Database instance class** to **db.t3.micro**.

   1. Set **Database name** to **database-test1**.

   1. For **Database master username**, enter a name for the master user.

   1. Set **Manage DB master user password with Secrets Manager** to `false` for this tutorial.

   1. For **Database password**, set a password of your choice. Remember this password for further steps in the tutorial.

   1. Under **Database Storage configuration**, set **Database storage type** to **gp2**.

   1. Under **Database Monitoring configuration**, set **Enable RDS Performance Insights** to false.

   1. Leave all other settings as the default values. Click **Next** to continue.

1. In the **Configure stack options** page, leave all the default options. Click **Next** to continue.

1. In the **Review stack** page, select **Submit** after checking the database and Linux bastion host options.

After the stack creation process completes, view the stacks with names *BastionStack* and *RDSNS* to note the information you need to connect to the database. For more information, see [ Viewing CloudFormation stack data and resources on the AWS Management Console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-view-stack-data-resources.html).

## Connect to a MySQL DB instance
<a name="CHAP_GettingStarted.Connecting.MySQL"></a>

You can use any standard SQL client application to connect to the DB instance. In this example, you connect to a MySQL DB instance using the mysql command-line client.

**To connect to a MySQL DB instance**

1. Find the endpoint (DNS name) and port number for your DB instance. 

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

   1. In the upper-right corner of the Amazon RDS console, choose the AWS Region for the DB instance.

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

   1. Choose the MySQL DB instance name to display its details. 

   1. On the **Connectivity & security** tab, copy the endpoint. Also, note the port number. You need both the endpoint and the port number to connect to the DB instance.   
![\[Connect to a MySQL DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/MySQLConnect1.png)

1. Connect to the EC2 instance that you created earlier by following the steps in [Connect to your Linux instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html) in the *Amazon EC2 User Guide*.

   We recommend that you connect to your EC2 instance using SSH. If the SSH client utility is installed on Windows, Linux, or Mac, you can connect to the instance using the following command format:

   ```
   ssh -i location_of_pem_file ec2-user@ec2-instance-public-dns-name
   ```

   For example, assume that `ec2-database-connect-key-pair.pem` is stored in `/dir1` on Linux, and the public IPv4 DNS for your EC2 instance is `ec2-12-345-678-90.compute-1.amazonaws.com`. Your SSH command would look as follows:

   ```
   ssh -i /dir1/ec2-database-connect-key-pair.pem ec2-user@ec2-12-345-678-90.compute-1.amazonaws.com
   ```

1. Get the latest bug fixes and security updates by updating the software on your EC2 instance. To do this, use the following command.
**Note**  
The `-y` option installs the updates without asking for confirmation. To examine updates before installing, omit this option.

   ```
   sudo dnf update -y
   ```

1.  To install the mysql command-line client from MariaDB on Amazon Linux 2023, run the following command:

   ```
   sudo dnf install mariadb105
   ```

1. Connect to the MySQL DB instance. For example, enter the following command. This action lets you connect to the MySQL DB instance using the MySQL client.

   Substitute the DB instance endpoint (DNS name) for `endpoint`, and substitute the master username that you used for `admin`. Provide the master password that you used when prompted for a password.

   ```
   mysql -h endpoint -P 3306 -u admin -p
   ```

   After you enter the password for the user, you should see output similar to the following.

   ```
   Welcome to the MariaDB monitor.  Commands end with ; or \g.
   Your MySQL connection id is 3082
   Server version: 8.0.28 Source distribution
   
   Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.
   
   Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
   
   MySQL [(none)]>
   ```

   For more information about connecting to a MySQL DB instance, see [Connecting to your MySQL DB instance](USER_ConnectToInstance.md). If you can't connect to your DB instance, see [Can't connect to Amazon RDS DB instance](CHAP_Troubleshooting.md#CHAP_Troubleshooting.Connecting).

   For security, it is a best practice to use encrypted connections. Only use an unencrypted MySQL connection when the client and server are in the same VPC and the network is trusted. For information about using encrypted connections, see [Connecting to your MySQL DB instance on Amazon RDS with SSL/TLS from the MySQL command-line client (encrypted)](USER_ConnectToInstanceSSL.CLI.md).

1. Run SQL commands.

   For example, the following SQL command shows the current date and time:

   ```
   SELECT CURRENT_TIMESTAMP;
   ```

## Delete the EC2 instance and DB instance
<a name="CHAP_GettingStarted.Deleting.MySQL"></a>

After you connect to and explore the sample EC2 instance and DB instance that you created, delete them so you're no longer charged for them.

If you used CloudFormation to create resources, skip this step and go to the next step.

**To delete the EC2 instance**

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

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

1. Select the EC2 instance, and choose **Instance state, Terminate instance**.

1. Choose **Terminate** when prompted for confirmation.

For more information about deleting an EC2 instance, see [Terminate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html) in the *Amazon EC2 User Guide*.

**To delete the DB instance with no final DB snapshot**

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

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

1. Choose the DB instance that you want to delete.

1. For **Actions**, choose **Delete**.

1. Clear **Create final snapshot?** and **Retain automated backups**.

1. Complete the acknowledgement and choose **Delete**. 

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
<a name="CHAP_GettingStarted.DeletingCFN.MySQL"></a>

If you used CloudFormation to create resources, delete the CloudFormation stack after you connect to and explore the sample EC2 instance and DB instance, so you're no longer charged for them.

**To delete the CloudFormation resources**

1. Open the CloudFormation console.

1. On the **Stacks** page in the CloudFormationconsole, select the root stack (the stack without the name VPCStack, BastionStack or RDSNS).

1. Choose **Delete**.

1. Select **Delete stack** when prompted for confirmation.

For more information about deleting a stack in CloudFormation, see [Deleting a stack on the CloudFormation console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html) in the *AWS CloudFormation User Guide*.

## (Optional) Connect your DB instance to a Lambda function
<a name="CHAP_GettingStarted.ComputeConnect.MySQL"></a>

You can also connect your RDS for MySQL DB instance to a Lambda serverless compute resource. Lambda functions allow you to run code without provisioning or managing infrastructure. A Lambda function also allows you to automatically respond to code execution requests at any scale, from a dozen events a day to hundreds of per second. For more information, see [Automatically connecting a Lambda function and a DB instance](lambda-rds-connect.md).

# Creating and connecting to an Oracle DB instance
<a name="CHAP_GettingStarted.CreatingConnecting.Oracle"></a>

This tutorial creates an EC2 instance and an RDS for Oracle DB instance. The tutorial shows you how to access the DB instance from the EC2 instance using a standard Oracle client. As a best practice, this tutorial creates a private DB instance in a virtual private cloud (VPC). In most cases, other resources in the same VPC, such as EC2 instances, can access the DB instance, but resources outside of the VPC can't access it.

After you complete the tutorial, there is a public and private subnet in each Availability Zone in your VPC. In one Availability Zone, the EC2 instance is in the public subnet, and the DB instance is in the private subnet.

**Important**  
There's no charge for creating an AWS account. However, by completing this tutorial, you might incur costs for the AWS resources you use. You can delete these resources after you complete the tutorial if they are no longer needed.

The following diagram shows the configuration when the tutorial is complete.

![\[EC2 instance and Oracle DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-oracle.png)


This tutorial allows you to create your resources by using one of the following methods:

1. Use the AWS Management Console ‐ [Step 2: Create an Oracle DB instance](#CHAP_GettingStarted.Creating.Oracle) and [Step 1: Create an EC2 instance](#CHAP_GettingStarted.Creating.Oracle.EC2) 

1. Use CloudFormation to create the database instance and EC2 instance ‐ [(Optional) Create VPC, EC2 instance, and Oracle DB instance using CloudFormation](#CHAP_GettingStarted.CFN.Oracle) 

The first method uses **Easy create** to create a private Oracle DB instance with the AWS Management Console. Here, you specify only the DB engine type, DB instance size, and DB instance identifier. **Easy create** uses the default settings for the other configuration options.

When you use **Standard create** instead, you can specify more configuration options when you create a DB instance. These options include settings for availability, security, backups, and maintenance. To create a public DB instance, you must use **Standard create**. For information, see [Creating an Amazon RDS DB instance](USER_CreateDBInstance.md).

**Topics**
+ [

## Prerequisites
](#CHAP_GettingStarted.Prerequisites.Oracle)
+ [

## Step 1: Create an EC2 instance
](#CHAP_GettingStarted.Creating.Oracle.EC2)
+ [

## Step 2: Create an Oracle DB instance
](#CHAP_GettingStarted.Creating.Oracle)
+ [

## (Optional) Create VPC, EC2 instance, and Oracle DB instance using CloudFormation
](#CHAP_GettingStarted.CFN.Oracle)
+ [

## Step 3: Connect your SQL client to an Oracle DB instance
](#CHAP_GettingStarted.Connecting.Oracle)
+ [

## Step 4: Delete the EC2 instance and DB instance
](#CHAP_GettingStarted.Deleting.Oracle)
+ [

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
](#CHAP_GettingStarted.DeletingCFN.Oracle)
+ [

## (Optional) Connect your DB instance to a Lambda function
](#CHAP_GettingStarted.ComputeConnect.Oracle)

## Prerequisites
<a name="CHAP_GettingStarted.Prerequisites.Oracle"></a>

Before you begin, complete the steps in the following sections:
+ [Sign up for an AWS account](CHAP_SettingUp.md#sign-up-for-aws)
+ [Create a user with administrative access](CHAP_SettingUp.md#create-an-admin)

## Step 1: Create an EC2 instance
<a name="CHAP_GettingStarted.Creating.Oracle.EC2"></a>

Create an Amazon EC2 instance that you will use to connect to your database.

**To create an EC2 instance**

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

1. In the upper-right corner of the AWS Management Console, choose the AWS Region in which you want to create the EC2 instance.

1. Choose **EC2 Dashboard**, and then choose **Launch instance**, as shown in the following image.  
![\[EC2 Dashboard.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_11.png)

   The **Launch an instance** page opens.

1. Choose the following settings on the **Launch an instance** page.

   1. Under **Name and tags**, for **Name**, enter **ec2-database-connect**.

   1. Under **Application and OS Images (Amazon Machine Image)**, choose **Amazon Linux**, and then choose the **Amazon Linux 2023 AMI**. Keep the default selections for the other choices.  
![\[Choose an Amazon Machine Image.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_12.png)

   1. Under **Instance type**, choose **t2.micro**.

   1. Under **Key pair (login)**, choose a **Key pair name** to use an existing key pair. To create a new key pair for the Amazon EC2 instance, choose **Create new key pair** and then use the **Create key pair** window to create it.

      For more information about creating a new key pair, see [Create a key pair](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html#create-a-key-pair) in the *Amazon EC2 User Guide*.

   1. For **Allow SSH traffic** in **Network settings**, choose the source of SSH connections to the EC2 instance. 

      You can choose **My IP** if the displayed IP address is correct for SSH connections. Otherwise, you can determine the IP address to use to connect to EC2 instances in your VPC using Secure Shell (SSH). To determine your public IP address, in a different browser window or tab, you can use the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com/). An example of an IP address is 192.0.2.1/32.

       In many cases, you might connect through an internet service provider (ISP) or from behind your firewall without a static IP address. If so, make sure to determine the range of IP addresses used by client computers.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public EC2 instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using SSH.

      The following image shows an example of the **Network settings** section.  
![\[Network settings for an EC2 instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Connect_NtwkSettings.png)

   1. Leave the default values for the remaining sections.

   1. Review a summary of your EC2 instance configuration in the **Summary** panel, and when you're ready, choose **Launch instance**.

1. On the **Launch Status** page, note the identifier for your new EC2 instance, for example: `i-1234567890abcdef0`.  
![\[EC2 instance identifier on Launch Status page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-ec2-id.png)

1. Choose the EC2 instance identifier to open the list of EC2 instances, and then select your EC2 instance.

1. In the **Details** tab, note the following values, which you need when you connect using SSH:

   1. In **Instance summary**, note the value for **Public IPv4 DNS**.  
![\[EC2 public DNS name on Details tab of Instances page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-public-dns.png)

   1. In **Instance details**, note the value for **Key pair name**.  
![\[EC2 key pair name on Details tab of Instance page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-key-pair.png)

1. Wait until the **Instance state** for your EC2 instance has a status of **Running** before continuing.

## Step 2: Create an Oracle DB instance
<a name="CHAP_GettingStarted.Creating.Oracle"></a>

The basic building block of Amazon RDS is the DB instance. This environment is where you run your Oracle databases.

In this example, you use **Easy create** to create a DB instance running the Oracle database engine with a db.m5.large DB instance class.

**To create an Oracle DB instance with Easy create**

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

1. In the upper-right corner of the Amazon RDS console, choose the AWS Region in which you want to create the DB instance.

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

1. Choose **Create database** and make sure that **Easy create** is chosen.   
![\[Easy create option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-option.png)

1. In **Configuration**, choose **Oracle**.

1. For **DB instance size**, choose **Dev/Test**.

1. For **DB instance identifier**, enter **database-test1**.

1. For **Master username**, enter a name for the master user, or keep the default name.

   The **Create database** page should look similar to the following image.  
![\[Create database page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-oracle2.png)

1. To use an automatically generated master password for the DB instance, select **Auto generate a password**.

   To enter your master password, make sure **Auto generate a password** is cleared, and then enter the same password in **Master password** and **Confirm password**.

1. To set up a connection with the EC2 instance you created previously, open **Set up EC2 connection - *optional***.

   Select **Connect to an EC2 compute resource**. Choose the EC2 instance you created previously.  
![\[Set up EC2 connection option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Setup_Conn-EasyCreate.png)

1. Open **View default settings for Easy create**.  
![\[Easy create default settings.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-view-default-Oracle.png)

   You can examine the default settings used with **Easy create**. The **Editable after database is created** column shows which options you can change after you create the database.
   + If a setting has **No** in that column, and you want a different setting, you can use **Standard create** to create the DB instance.
   + If a setting has **Yes** in that column, and you want a different setting, you can either use **Standard create** to create the DB instance, or modify the DB instance after you create it to change the setting.

1. Choose **Create database**.

   To view the master username and password for the DB instance, choose **View credential details**.

   You can use the username and password that appears to connect to the DB instance as the master user.
**Important**  
You can't view the master user password again. If you don't record it, you might have to change it.   
If you need to change the master user password after the DB instance is available, you can modify the DB instance to do so. For more information about modifying a DB instance, see [Modifying an Amazon RDS DB instance](Overview.DBInstance.Modifying.md).

1. In the **Databases** list, choose the name of the new Oracle DB instance to show its details.

   The DB instance has a status of **Creating** until it is ready to use.  
![\[DB instance details.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Oracle-Launch05.png)

   When the status changes to **Available**, you can connect to the DB instance. Depending on the DB instance class and the amount of storage, it can take up to 20 minutes before the new instance is available. While the DB instance is being created, you can move on to the next step and create an EC2 instance.

## (Optional) Create VPC, EC2 instance, and Oracle DB instance using CloudFormation
<a name="CHAP_GettingStarted.CFN.Oracle"></a>

Instead of using the console to create your VPC, EC2 instance, and Oracle DB instance, you can use CloudFormation to provision AWS resources by treating infrastructure as code. To help you organize your AWS resources into smaller and more manageable units, you can use the CloudFormation nested stack functionality. For more information, see [ Creating a stack on the CloudFormation console](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html) and [Working with nested stacks](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html). 

**Important**  
CloudFormation is free, but the resources that CloudFormation creates are live. You incur the standard usage fees for these resources until you terminate them. For more information, see [RDS for Oracle pricing](https://aws.amazon.com//rds/oracle/pricing).

To create your resources using the CloudFormation console, complete the following steps:
+ Step 1: Download the CloudFormation template
+ Step 2: Configure your resources using CloudFormation

### Download the CloudFormation template
<a name="CHAP_GettingStarted.CFN.Oracle.Step1"></a>

A CloudFormation template is a JSON or YAML text file that contains the configuration information about the resources you want to create in the stack. This template also creates a VPC and a bastion host for you along with the RDS instance.

To download the template file, open the following link, [Oracle CloudFormation template](https://github.com/aws-ia/cfn-ps-amazon-rds/blob/main/templates/rds-oracle-main.template.yaml).

In the Github page, click the *Download raw file* button to save the template YAML file.

### Configure your resources using CloudFormation
<a name="CHAP_GettingStarted.CFN.Oracle.Step2"></a>

**Note**  
Before starting this process, make sure you have a Key pair for an EC2 instance in your AWS account. For more information, see [Amazon EC2 key pairs and Linux instances](https://docs.aws.amazon.com//AWSEC2/latest/UserGuide/ec2-key-pairs.html).

When you use the CloudFormation template, you must select the correct parameters to make sure your resources are created properly. Follow the steps below:

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

1. Choose **Create Stack**.

1. In the Specify template section, select **Upload a template file from your computer**, and then choose **Next**.

1. In the **Specify stack details** page, set the following parameters:

   1. Set **Stack name** to **OracleTestStack**.

   1. Under **Parameters**, set **Availability Zones** by selecting three availability zones.

   1. Under **Linux Bastion Host configuration**, for **Key Name**, select a key pair to login to your EC2 instance.

   1. In **Linux Bastion Host configuration** settings, set the **Permitted IP range** to your IP address. To connect to EC2 instances in your VPC using Secure Shell (SSH), determine your public IP address using the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com). An example of an IP address is 192.0.2.1/32.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public EC2 instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using SSH.

   1. Under **Database General configuration**, set **Database instance class** to **db.t3.micro**.

   1. Set **Database name** to **database-test1**.

   1. For **Database master username**, enter a name for the master user.

   1. Set **Manage DB master user password with Secrets Manager** to `false` for this tutorial.

   1. For **Database password**, set a password of your choice. Remember this password for further steps in the tutorial.

   1. Under **Database Storage configuration**, set **Database storage type** to **gp2**.

   1. Under **Database Monitoring configuration**, set **Enable RDS Performance Insights** to false.

   1. Leave all other settings as the default values. Click **Next** to continue.

1. In the **Configure stack options** page, leave all the default options. Click **Next** to continue.

1. In the **Review stack** page, select **Submit** after checking the database and Linux bastion host options.

After the stack creation process completes, view the stacks with names *BastionStack* and *RDSNS* to note the information you need to connect to the database. For more information, see [ Viewing CloudFormation stack data and resources on the AWS Management Console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-view-stack-data-resources.html).

## Step 3: Connect your SQL client to an Oracle DB instance
<a name="CHAP_GettingStarted.Connecting.Oracle"></a>

You can use any standard SQL client application to connect to your DB instance. In this example, you connect to an Oracle DB instance using the Oracle command-line client.

**To connect to an Oracle DB instance**

1. Find the endpoint (DNS name) and port number for your DB instance. 

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

   1. In the upper-right corner of the Amazon RDS console, choose the AWS Region for the DB instance.

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

   1. Choose the Oracle DB instance name to display its details. 

   1. On the **Connectivity & security** tab, copy the endpoint. Also, note the port number. You need both the endpoint and the port number to connect to the DB instance.   
![\[Connect to an Oracle DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/OracleConnect1.png)

1. Connect to the EC2 instance that you created earlier by following the steps in [Connect to your Linux instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html) in the *Amazon EC2 User Guide*.

   We recommend that you connect to your EC2 instance using SSH. If the SSH client utility is installed on Windows, Linux, or Mac, you can connect to the instance using the following command format:

   ```
   ssh -i location_of_pem_file ec2-user@ec2-instance-public-dns-name
   ```

   For example, assume that `ec2-database-connect-key-pair.pem` is stored in `/dir1` on Linux, and the public IPv4 DNS for your EC2 instance is `ec2-12-345-678-90.compute-1.amazonaws.com`. Your SSH command would look as follows:

   ```
   ssh -i /dir1/ec2-database-connect-key-pair.pem ec2-user@ec2-12-345-678-90.compute-1.amazonaws.com
   ```

1. Get the latest bug fixes and security updates by updating the software on your EC2 instance. To do so, use the following command.
**Note**  
The `-y` option installs the updates without asking for confirmation. To examine updates before installing, omit this option.

   ```
   sudo dnf update -y
   ```

1. In a web browser, go to [https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html](https://www.oracle.com/database/technologies/instant-client/linux-x86-64-downloads.html).

1. For the latest database version that appears on the web page, copy the .rpm links (not the .zip links) for the Instant Client Basic Package and SQL\$1Plus Package. For example, the following links are for Oracle Database version 21.9:
   + https://download.oracle.com/otn\$1software/linux/instantclient/219000/oracle-instantclient-basic-21.9.0.0.0-1.el8.x86\$164.rpm
   + https://download.oracle.com/otn\$1software/linux/instantclient/219000/oracle-instantclient-sqlplus-21.9.0.0.0-1.el8.x86\$164.rpm

1. In your SSH session, run the `wget` command to the download the .rpm files from the links that you obtained in the previous step. The following example downloads the .rpm files for Oracle Database version 21.9:

   ```
   wget https://download.oracle.com/otn_software/linux/instantclient/219000/oracle-instantclient-basic-21.9.0.0.0-1.el8.x86_64.rpm
   wget https://download.oracle.com/otn_software/linux/instantclient/219000/oracle-instantclient-sqlplus-21.9.0.0.0-1.el8.x86_64.rpm
   ```

1. Install the packages by running the `dnf` command as follows:

   ```
   sudo dnf install oracle-instantclient-*.rpm
   ```

1. Start SQL\$1Plus and connect to the Oracle DB instance. For example, enter the following command.

   Substitute the DB instance endpoint (DNS name) for `oracle-db-instance-endpoint` and substitute the master user name that you used for `admin`. When you use **Easy create** for Oracle, the database name is `DATABASE`. Provide the master password that you used when prompted for a password.

   ```
   sqlplus admin@oracle-db-instance-endpoint:1521/DATABASE
   ```

   After you enter the password for the user, you should see output similar to the following.

   ```
   SQL*Plus: Release 21.0.0.0.0 - Production on Wed Mar 1 16:41:28 2023
   Version 21.9.0.0.0
   
   Copyright (c) 1982, 2022, Oracle.  All rights reserved.
   
   Enter password: 
   Last Successful login time: Wed Mar 01 2023 16:30:52 +00:00
   
   Connected to:
   Oracle Database 19c Standard Edition 2 Release 19.0.0.0.0 - Production
   Version 19.18.0.0.0
   
   SQL>
   ```

   For more information about connecting to an RDS for Oracle DB instance, see [Connecting to your Oracle DB instance](USER_ConnectToOracleInstance.md). If you can't connect to your DB instance, see [Can't connect to Amazon RDS DB instance](CHAP_Troubleshooting.md#CHAP_Troubleshooting.Connecting).

   For security, it is a best practice to use encrypted connections. Only use an unencrypted Oracle connection when the client and server are in the same VPC and the network is trusted. For information about using encrypted connections, see [Securing Oracle DB instance connections](Oracle.Concepts.RestrictedDBAPrivileges.md).

1. Run SQL commands.

   For example, the following SQL command shows the current date:

   ```
   SELECT SYSDATE FROM DUAL;
   ```

## Step 4: Delete the EC2 instance and DB instance
<a name="CHAP_GettingStarted.Deleting.Oracle"></a>

After you connect to and explore the sample EC2 instance and DB instance that you created, delete them so you're no longer charged for them.

If you used CloudFormation to create resources, skip this step and go to the next step.

**To delete the EC2 instance**

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

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

1. Select the EC2 instance, and choose **Instance state, Terminate instance**.

1. Choose **Terminate** when prompted for confirmation.

For more information about deleting an EC2 instance, see [Terminate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html) in the *Amazon EC2 User Guide*.

**To delete the DB instance with no final DB snapshot**

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

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

1. Choose the DB instance that you want to delete.

1. For **Actions**, choose **Delete**.

1. Clear **Create final snapshot?** and **Retain automated backups**.

1. Complete the acknowledgement and choose **Delete**. 

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
<a name="CHAP_GettingStarted.DeletingCFN.Oracle"></a>

If you used CloudFormation to create resources, delete the CloudFormation stack after you connect to and explore the sample EC2 instance and DB instance, so you're no longer charged for them.

**To delete the CloudFormation resources**

1. Open the CloudFormation console.

1. On the **Stacks** page in the CloudFormationconsole, select the root stack (the stack without the name VPCStack, BastionStack or RDSNS).

1. Choose **Delete**.

1. Select **Delete stack** when prompted for confirmation.

For more information about deleting a stack in CloudFormation, see [Deleting a stack on the CloudFormation console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html) in the *AWS CloudFormation User Guide*.

## (Optional) Connect your DB instance to a Lambda function
<a name="CHAP_GettingStarted.ComputeConnect.Oracle"></a>

You can also connect your RDS for Oracle DB instance to a Lambda serverless compute resource. Lambda functions allow you to run code without provisioning or managing infrastructure. A Lambda function also allows you to automatically respond to code execution requests at any scale, from a dozen events a day to hundreds of per second. For more information, see [Automatically connecting a Lambda function and a DB instance](lambda-rds-connect.md).

# Creating and connecting to a PostgreSQL DB instance
<a name="CHAP_GettingStarted.CreatingConnecting.PostgreSQL"></a>

This tutorial creates an EC2 instance and an RDS for PostgreSQL DB instance. The tutorial shows you how to access the DB instance from the EC2 instance using a standard PostgreSQL client. As a best practice, this tutorial creates a private DB instance in a virtual private cloud (VPC). In most cases, other resources in the same VPC, such as EC2 instances, can access the DB instance, but resources outside of the VPC can't access it.

After you complete the tutorial, there is a public and private subnet in each Availability Zone in your VPC. In one Availability Zone, the EC2 instance is in the public subnet, and the DB instance is in the private subnet.

**Important**  
There's no charge for creating an AWS account. However, by completing this tutorial, you might incur costs for the AWS resources you use. You can delete these resources after you complete the tutorial if they are no longer needed.

The following diagram shows the configuration when the tutorial is complete.

![\[EC2 instance and PostgreSQL DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-postgresql.png)


This tutorial allows you to create your resources by using one of the following methods:

1. Use the AWS Management Console ‐ [Create an EC2 instance](#CHAP_GettingStarted.Creating.RDSPostgreSQL.EC2) and [Create a PostgreSQL DB instance](#CHAP_GettingStarted.Creating.PostgreSQL) 

1. Use CloudFormation to create the database instance and EC2 instance ‐ [(Optional) Create VPC, EC2 instance, and PostgreSQL instance using CloudFormation](#CHAP_GettingStarted.CFN.PostgreSQL) 

The first method uses **Easy create** to create a private PostgreSQL DB instance with the AWS Management Console. Here, you specify only the DB engine type, DB instance size, and DB instance identifier. **Easy create** uses the default settings for the other configuration options. 

When you use **Standard create** instead, you can specify more configuration options when you create a DB instance. These options include settings for availability, security, backups, and maintenance. To create a public DB instance, you must use **Standard create**. For information, see [Creating an Amazon RDS DB instance](USER_CreateDBInstance.md).

**Topics**
+ [

## Prerequisites
](#CHAP_GettingStarted.Prerequisites.RDSPostgreSQL)
+ [

## Create an EC2 instance
](#CHAP_GettingStarted.Creating.RDSPostgreSQL.EC2)
+ [

## Create a PostgreSQL DB instance
](#CHAP_GettingStarted.Creating.PostgreSQL)
+ [

## (Optional) Create VPC, EC2 instance, and PostgreSQL instance using CloudFormation
](#CHAP_GettingStarted.CFN.PostgreSQL)
+ [

## Connect to a PostgreSQL DB instance
](#CHAP_GettingStarted.Connecting.PostgreSQL)
+ [

## Delete the EC2 instance and DB instance
](#CHAP_GettingStarted.Deleting.PostgreSQL)
+ [

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
](#CHAP_GettingStarted.DeletingCFN.PostgreSQL)
+ [

## (Optional) Connect your DB instance to a Lambda function
](#CHAP_GettingStarted.ComputeConnect.PostreSQL)

## Prerequisites
<a name="CHAP_GettingStarted.Prerequisites.RDSPostgreSQL"></a>

Before you begin, complete the steps in the following sections:
+ [Sign up for an AWS account](CHAP_SettingUp.md#sign-up-for-aws)
+ [Create a user with administrative access](CHAP_SettingUp.md#create-an-admin)

## Create an EC2 instance
<a name="CHAP_GettingStarted.Creating.RDSPostgreSQL.EC2"></a>

Create an Amazon EC2 instance that you will use to connect to your database.

**To create an EC2 instance**

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

1. In the upper-right corner of the AWS Management Console, choose the AWS Region in which you want to create the EC2 instance.

1. Choose **EC2 Dashboard**, and then choose **Launch instance**, as shown in the following image.  
![\[EC2 Dashboard.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_11.png)

   The **Launch an instance** page opens.

1. Choose the following settings on the **Launch an instance** page.

   1. Under **Name and tags**, for **Name**, enter **ec2-database-connect**.

   1. Under **Application and OS Images (Amazon Machine Image)**, choose **Amazon Linux**, and then choose the **Amazon Linux 2023 AMI**. Keep the default selections for the other choices.  
![\[Choose an Amazon Machine Image.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_12.png)

   1. Under **Instance type**, choose **t2.micro**.

   1. Under **Key pair (login)**, choose a **Key pair name** to use an existing key pair. To create a new key pair for the Amazon EC2 instance, choose **Create new key pair** and then use the **Create key pair** window to create it.

      For more information about creating a new key pair, see [Create a key pair](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html#create-a-key-pair) in the *Amazon EC2 User Guide*.

   1. For **Allow SSH traffic** in **Network settings**, choose the source of SSH connections to the EC2 instance. 

      You can choose **My IP** if the displayed IP address is correct for SSH connections. Otherwise, you can determine the IP address to use to connect to EC2 instances in your VPC using Secure Shell (SSH). To determine your public IP address, in a different browser window or tab, you can use the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com/). An example of an IP address is 192.0.2.1/32.

       In many cases, you might connect through an internet service provider (ISP) or from behind your firewall without a static IP address. If so, make sure to determine the range of IP addresses used by client computers.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public EC2 instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using SSH.

      The following image shows an example of the **Network settings** section.  
![\[Network settings for an EC2 instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Connect_NtwkSettings.png)

   1. Leave the default values for the remaining sections.

   1. Review a summary of your EC2 instance configuration in the **Summary** panel, and when you're ready, choose **Launch instance**.

1. On the **Launch Status** page, note the identifier for your new EC2 instance, for example: `i-1234567890abcdef0`.  
![\[EC2 instance identifier on Launch Status page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-ec2-id.png)

1. Choose the EC2 instance identifier to open the list of EC2 instances, and then select your EC2 instance.

1. In the **Details** tab, note the following values, which you need when you connect using SSH:

   1. In **Instance summary**, note the value for **Public IPv4 DNS**.  
![\[EC2 public DNS name on Details tab of Instances page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-public-dns.png)

   1. In **Instance details**, note the value for **Key pair name**.  
![\[EC2 key pair name on Details tab of Instance page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-key-pair.png)

1. Wait until the **Instance state** for your EC2 instance has a status of **Running** before continuing.

## Create a PostgreSQL DB instance
<a name="CHAP_GettingStarted.Creating.PostgreSQL"></a>

The basic building block of Amazon RDS is the DB instance. This environment is where you run your PostgreSQL databases.

In this example, you use **Easy create** to create a DB instance running the PostgreSQL database engine with a db.t3.micro DB instance class.

**To create a PostgreSQL DB instance with Easy create**

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

1. In the upper-right corner of the Amazon RDS console, choose the AWS Region in which you want to create the DB instance. 

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

1. Choose **Create database** and make sure that **Easy create** is chosen.  
![\[Easy create option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-option.png)

1. In **Configuration**, choose **PostgreSQL**.

1. For **DB instance size**, choose **Free tier**. **Free tier** appears for free plan accounts. **Sandbox** appears for paid plan accounts.

1. For **DB instance identifier**, enter **database-test1**.

1. For **Master username**, enter a name for the master user, or keep the default name (**postgres**).

   The **Create database** page should look similar to the following image. For free plan accounts, **Free tier **appears. For paid plan accounts, **Sandbox** appears.  
![\[Create database page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-postgresql.png)

1. To use an automatically generated master password for the DB instance, select **Auto generate a password**.

   To enter your master password, make sure **Auto generate a password** is cleared, and then enter the same password in **Master password** and **Confirm password**.

1. To set up a connection with the EC2 instance you created previously, open **Set up EC2 connection - *optional***.

   Select **Connect to an EC2 compute resource**. Choose the EC2 instance you created previously.  
![\[Set up EC2 connection option.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/EC2_RDS_Setup_Conn-EasyCreate.png)

1. Open **View default settings for Easy create**.  
![\[Easy create default settings for RDS for PostgreSQL.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-view-default-postgres.png)

   You can examine the default settings used with **Easy create**. The **Editable after database is created** column shows which options you can change after you create the database.
   + If a setting has **No** in that column, and you want a different setting, you can use **Standard create** to create the DB instance.
   + If a setting has **Yes** in that column, and you want a different setting, you can either use **Standard create** to create the DB instance, or modify the DB instance after you create it to change the setting.

1. Choose **Create database**.

   To view the master username and password for the DB instance, choose **View credential details**.

   You can use the username and password that appears to connect to the DB instance as the master user.
**Important**  
You can't view the master user password again. If you don't record it, you might have to change it.   
If you need to change the master user password after the DB instance is available, you can modify the DB instance to do so. For more information about modifying a DB instance, see [Modifying an Amazon RDS DB instance](Overview.DBInstance.Modifying.md).

1. In the **Databases** list, choose the name of the new PostgreSQL DB instance to show its details.

   The DB instance has a status of **Creating** until it is ready to use.  
![\[DB instance details.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Postgres-Launch06.png)

   When the status changes to **Available**, you can connect to the DB instance. Depending on the DB instance class and the amount of storage, it can take up to 20 minutes before the new instance is available.

## (Optional) Create VPC, EC2 instance, and PostgreSQL instance using CloudFormation
<a name="CHAP_GettingStarted.CFN.PostgreSQL"></a>

Instead of using the console to create your VPC, EC2 instance, and PostgreSQL instance, you can use CloudFormation to provision AWS resources by treating infrastructure as code. To help you organize your AWS resources into smaller and more manageable units, you can use the CloudFormation nested stack functionality. For more information, see [ Creating a stack on the CloudFormation console](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/cfn-console-create-stack.html) and [Working with nested stacks](https://docs.aws.amazon.com//AWSCloudFormation/latest/UserGuide/using-cfn-nested-stacks.html). 

**Important**  
CloudFormation is free, but the resources that CloudFormation creates are live. You incur the standard usage fees for these resources until you terminate them. For more information, see [RDS for PostgreSQL pricing](https://aws.amazon.com//rds/postgresql/pricing).

To create your resources using the CloudFormation console, complete the following steps:
+ Download the CloudFormation template
+ Configure your resources using CloudFormation

### Download the CloudFormation template
<a name="CHAP_GettingStarted.CFN.PostgreSQL.Step1"></a>

A CloudFormation template is a JSON or YAML text file that contains the configuration information about the resources you want to create in the stack. This template also creates a VPC and a bastion host for you along with the RDS instance.

To download the template file, open the following link, [PostgreSQL CloudFormation template](https://github.com/aws-ia/cfn-ps-amazon-rds/blob/main/templates/rds-postgres-main.template.yaml).

In the Github page, click the *Download raw file* button to save the template YAML file.

### Configure your resources using CloudFormation
<a name="CHAP_GettingStarted.CFN.PostgreSQL.Step2"></a>

**Note**  
Before starting this process, make sure you have a Key pair for an EC2 instance in your AWS account. For more information, see [Amazon EC2 key pairs and Linux instances](https://docs.aws.amazon.com//AWSEC2/latest/UserGuide/ec2-key-pairs.html).

When you use the CloudFormation template, you must select the correct parameters to make sure your resources are created properly. Follow the steps below:

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

1. Choose **Create Stack**.

1. In the Specify template section, select **Upload a template file from your computer**, and then choose **Next**.

1. In the **Specify stack details** page, set the following parameters:

   1. Set **Stack name** to **PostgreSQLTestStack**.

   1. Under **Parameters**, set **Availability Zones** by selecting three availability zones.

   1. Under **Linux Bastion Host configuration**, for **Key Name**, select a key pair to login to your EC2 instance.

   1. In **Linux Bastion Host configuration** settings, set the **Permitted IP range** to your IP address. To connect to EC2 instances in your VPC using Secure Shell (SSH), determine your public IP address using the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com). An example of an IP address is 192.0.2.1/32.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public EC2 instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your EC2 instances using SSH.

   1. Under **Database General configuration**, set **Database instance class** to **db.t3.micro**.

   1. Set **Database name** to **database-test1**.

   1. For **Database master username**, enter a name for the master user.

   1. Set **Manage DB master user password with Secrets Manager** to `false` for this tutorial.

   1. For **Database password**, set a password of your choice. Remember this password for further steps in the tutorial.

   1. Under **Database Storage configuration**, set **Database storage type** to **gp2**.

   1. Under **Database Monitoring configuration**, set **Enable RDS Performance Insights** to false.

   1. Leave all other settings as the default values. Click **Next** to continue.

1. In the **Configure stack options** page, leave all the default options. Click **Next** to continue.

1. In the **Review stack** page, select **Submit** after checking the database and Linux bastion host options.

After the stack creation process completes, view the stacks with names *BastionStack* and *RDSNS* to note the information you need to connect to the database. For more information, see [ Viewing CloudFormation stack data and resources on the AWS Management Console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-view-stack-data-resources.html).

## Connect to a PostgreSQL DB instance
<a name="CHAP_GettingStarted.Connecting.PostgreSQL"></a>

You can connect to the DB instance using pgadmin or psql. This example explains how to connect to a PostgreSQL DB instance using the psql command-line client.

**To connect to a PostgreSQL DB instance using psql**

1. Find the endpoint (DNS name) and port number for your DB instance. 

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

   1. In the upper-right corner of the Amazon RDS console, choose the AWS Region for the DB instance.

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

   1. Choose the PostgreSQL DB instance name to display its details. 

   1. On the **Connectivity & security** tab, copy the endpoint. Also note the port number. You need both the endpoint and the port number to connect to the DB instance.   
![\[Connect to a PostgreSQL DB instance.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/PostgreSQL-endpoint.png)

1. Connect to the EC2 instance that you created earlier by following the steps in [Connect to your Linux instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html) in the *Amazon EC2 User Guide*.

   We recommend that you connect to your EC2 instance using SSH. If the SSH client utility is installed on Windows, Linux, or Mac, you can connect to the instance using the following command format:

   ```
   ssh -i location_of_pem_file ec2-user@ec2-instance-public-dns-name
   ```

   For example, assume that `ec2-database-connect-key-pair.pem` is stored in `/dir1` on Linux, and the public IPv4 DNS for your EC2 instance is `ec2-12-345-678-90.compute-1.amazonaws.com`. Your SSH command would look as follows:

   ```
   ssh -i /dir1/ec2-database-connect-key-pair.pem ec2-user@ec2-12-345-678-90.compute-1.amazonaws.com
   ```

1. Get the latest bug fixes and security updates by updating the software on your EC2 instance. To do this, use the following command.
**Note**  
The `-y` option installs the updates without asking for confirmation. To examine updates before installing, omit this option.

   ```
   sudo dnf update -y
   ```

1. To install the psql command-line client from PostgreSQL on Amazon Linux 2023, run the following command:

   ```
   sudo dnf install postgresql15
   ```

1. Connect to the PostgreSQL DB instance. For example, enter the following command at a command prompt on a client computer. This action lets you connect to the PostgreSQL DB instance using the psql client.

   Substitute the DB instance endpoint (DNS name) for `endpoint`, substitute the database name `--dbname` that you want to connect to for `postgres`, and substitute the master username that you used for `postgres`. Provide the master password that you used when prompted for a password.

   ```
   psql --host=endpoint --port=5432 --dbname=postgres --username=postgres
   ```

   After you enter the password for the user, you should see output similar to the following:

   ```
   psql (14.3, server 14.6)
   SSL connection (protocol: TLSv1.2, cipher: ECDHE-RSA-AES256-GCM-SHA384, bits: 256, compression: off)
   Type "help" for help.
   
   postgres=>
   ```

   For more information on connecting to a PostgreSQL DB instance, see [Connecting to a DB instance running the PostgreSQL database engine](USER_ConnectToPostgreSQLInstance.md). If you can't connect to your DB instance, see [Troubleshooting connections to your RDS for PostgreSQL instance](USER_ConnectToPostgreSQLInstance.Troubleshooting.md). 

   For security, it is a best practice to use encrypted connections. Only use an unencrypted PostgreSQL connection when the client and server are in the same VPC and the network is trusted. For information about using encrypted connections, see [Connecting to a PostgreSQL DB instance over SSL](PostgreSQL.Concepts.General.SSL.md#PostgreSQL.Concepts.General.SSL.Connecting).

1. Run SQL commands.

   For example, the following SQL command shows the current date and time:

   ```
   SELECT CURRENT_TIMESTAMP;
   ```

## Delete the EC2 instance and DB instance
<a name="CHAP_GettingStarted.Deleting.PostgreSQL"></a>

After you connect to and explore the sample EC2 instance and DB instance that you created, delete them so you're no longer charged for them.

If you used CloudFormation to create resources, skip this step and go to the next step.

**To delete the EC2 instance**

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

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

1. Select the EC2 instance, and choose **Instance state, Terminate instance**.

1. Choose **Terminate** when prompted for confirmation.

For more information about deleting an EC2 instance, see [Terminate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html) in the *Amazon EC2 User Guide*.

**To delete a DB instance with no final DB snapshot**

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

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

1. Choose the DB instance that you want to delete.

1. For **Actions**, choose **Delete**.

1. Clear **Create final snapshot?** and **Retain automated backups**.

1. Complete the acknowledgement and choose **Delete**. 

## (Optional) Delete the EC2 instance and DB instance created with CloudFormation
<a name="CHAP_GettingStarted.DeletingCFN.PostgreSQL"></a>

If you used CloudFormation to create resources, delete the CloudFormation stack after you connect to and explore the sample EC2 instance and DB instance, so you're no longer charged for them.

**To delete the CloudFormation resources**

1. Open the CloudFormation console.

1. On the **Stacks** page in the CloudFormationconsole, select the root stack (the stack without the name VPCStack, BastionStack or RDSNS).

1. Choose **Delete**.

1. Select **Delete stack** when prompted for confirmation.

For more information about deleting a stack in CloudFormation, see [Deleting a stack on the CloudFormation console](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-console-delete-stack.html) in the *AWS CloudFormation User Guide*.

## (Optional) Connect your DB instance to a Lambda function
<a name="CHAP_GettingStarted.ComputeConnect.PostreSQL"></a>

You can also connect your RDS for PostgreSQL DB instance to a Lambda serverless compute resource. Lambda functions allow you to run code without provisioning or managing infrastructure. A Lambda function also allows you to automatically respond to code execution requests at any scale, from a dozen events a day to hundreds of per second. For more information, see [Automatically connecting a Lambda function and a DB instance](lambda-rds-connect.md).

# Tutorial: Create a web server and an Amazon RDS DB instance
<a name="TUT_WebAppWithRDS"></a>

This tutorial shows you how to install an Apache web server with PHP and create a MariaDB, MySQL, or PostgreSQL database. The web server runs on an Amazon EC2 instance using Amazon Linux 2023, and you can choose between a MySQL or PostgreSQL DB instance. Both the Amazon EC2 instance and the DB instance run in a virtual private cloud (VPC) based on the Amazon VPC service. 

**Important**  
There's no charge for creating an AWS account. However, by completing this tutorial, you might incur costs for the AWS resources you use. You can delete these resources after you complete the tutorial if they are no longer needed.

**Note**  
This tutorial works with Amazon Linux 2023 and might not work for other versions of Linux.

In the tutorial that follows, you create an EC2 instance that uses the default VPC, subnets, and security group for your AWS account. This tutorial shows you how to create the DB instance and automatically set up connectivity with the EC2 instance that you created. The tutorial then shows you how to install the web server on the EC2 instance. You connect your web server to your DB instance in the VPC using the DB instance endpoint.

1. [Launch an EC2 instance to connect with your DB instance](CHAP_Tutorials.WebServerDB.LaunchEC2.md)

1. [Create an Amazon RDS DB instance](CHAP_Tutorials.WebServerDB.CreateDBInstance.md)

1. [Install a web server on your EC2 instance](CHAP_Tutorials.WebServerDB.CreateWebServer.md)

The following diagram shows the configuration when the tutorial is complete.

![\[Single VPC Scenario\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/con-VPC-sec-grp.png)


**Note**  
After you complete the tutorial, there is a public and private subnet in each Availability Zone in your VPC. This tutorial uses the default VPC for your AWS account and automatically sets up connectivity between your EC2 instance and DB instance. If you would rather configure a new VPC for this scenario instead, complete the tasks in [Tutorial: Create a VPC for use with a DB instance (IPv4 only)](CHAP_Tutorials.WebServerDB.CreateVPC.md).

# Launch an EC2 instance to connect with your DB instance
<a name="CHAP_Tutorials.WebServerDB.LaunchEC2"></a>

Create an Amazon EC2 instance in the public subnet of your VPC.

**To launch an EC2 instance**

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

1. In the upper-right corner of the AWS Management Console, choose the AWS Region where you want to create the EC2 instance.

1. Choose **EC2 Dashboard**, and then choose **Launch instance**, as shown following.  
![\[EC2 Dashboard\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_11.png)

1. Choose the following settings in the **Launch an instance** page.

   1. Under **Name and tags**, for **Name**, enter **tutorial-ec2-instance-web-server**.

   1. Under **Application and OS Images (Amazon Machine Image)**, choose **Amazon Linux**, and then choose the **Amazon Linux 2023 AMI**. Keep the defaults for the other choices.  
![\[Choose an Amazon Machine Image\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_12.png)

   1. Under **Instance type**, choose **t2.micro**.

   1. Under **Key pair (login)**, choose a **Key pair name** to use an existing key pair. To create a new key pair for the Amazon EC2 instance, choose **Create new key pair** and then use the **Create key pair** window to create it.

      For more information about creating a new key pair, see [Create a key pair](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html#create-a-key-pair) in the *Amazon EC2 User Guide*.

   1. Under **Network settings**, set these values and keep the other values as their defaults:
      + For **Allow SSH traffic from**, choose the source of SSH connections to the EC2 instance.

        You can choose **My IP** if the displayed IP address is correct for SSH connections.

        Otherwise, you can determine the IP address to use to connect to EC2 instances in your VPC using Secure Shell (SSH). To determine your public IP address, in a different browser window or tab, you can use the service at [https://checkip.amazonaws.com](https://checkip.amazonaws.com). An example of an IP address is `203.0.113.25/32`.

        In many cases, you might connect through an internet service provider (ISP) or from behind your firewall without a static IP address. If so, make sure to determine the range of IP addresses used by client computers.
**Warning**  
If you use `0.0.0.0/0` for SSH access, you make it possible for all IP addresses to access your public instances using SSH. This approach is acceptable for a short time in a test environment, but it's unsafe for production environments. In production, authorize only a specific IP address or range of addresses to access your instances using SSH.
      + Turn on **Allow HTTPs traffic from the internet**.
      + Turn on **Allow HTTP traffic from the internet**.  
![\[Configure Instance Details\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_14.png)

   1. Leave the default values for the remaining sections.

   1. Review a summary of your instance configuration in the **Summary** panel, and when you're ready, choose **Launch instance**.

1. On the **Launch Status** page, note the identifier for your new EC2 instance, for example: `i-1234567890abcdef0`.  
![\[EC2 instance identifier on Launch Status page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/getting-started-ec2-id.png)

1. Choose the EC2 instance identifier to open the list of EC2 instances, and then select your EC2 instance.

1. In the **Details** tab, note the following values, which you need when you connect using SSH:

   1. In **Instance summary**, note the value for **Public IPv4 DNS**.  
![\[EC2 public DNS name on Details tab of Instances page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-public-dns.png)

   1. In **Instance details**, note the value for **Key pair name**.  
![\[EC2 key pair name on Details tab of Instance page.\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/easy-create-ec2-key-pair.png)

1. Wait until **Instance state** for your instance is **Running** before continuing.

1. Complete [Create an Amazon RDS DB instance](CHAP_Tutorials.WebServerDB.CreateDBInstance.md).

# Create an Amazon RDS DB instance
<a name="CHAP_Tutorials.WebServerDB.CreateDBInstance"></a>

Create an RDS for MariaDB, RDS for MySQL, or RDS for PostgreSQL DB instance that maintains the data used by a web application. 

------
#### [ RDS for MariaDB ]

**To create a MariaDB instance**

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

1. In the upper-right corner of the AWS Management Console, check the AWS Region. It should be the same as the one where you created your EC2 instance.

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

1. Choose **Create database**.

1. On the **Create database** page, choose **Standard create**.

1. For **Engine options**, choose **MariaDB**.  
![\[Select engine type\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/tutorial-create-mariadb.png)

1. For **Templates**, choose **Free tier** or **Sandbox**. **Free tier** appears for free plan accounts. **Sandbox** appears for paid plan accounts.  
![\[Select template\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/tutorial-create-template.png)

1. In the **Availability and durability** section, keep the defaults.

1. In the **Settings** section, set these values:
   + **DB instance identifier** – Type **tutorial-db-instance**.
   + **Master username** – Type **tutorial\$1user**.
   + **Auto generate a password** – Leave the option turned off.
   + **Master password** – Type a password.
   + **Confirm password** – Retype the password.  
![\[Settings sections\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Settings.png)

1. In the **Instance configuration** section, set these values:
   + **Burstable classes (includes t classes)**
   + **db.t3.micro**  
![\[Instance configuration section\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_DB_instance_micro.png)

1. In the **Storage** section, keep the defaults.

1. In the **Connectivity** section, set these values and keep the other values as their defaults:
   + For **Compute resource**, choose **Connect to an EC2 compute resource**.
   + For **EC2 instance**, choose the EC2 instance you created previously, such as **tutorial-ec2-instance-web-server**.  
![\[Connectivity section\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Connectivity.png)

1. In the **Database authentication** section, make sure **Password authentication** is selected.

1. Open the **Additional configuration** section, and enter **sample** for **Initial database name**. Keep the default settings for the other options.

1. To create your MariaDB instance, choose **Create database**.

   Your new DB instance appears in the **Databases** list with the status **Creating**.

1. Wait for the **Status** of your new DB instance to show as **Available**. Then choose the DB instance name to show its details.

1. In the **Connectivity & security** section, view the **Endpoint** and **Port** of the DB instance.  
![\[DB instance details\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Endpoint_Port.png)

   Note the endpoint and port for your DB instance. You use this information to connect your web server to your DB instance.

1. Complete [Install a web server on your EC2 instance](CHAP_Tutorials.WebServerDB.CreateWebServer.md).

------
#### [ RDS for MySQL ]

**To create a MySQL DB instance**

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

1. In the upper-right corner of the AWS Management Console, check the AWS Region. It should be the same as the one where you created your EC2 instance.

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

1. Choose **Create database**.

1. On the **Create database** page, choose **Standard create**.

1. For **Engine options**, choose **MySQL**.  
![\[Select engine type\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/tutorial-create-mysql.png)

1. For **Templates**, choose **Free tier** or **Sandbox**. **Free tier** appears for free plan accounts. **Sandbox** appears for paid plan accounts.  
![\[Select template\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/tutorial-create-template.png)

1. In the **Availability and durability** section, keep the defaults.

1. In the **Settings** section, set these values:
   + **DB instance identifier** – Type **tutorial-db-instance**.
   + **Master username** – Type **tutorial\$1user**.
   + **Auto generate a password** – Leave the option turned off.
   + **Master password** – Type a password.
   + **Confirm password** – Retype the password.  
![\[Settings sections\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Settings.png)

1. In the **Instance configuration** section, set these values:
   + **Burstable classes (includes t classes)**
   + **db.t3.micro**  
![\[Instance configuration section\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_DB_instance_micro.png)

1. In the **Storage** section, keep the defaults.

1. In the **Connectivity** section, set these values and keep the other values as their defaults:
   + For **Compute resource**, choose **Connect to an EC2 compute resource**.
   + For **EC2 instance**, choose the EC2 instance you created previously, such as **tutorial-ec2-instance-web-server**.  
![\[Connectivity section\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Connectivity.png)

1. In the **Database authentication** section, make sure **Password authentication** is selected.

1. Open the **Additional configuration** section, and enter **sample** for **Initial database name**. Keep the default settings for the other options.

1. To create your MySQL DB instance, choose **Create database**.

   Your new DB instance appears in the **Databases** list with the status **Creating**.

1. Wait for the **Status** of your new DB instance to show as **Available**. Then choose the DB instance name to show its details.

1. In the **Connectivity & security** section, view the **Endpoint** and **Port** of the DB instance.  
![\[DB instance details\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Endpoint_Port.png)

   Note the endpoint and port for your DB instance. You use this information to connect your web server to your DB instance.

1. Complete [Install a web server on your EC2 instance](CHAP_Tutorials.WebServerDB.CreateWebServer.md).

------
#### [ RDS for PostgreSQL ]

**To create a PostgreSQL DB instance**

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

1. In the upper-right corner of the AWS Management Console, check the AWS Region. It should be the same as the one where you created your EC2 instance.

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

1. Choose **Create database**.

1. On the **Create database** page, choose **Standard create**.

1. For **Engine options**, choose **PostgreSQL**.  
![\[Select engine type\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/tutorial-create-postgres.png)

1. For **Templates**, choose **Free tier** or **Sandbox**. **Free tier** appears for free plan accounts. **Sandbox** appears for paid plan accounts.  
![\[Select template\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/tutorial-create-template.png)

1. In the **Availability and durability** section, keep the defaults.

1. In the **Settings** section, set these values:
   + **DB instance identifier** – Type **tutorial-db-instance**.
   + **Master username** – Type **tutorial\$1user**.
   + **Auto generate a password** – Leave the option turned off.
   + **Master password** – Type a password.
   + **Confirm password** – Retype the password.  
![\[Settings sections\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Settings.png)

1. In the **Instance configuration** section, set these values:
   + **Burstable classes (includes t classes)**
   + **db.t3.micro**  
![\[Instance configuration section\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_DB_instance_micro.png)

1. In the **Storage** section, keep the defaults.

1. In the **Connectivity** section, set these values and keep the other values as their defaults:
   + For **Compute resource**, choose **Connect to an EC2 compute resource**.
   + For **EC2 instance**, choose the EC2 instance you created previously, such as **tutorial-ec2-instance-web-server**.  
![\[Connectivity section\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Connectivity.png)

1. In the **Database authentication** section, make sure **Password authentication** is selected.

1. Open the **Additional configuration** section, and enter **sample** for **Initial database name**. Keep the default settings for the other options.

1. To create your PostgreSQL DB instance, choose **Create database**.

   Your new DB instance appears in the **Databases** list with the status **Creating**.

1. Wait for the **Status** of your new DB instance to show as **Available**. Then choose the DB instance name to show its details.

1. In the **Connectivity & security** section, view the **Endpoint** and **Port** of the DB instance.  
![\[DB instance details\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/Tutorial_WebServer_Endpoint_Port_postgres.png)

   Note the endpoint and port for your DB instance. You use this information to connect your web server to your DB instance.

1. Complete [Install a web server on your EC2 instance](CHAP_Tutorials.WebServerDB.CreateWebServer.md).

------

# Install a web server on your EC2 instance
<a name="CHAP_Tutorials.WebServerDB.CreateWebServer"></a>

Install a web server on the EC2 instance you created in [Launch an EC2 instance to connect with your DB instance](CHAP_Tutorials.WebServerDB.LaunchEC2.md). The web server connects to the Amazon RDS DB instance that you created in [Create an Amazon RDS DB instance](CHAP_Tutorials.WebServerDB.CreateDBInstance.md). 

## Install an Apache web server with PHP and MariaDB
<a name="CHAP_Tutorials.WebServerDB.CreateWebServer.Apache"></a>

Connect to your EC2 instance and install the web server.

**To connect to your EC2 instance and install the Apache web server with PHP**

1. Connect to the EC2 instance that you created earlier by following the steps in [Connect to your Linux instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html) in the *Amazon EC2 User Guide*.

   We recommend that you connect to your EC2 instance using SSH. If the SSH client utility is installed on Windows, Linux, or Mac, you can connect to the instance using the following command format:

   ```
   ssh -i location_of_pem_file ec2-user@ec2-instance-public-dns-name
   ```

   For example, assume that `ec2-database-connect-key-pair.pem` is stored in `/dir1` on Linux, and the public IPv4 DNS for your EC2 instance is `ec2-12-345-678-90.compute-1.amazonaws.com`. Your SSH command would look as follows:

   ```
   ssh -i /dir1/ec2-database-connect-key-pair.pem ec2-user@ec2-12-345-678-90.compute-1.amazonaws.com
   ```

1. Get the latest bug fixes and security updates by updating the software on your EC2 instance. To do this, use the following command.
**Note**  
The `-y` option installs the updates without asking for confirmation. To examine updates before installing, omit this option.

   ```
   sudo dnf update -y
   ```

1. After the updates complete, install the Apache web server, PHP, and MariaDB or PostgreSQL software using the following commands. This command installs multiple software packages and related dependencies at the same time.

------
#### [ MariaDB & MySQL ]

   ```
   sudo dnf install -y httpd php php-mysqli mariadb105
   ```

------
#### [ PostgreSQL ]

   ```
   sudo dnf install -y httpd php php-pgsql postgresql15
   ```

------

   If you receive an error, your instance probably wasn't launched with an Amazon Linux 2023 AMI. You might be using the Amazon Linux 2 AMI instead. You can view your version of Amazon Linux using the following command.

   ```
   cat /etc/system-release
   ```

   For more information, see [Updating instance software](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/install-updates.html).

1. Start the web server with the command shown following.

   ```
   sudo systemctl start httpd
   ```

   You can test that your web server is properly installed and started. To do this, enter the public Domain Name System (DNS) name of your EC2 instance in the address bar of a web browser, for example: `http://ec2-42-8-168-21.us-west-1.compute.amazonaws.com`. If your web server is running, then you see the Apache test page. 

   If you don't see the Apache test page, check your inbound rules for the VPC security group that you created in [Tutorial: Create a VPC for use with a DB instance (IPv4 only)](CHAP_Tutorials.WebServerDB.CreateVPC.md). Make sure that your inbound rules include one allowing HTTP (port 80) access for the IP address to connect to the web server.
**Note**  
The Apache test page appears only when there is no content in the document root directory, `/var/www/html`. After you add content to the document root directory, your content appears at the public DNS address of your EC2 instance. Before this point, it appears on the Apache test page.

1. Configure the web server to start with each system boot using the `systemctl` command.

   ```
   sudo systemctl enable httpd
   ```

To allow `ec2-user` to manage files in the default root directory for your Apache web server, modify the ownership and permissions of the `/var/www` directory. There are many ways to accomplish this task. In this tutorial, you add `ec2-user` to the `apache` group, to give the `apache` group ownership of the `/var/www` directory and assign write permissions to the group.

**To set file permissions for the Apache web server**

1. Add the `ec2-user` user to the `apache` group.

   ```
   sudo usermod -a -G apache ec2-user
   ```

1. Log out to refresh your permissions and include the new `apache` group.

   ```
   exit
   ```

1. Log back in again and verify that the `apache` group exists with the `groups` command.

   ```
   groups
   ```

   Your output looks similar to the following:

   ```
   ec2-user adm wheel apache systemd-journal
   ```

1. Change the group ownership of the `/var/www` directory and its contents to the `apache` group.

   ```
   sudo chown -R ec2-user:apache /var/www
   ```

1. Change the directory permissions of `/var/www` and its subdirectories to add group write permissions and set the group ID on subdirectories created in the future.

   ```
   sudo chmod 2775 /var/www
   find /var/www -type d -exec sudo chmod 2775 {} \;
   ```

1. Recursively change the permissions for files in the `/var/www` directory and its subdirectories to add group write permissions.

   ```
   find /var/www -type f -exec sudo chmod 0664 {} \;
   ```

Now, `ec2-user` (and any future members of the `apache` group) can add, delete, and edit files in the Apache document root. This makes it possible for you to add content, such as a static website or a PHP application. 

**Note**  
A web server running the HTTP protocol provides no transport security for the data that it sends or receives. When you connect to an HTTP server using a web browser, much information is visible to eavesdroppers anywhere along the network pathway. This information includes the URLs that you visit, the content of web pages that you receive, and the contents (including passwords) of any HTML forms.   
The best practice for securing your web server is to install support for HTTPS (HTTP Secure). This protocol protects your data with SSL/TLS encryption. For more information, see [ Tutorial: Configure SSL/TLS with the Amazon Linux AMI](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/SSL-on-amazon-linux-ami.html) in the *Amazon EC2 User Guide*.

## Connect your Apache web server to your DB instance
<a name="CHAP_Tutorials.WebServerDB.CreateWebServer.PHPContent"></a>

Next, you add content to your Apache web server that connects to your Amazon RDS DB instance.

**To add content to the Apache web server that connects to your DB instance**

1. While still connected to your EC2 instance, change the directory to `/var/www` and create a new subdirectory named `inc`.

   ```
   cd /var/www
   mkdir inc
   cd inc
   ```

1. Create a new file in the `inc` directory named `dbinfo.inc`, and then edit the file by calling nano (or the editor of your choice).

   ```
   >dbinfo.inc
   nano dbinfo.inc
   ```

1. Add the following contents to the `dbinfo.inc` file. Here, *db\$1instance\$1endpoint* is your DB instance endpoint, without the port, for your DB instance.
**Note**  
We recommend placing the user name and password information in a folder that isn't part of the document root for your web server. Doing this reduces the possibility of your security information being exposed.  
Make sure to change `master password` to a suitable password in your application.

   ```
   <?php
   
   define('DB_SERVER', 'db_instance_endpoint');
   define('DB_USERNAME', 'tutorial_user');
   define('DB_PASSWORD', 'master password');
   define('DB_DATABASE', 'sample');
   ?>
   ```

1. Save and close the `dbinfo.inc` file. If you are using nano, save and close the file by using Ctrl\$1S and Ctrl\$1X.

1. Change the directory to `/var/www/html`.

   ```
   cd /var/www/html
   ```

1. Create a new file in the `html` directory named `SamplePage.php`, and then edit the file by calling nano (or the editor of your choice).

   ```
   >SamplePage.php
   nano SamplePage.php
   ```

1. Add the following contents to the `SamplePage.php` file:

------
#### [ MariaDB & MySQL ]

   ```
   <?php include "../inc/dbinfo.inc"; ?>
   <html>
   <body>
   <h1>Sample page</h1>
   <?php
   
     /* Connect to MySQL and select the database. */
     $connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
   
     if (mysqli_connect_errno()) echo "Failed to connect to MySQL: " . mysqli_connect_error();
   
     $database = mysqli_select_db($connection, DB_DATABASE);
   
     /* Ensure that the EMPLOYEES table exists. */
     VerifyEmployeesTable($connection, DB_DATABASE);
   
     /* If input fields are populated, add a row to the EMPLOYEES table. */
     $employee_name = htmlentities($_POST['NAME']);
     $employee_address = htmlentities($_POST['ADDRESS']);
   
     if (strlen($employee_name) || strlen($employee_address)) {
       AddEmployee($connection, $employee_name, $employee_address);
     }
   ?>
   
   <!-- Input form -->
   <form action="<?PHP echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
     <table border="0">
       <tr>
         <td>NAME</td>
         <td>ADDRESS</td>
       </tr>
       <tr>
         <td>
           <input type="text" name="NAME" maxlength="45" size="30" />
         </td>
         <td>
           <input type="text" name="ADDRESS" maxlength="90" size="60" />
         </td>
         <td>
           <input type="submit" value="Add Data" />
         </td>
       </tr>
     </table>
   </form>
   
   <!-- Display table data. -->
   <table border="1" cellpadding="2" cellspacing="2">
     <tr>
       <td>ID</td>
       <td>NAME</td>
       <td>ADDRESS</td>
     </tr>
   
   <?php
   
   $result = mysqli_query($connection, "SELECT * FROM EMPLOYEES");
   
   while($query_data = mysqli_fetch_row($result)) {
     echo "<tr>";
     echo "<td>",$query_data[0], "</td>",
          "<td>",$query_data[1], "</td>",
          "<td>",$query_data[2], "</td>";
     echo "</tr>";
   }
   ?>
   
   </table>
   
   <!-- Clean up. -->
   <?php
   
     mysqli_free_result($result);
     mysqli_close($connection);
   
   ?>
   
   </body>
   </html>
   
   
   <?php
   
   /* Add an employee to the table. */
   function AddEmployee($connection, $name, $address) {
      $n = mysqli_real_escape_string($connection, $name);
      $a = mysqli_real_escape_string($connection, $address);
   
      $query = "INSERT INTO EMPLOYEES (NAME, ADDRESS) VALUES ('$n', '$a');";
   
      if(!mysqli_query($connection, $query)) echo("<p>Error adding employee data.</p>");
   }
   
   /* Check whether the table exists and, if not, create it. */
   function VerifyEmployeesTable($connection, $dbName) {
     if(!TableExists("EMPLOYEES", $connection, $dbName))
     {
        $query = "CREATE TABLE EMPLOYEES (
            ID int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
            NAME VARCHAR(45),
            ADDRESS VARCHAR(90)
          )";
   
        if(!mysqli_query($connection, $query)) echo("<p>Error creating table.</p>");
     }
   }
   
   /* Check for the existence of a table. */
   function TableExists($tableName, $connection, $dbName) {
     $t = mysqli_real_escape_string($connection, $tableName);
     $d = mysqli_real_escape_string($connection, $dbName);
   
     $checktable = mysqli_query($connection,
         "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = '$t' AND TABLE_SCHEMA = '$d'");
   
     if(mysqli_num_rows($checktable) > 0) return true;
   
     return false;
   }
   ?>
   ```

------
#### [ PostgreSQL ]

   ```
   <?php include "../inc/dbinfo.inc"; ?>
   
   <html>
   <body>
   <h1>Sample page</h1>
   <?php
   
   /* Connect to PostgreSQL and select the database. */
   $constring = "host=" . DB_SERVER . " dbname=" . DB_DATABASE . " user=" . DB_USERNAME . " password=" . DB_PASSWORD ;
   $connection = pg_connect($constring);
   
   if (!$connection){
    echo "Failed to connect to PostgreSQL";
    exit;
   }
   
   /* Ensure that the EMPLOYEES table exists. */
   VerifyEmployeesTable($connection, DB_DATABASE);
   
   /* If input fields are populated, add a row to the EMPLOYEES table. */
   $employee_name = htmlentities($_POST['NAME']);
   $employee_address = htmlentities($_POST['ADDRESS']);
   
   if (strlen($employee_name) || strlen($employee_address)) {
     AddEmployee($connection, $employee_name, $employee_address);
   }
   
   ?>
   
   <!-- Input form -->
   <form action="<?PHP echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
     <table border="0">
       <tr>
         <td>NAME</td>
         <td>ADDRESS</td>
       </tr>
       <tr>
         <td>
       <input type="text" name="NAME" maxlength="45" size="30" />
         </td>
         <td>
       <input type="text" name="ADDRESS" maxlength="90" size="60" />
         </td>
         <td>
       <input type="submit" value="Add Data" />
         </td>
       </tr>
     </table>
   </form>
   <!-- Display table data. -->
   <table border="1" cellpadding="2" cellspacing="2">
     <tr>
       <td>ID</td>
       <td>NAME</td>
       <td>ADDRESS</td>
     </tr>
   
   <?php
   
   $result = pg_query($connection, "SELECT * FROM EMPLOYEES");
   
   while($query_data = pg_fetch_row($result)) {
     echo "<tr>";
     echo "<td>",$query_data[0], "</td>",
          "<td>",$query_data[1], "</td>",
          "<td>",$query_data[2], "</td>";
     echo "</tr>";
   }
   ?>
   </table>
   
   <!-- Clean up. -->
   <?php
   
     pg_free_result($result);
     pg_close($connection);
   ?>
   </body>
   </html>
   
   
   <?php
   
   /* Add an employee to the table. */
   function AddEmployee($connection, $name, $address) {
      $n = pg_escape_string($name);
      $a = pg_escape_string($address);
      echo "Forming Query";
      $query = "INSERT INTO EMPLOYEES (NAME, ADDRESS) VALUES ('$n', '$a');";
   
      if(!pg_query($connection, $query)) echo("<p>Error adding employee data.</p>"); 
   }
   
   /* Check whether the table exists and, if not, create it. */
   function VerifyEmployeesTable($connection, $dbName) {
     if(!TableExists("EMPLOYEES", $connection, $dbName))
     {
        $query = "CREATE TABLE EMPLOYEES (
            ID serial PRIMARY KEY,
            NAME VARCHAR(45),
            ADDRESS VARCHAR(90)
          )";
   
        if(!pg_query($connection, $query)) echo("<p>Error creating table.</p>"); 
     }
   }
   /* Check for the existence of a table. */
   function TableExists($tableName, $connection, $dbName) {
     $t = strtolower(pg_escape_string($tableName)); //table name is case sensitive
     $d = pg_escape_string($dbName); //schema is 'public' instead of 'sample' db name so not using that
   
     $query = "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = '$t';";
     $checktable = pg_query($connection, $query);
   
     if (pg_num_rows($checktable) >0) return true;
     return false;
   
   }
   ?>
   ```

------

1. Save and close the `SamplePage.php` file.

1. Verify that your web server successfully connects to your DB instance by opening a web browser and browsing to `http://EC2 instance endpoint/SamplePage.php`, for example: `http://ec2-12-345-67-890.us-west-2.compute.amazonaws.com/SamplePage.php`.

You can use `SamplePage.php` to add data to your DB instance. The data that you add is then displayed on the page. To verify that the data was inserted into the table, install MySQL client on the Amazon EC2 instance. Then connect to the DB instance and query the table. 

For information about installing the MySQL client and connecting to a DB instance, see [Connecting to your MySQL DB instance](USER_ConnectToInstance.md).

To make sure that your DB instance is as secure as possible, verify that sources outside of the VPC can't connect to your DB instance. 

After you have finished testing your web server and your database, you should delete your DB instance and your Amazon EC2 instance.
+ To delete a DB instance, follow the instructions in [Deleting a DB instance](USER_DeleteInstance.md). You don't need to create a final snapshot.
+ To terminate an Amazon EC2 instance, follow the instruction in [Terminate your instance](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/terminating-instances.html) in the *Amazon EC2 User Guide*.

# Tutorial: Using a Lambda function to access an Amazon RDS database
<a name="rds-lambda-tutorial"></a>

In this tutorial, you use a Lambda function to write data to an [Amazon Relational Database Service](https://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html) (Amazon RDS) database through RDS Proxy. Your Lambda function reads records from an Amazon Simple Queue Service (Amazon SQS) queue and writes a new item to a table in your database whenever a message is added. In this example, you use the AWS Management Console to manually add messages to your queue. The following diagram shows the AWS resources you use to complete the tutorial.

![\[\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/TUT_Lambda_1.png)


With Amazon RDS, you can run a managed relational database in the cloud using common database products like Microsoft SQL Server, MariaDB, MySQL, Oracle Database, and PostgreSQL. By using Lambda to access your database, you can read and write data in response to events, such as a new customer registering with your website. Your function, database instance, and proxy scale automatically to meet periods of high demand.

To complete this tutorial, you carry out the following tasks:

1. Launch an RDS for MySQL database instance and a proxy in your AWS account's default VPC.

1. Create and test a Lambda function that creates a new table in your database and writes data to it.

1. Create an Amazon SQS queue and configure it to invoke your Lambda function whenever a new message is added.

1. Test the complete setup by adding messages to your queue using the AWS Management Console and monitoring the results using CloudWatch Logs.

By completing these steps, you learn:
+ How to use Amazon RDS to create a database instance and a proxy, and connect a Lambda function to the proxy.
+ How to use Lambda to perform create and read operations on an Amazon RDS database.
+ How to use Amazon SQS to invoke a Lambda function.

You can complete this tutorial using the AWS Management Console or the AWS Command Line Interface (AWS CLI).

## Prerequisites
<a name="vpc-rds-prereqs"></a>

Before you begin, complete the steps in the following sections:
+ [Sign up for an AWS account](CHAP_SettingUp.md#sign-up-for-aws)
+ [Create a user with administrative access](CHAP_SettingUp.md#create-an-admin)

## Create an Amazon RDS DB instance
<a name="vpc-rds-create-RDS-instance"></a>

![\[\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/TUT_Lambda_step1.png)


An Amazon RDS DB instance is an isolated database environment running in the AWS Cloud. An instance can contain one or more user-created databases. Unless you specify otherwise, Amazon RDS creates new database instances in the default VPC included in your AWS account. For more information about Amazon VPC, see the [Amazon Virtual Private Cloud User Guide](https://docs.aws.amazon.com/vpc/latest/userguide/what-is-amazon-vpc.html).

In this tutorial, you create a new instance in your AWS account's default VPC and create a database named `ExampleDB` in that instance. You can create your DB instance and database using either the AWS Management Console or the AWS CLI.

**To create a database instance**

1. Open the Amazon RDS console and choose **Create database**.

1. Leave the **Standard create** option selected, then in **Engine options**, choose **MySQL**.

1. In **Templates**, choose **Free tier** or **Sandbox**. **Free tier** appears for free tier accounts. **Sandbox** appears for paid plan accounts.

1. In **Settings**, for **DB instance identifier**, enter **MySQLForLambda**.

1. Set your username and password by doing the following:

   1. In **Credentials settings**, leave **Master username** set to `admin`.

   1. For **Master password**, enter and confirm a password to access your database.

1. Specify the database name by doing the following:
   + Leave all the remaining default options selected and scroll down to the **Additional configuration** section.
   + Expand this section and enter **ExampleDB** as the **Initial database name**.

1. Leave all the remaining default options selected and choose **Create database**.

## Create Lambda function and proxy
<a name="auto-create-Lambda"></a>

![\[\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/TUT_Lambda_step2.png)


You can use the RDS console to create a Lambda function and a proxy in the same VPC as the database. 

**Note**  
You can only create these associated resources when your database has completed creation and is in **Available** status.

**To create an associated function and proxy**

1. From the **Databases** page, check if your database is in the **Available** status. If so, proceed to the next step. Else, wait till your database is available.

1. Select your database and choose **Set up Lambda connection** from **Actions**.

1. In the **Set up Lambda connection** page, choose **Create new function**.

   Set the **New Lambda function name** to **LambdaFunctionWithRDS**.

1. In the **RDS Proxy** section, select the **Connect using RDS Proxy** option. Further choose **Create new proxy**.
   + For **Database credentials**, choose **Database username and password**.
   + For **Username**, specify `admin`.
   + For **Password**, enter the password you created for your database instance. 

1. Select **Set up** to complete the proxy and Lambda function creation.

The wizard completes the set up and provides a link to the Lambda console to review your new function. Note the proxy endpoint before switching to the Lambda console.

## Create a function execution role
<a name="vpc-rds-create-execution-role"></a>

![\[\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/TUT_Lambda_step3.png)


Before you create your Lambda function, you create an execution role to give your function the necessary permissions. For this tutorial, Lambda needs permission to manage the network connection to the VPC containing your database instance and to poll messages from an Amazon SQS queue.

To give your Lambda function the permissions it needs, this tutorial uses IAM managed policies. These are policies that grant permissions for many common use cases and are available in your AWS account. For more information about using managed policies, see [Policy best practices](security_iam_id-based-policy-examples.md#security_iam_service-with-iam-policy-best-practices).

**To create the Lambda execution role**

1. Open the [Roles](https://console.aws.amazon.com/iamv2/home#/roles) page of the IAM console and choose **Create role**.

1. For the **Trusted entity type**, choose **AWS service**, and for the **Use case**, choose **Lambda**.

1. Choose **Next**.

1. Add the IAM managed policies by doing the following:

   1. Using the policy search box, search for **AWSLambdaSQSQueueExecutionRole**.

   1. In the results list, select the check box next to the role, then choose **Clear filters**.

   1. Using the policy search box, search for **AWSLambdaVPCAccessExecutionRole**.

   1. In the results list, select the check box next to the role, then choose **Next**.

1. For the **Role name**, enter **lambda-vpc-sqs-role**, then choose **Create role**.

Later in the tutorial, you need the Amazon Resource Name (ARN) of the execution role you just created.

**To find the execution role ARN**

1. Open the [Roles](https://console.aws.amazon.com/iamv2/home#/roles) page of the IAM console and choose your role (`lambda-vpc-sqs-role`).

1.  Copy the **ARN** displayed in the **Summary** section.

## Create a Lambda deployment package
<a name="vpc-rds-create-deployment-package"></a>

![\[\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/TUT_Lambda_step4.png)


The following example Python code uses the [PyMySQL](https://pymysql.readthedocs.io/en/latest/) package to open a connection to your database. The first time you invoke your function, it also creates a new table called `Customer`. The table uses the following schema, where `CustID` is the primary key:

```
Customer(CustID, Name)
```

The function also uses PyMySQL to add records to this table. The function adds records using customer IDs and names specified in messages you will add to your Amazon SQS queue.

The code creates the connection to your database outside of the handler function. Creating the connection in the initialization code allows the connection to be re-used by subsequent invocations of your function and improves performance. In a production application, you can also use [provisioned concurrency](https://docs.aws.amazon.com/lambda/latest/dg/provisioned-concurrency.html) to initialize a requested number of database connections. These connections are available as soon as your function is invoked.

```
import sys
import logging
import pymysql
import json
import os

# rds settings
user_name = os.environ['USER_NAME']
password = os.environ['PASSWORD']
rds_proxy_host = os.environ['RDS_PROXY_HOST']
db_name = os.environ['DB_NAME']

logger = logging.getLogger()
logger.setLevel(logging.INFO)

# create the database connection outside of the handler to allow connections to be
# re-used by subsequent function invocations.
try:
        conn = pymysql.connect(host=rds_proxy_host, user=user_name, passwd=password, db=db_name, connect_timeout=5)
except pymysql.MySQLError as e:
    logger.error("ERROR: Unexpected error: Could not connect to MySQL instance.")
    logger.error(e)
    sys.exit(1)

logger.info("SUCCESS: Connection to RDS for MySQL instance succeeded")

def lambda_handler(event, context):
    """
    This function creates a new RDS database table and writes records to it
    """
    message = event['Records'][0]['body']
    data = json.loads(message)
    CustID = data['CustID']
    Name = data['Name']

    item_count = 0
    sql_string = f"insert into Customer (CustID, Name) values(%s, %s)"

    with conn.cursor() as cur:
        cur.execute("create table if not exists Customer ( CustID  int NOT NULL, Name varchar(255) NOT NULL, PRIMARY KEY (CustID))")
        cur.execute(sql_string, (CustID, Name))
        conn.commit()
        cur.execute("select * from Customer")
        logger.info("The following items have been added to the database:")
        for row in cur:
            item_count += 1
            logger.info(row)
    conn.commit()

    return "Added %d items to RDS for MySQL table" %(item_count)
```

**Note**  
In this example, your database access credentials are stored as environment variables. In production applications, we recommend that you use [AWS Secrets Manager](https://docs.aws.amazon.com/secretsmanager/latest/userguide/intro.html) as a more secure option. Note that if your Lambda function is in a VPC, to connect to Secrets Manager you need to create a VPC endpoint. See [ How to connect to Secrets Manager service within a Virtual Private Cloud](https://aws.amazon.com/blogs/security/how-to-connect-to-aws-secrets-manager-service-within-a-virtual-private-cloud/) to learn more. 

 To include the PyMySQL dependency with your function code, create a .zip deployment package. The following commands work for Linux, macOS, or Unix:

**To create a .zip deployment package**

1. Save the example code as a file named `lambda_function.py`. 

1. In the same directory in which you created your `lambda_function.py` file, create a new directory named `package` and install the PyMySQL library. 

   ```
   mkdir package
   pip install --target package pymysql
   ```

1. Create a zip file containing your application code and the PyMySQL library. In Linux or MacOS, run the following CLI commands. In Windows, use your preferred zip tool to create the `lambda_function.zip` file. Your `lambda_function.py` source code file and the folders containing your dependencies must be installed at the root of the .zip file.

   ```
   cd package
   zip -r ../lambda_function.zip .
   cd ..
   zip lambda_function.zip lambda_function.py
   ```

   You can also create your deployment package using a Python virtual environment. See [Deploy Python Lambda functions with .zip file archives](https://docs.aws.amazon.com/lambda/latest/dg/python-package.html#python-package-create-package-with-dependency).

## Update the Lambda function
<a name="vpc-rds-update-function"></a>

Using the .zip package you just created, you now update your Lambda function using the Lambda console. To enable your function to access your database, you also need to configure environment variables with your access credentials.

**To update the Lambda function**

1. Open the [Functions](https://console.aws.amazon.com/lambda/home#/functions) page of the Lambda console and choose your function `LambdaFunctionWithRDS`.

1. In the **Runtime settings** tab, select **Edit** to change the **Runtime** of the function to **Python 3.10**.

1. Change the **Handler** to `lambda_function.lambda_handler`.

1. In the **Code** tab, choose **Upload from** and then **.zip file**.

1. Select the `lambda_function.zip` file you created in the previous stage and choose **Save**.

Now configure the function with the execution role you created earlier. This grants the function the permissions it needs to access your database instance and poll an Amazon SQS queue.

**To configure the function's execution role**

1. In the [Functions](https://console.aws.amazon.com/lambda/home#/functions) page of the Lambda console, select the **Configuration** tab, then choose **Permissions**.

1. In **Execution role**, choose **Edit**.

1. In **Existing role**, choose your execution role (`lambda-vpc-sqs-role`).

1. Choose **Save**.

**To configure your function's environment variables**

1. In the [Functions](https://console.aws.amazon.com/lambda/home#/functions) page of the Lambda console, select the **Configuration** tab, then choose **Environment variables**.

1. Choose **Edit**.

1. To add your database access credentials, do the following:

   1. Choose **Add environment variable**, then for **Key** enter **USER\$1NAME** and for **Value** enter **admin**.

   1. Choose **Add environment variable**, then for **Key** enter **DB\$1NAME** and for **Value** enter **ExampleDB**.

   1. Choose **Add environment variable**, then for **Key** enter **PASSWORD** and for **Value** enter the password you chose when you created your database.

   1. Choose **Add environment variable**, then for **Key** enter **RDS\$1PROXY\$1HOST** and for **Value** enter the RDS Proxy endpoint you noted earlier.

   1. Choose **Save**.

## Test your Lambda function in the console
<a name="vpc-rds-test-function"></a>

![\[\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/TUT_Lambda_step5.png)


You can now use the Lambda console to test your function. You create a test event which mimics the data your function will receive when you invoke it using Amazon SQS in the final stage of the tutorial. Your test event contains a JSON object specifying a customer ID and customer name to add to the `Customer` table your function creates.

**To test the Lambda function**

1. Open the [Functions](https://console.aws.amazon.com/lambda/home#/functions) page of the Lambda console and choose your function.

1. Choose the **Test** section.

1. Choose **Create new event** and enter **myTestEvent** for the event name.

1. Copy the following code into **Event JSON** and choose **Save**.

   ```
   {
     "Records": [
       {
         "messageId": "059f36b4-87a3-44ab-83d2-661975830a7d",
         "receiptHandle": "AQEBwJnKyrHigUMZj6rYigCgxlaS3SLy0a...",
         "body": "{\n     \"CustID\": 1021,\n     \"Name\": \"Martha Rivera\"\n}",
         "attributes": {
           "ApproximateReceiveCount": "1",
           "SentTimestamp": "1545082649183",
           "SenderId": "AIDAIENQZJOLO23YVJ4VO",
           "ApproximateFirstReceiveTimestamp": "1545082649185"
         },
         "messageAttributes": {},
         "md5OfBody": "e4e68fb7bd0e697a0ae8f1bb342846b3",
         "eventSource": "aws:sqs",
         "eventSourceARN": "arn:aws:sqs:us-west-2:123456789012:my-queue",
         "awsRegion": "us-west-2"
       }
     ]
   }
   ```

1. Choose **Test**.

In the **Execution results** tab, you should see results similar to the following displayed in the **Function Logs**:

```
[INFO] 2023-02-14T19:31:35.149Z bdd06682-00c7-4d6f-9abb-89f4bbb4a27f The following items have been added to the database:
[INFO] 2023-02-14T19:31:35.149Z bdd06682-00c7-4d6f-9abb-89f4bbb4a27f (1021, 'Martha Rivera')
```

## Create an Amazon SQS queue
<a name="vpc-rds-create-queue"></a>

![\[\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/TUT_Lambda_step6.png)


You have successfully tested the integration of your Lambda function and Amazon RDS database instance. Now you create the Amazon SQS queue you will use to invoke your Lambda function in the final stage of the tutorial.

**To create the Amazon SQS queue (console)**

1. Open the [Queues](https://console.aws.amazon.com/sqs/v2/home#/queues) page of the Amazon SQS console and select **Create queue**.

1. Leave the **Type** as **Standard** and enter **LambdaRDSQueue** for the name of your queue.

1. Leave all the default options selected and choose **Create queue**.

## Create an event source mapping to invoke your Lambda function
<a name="vpc-rds-create-event-source-mapping"></a>

![\[\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/TUT_Lambda_step7.png)


An [event source mapping](https://docs.aws.amazon.com/lambda/latest/dg/invocation-eventsourcemapping.html) is a Lambda resource which reads items from a stream or queue and invokes a Lambda function. When you configure an event source mapping, you can specify a batch size so that records from your stream or queue are batched together into a single payload. In this example, you set the batch size to 1 so that your Lambda function is invoked every time you send a message to your queue. You can configure the event source mapping using either the AWS CLI or the Lambda console.

**To create an event source mapping (console)**

1. Open the [Functions](https://console.aws.amazon.com/lambda/home#/functions) page of the Lambda console and select your function (`LambdaFunctionWithRDS`).

1. In the **Function overview** section, choose **Add trigger**.

1. For the source, select **Amazon SQS**, then select the name of your queue (`LambdaRDSQueue`).

1. For **Batch size**, enter **1**.

1. Leave all the other options set to the default values and choose **Add**.

You are now ready to test your complete setup by adding a message to your Amazon SQS queue.

## Test and monitor your setup
<a name="vpc-rds-test-setup"></a>

![\[\]](http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/images/TUT_Lambda_step8.png)


To test your complete setup, add messages to your Amazon SQS queue using the console. You then use CloudWatch Logs to confirm that your Lambda function is writing records to your database as expected.

**To test and monitor your setup**

1. Open the [Queues](https://console.aws.amazon.com/sqs/v2/home#/queues) page of the Amazon SQS console and select your queue (`LambdaRDSQueue`).

1. Choose **Send and receive messages** and paste the following JSON into the **Message body** in the **Send message** section.

   ```
   {
       "CustID": 1054,
       "Name": "Richard Roe"
   }
   ```

1. Choose **Send message**.

   Sending your message to the queue will cause Lambda to invoke your function through your event source mapping. To confirm that Lambda has invoked your function as expected, use CloudWatch Logs to verify that the function has written the customer name and ID to your database table.

1. Open the [Log groups](https://console.aws.amazon.com/cloudwatch/home#logsV2:log-groups) page of the CloudWatch console and select the log group for your function (`/aws/lambda/LambdaFunctionWithRDS`).

1. In the **Log streams** section, choose the most recent log stream.

   Your table should contain two customer records, one from each invocation of your function. In the log stream, you should see messages similar to the following:

   ```
   [INFO] 2023-02-14T19:06:43.873Z 45368126-3eee-47f7-88ca-3086ae6d3a77 The following items have been added to the database:
   [INFO] 2023-02-14T19:06:43.873Z 45368126-3eee-47f7-88ca-3086ae6d3a77 (1021, 'Martha Rivera')
   [INFO] 2023-02-14T19:06:43.873Z 45368126-3eee-47f7-88ca-3086ae6d3a77 (1054, 'Richard Roe')
   ```

## Clean up your resources
<a name="rds-tutorial-cleanup"></a>

You can now delete the resources that you created for this tutorial, unless you want to retain them. By deleting AWS resources that you're no longer using, you prevent unnecessary charges to your AWS account.

**To delete the Lambda function**

1. Open the [Functions page](https://console.aws.amazon.com/lambda/home#/functions) of the Lambda console.

1. Select the function that you created.

1. Choose **Actions**, **Delete**.

1. Choose **Delete**.

**To delete the execution role**

1. Open the [Roles page](https://console.aws.amazon.com/iam/home#/roles) of the IAM console.

1. Select the execution role that you created.

1. Choose **Delete role**.

1. Choose **Yes, delete**.

**To delete the MySQL DB instance**

1. Open the [Databases page](https://console.aws.amazon.com//rds/home#databases:) of the Amazon RDS console.

1. Select the database you created.

1. Choose **Actions**, **Delete**.

1. Clear the **Create final snapshot** check box.

1. Enter **delete me** in the text box.

1. Choose **Delete**.

**To delete the Amazon SQS queue**

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

1. Select the queue you created.

1. Choose **Delete**.

1. Enter **delete** in the text box.

1. Choose **Delete**.