[Yandex Cloud documentation](../../index.md) > [Tutorials](../index.md) > [Serverless technologies](index.md) > Serverless-based backend > Creating a Yandex Cloud Postbox address and verifying domain ownership with Terraform

# Creating a Yandex Cloud Postbox address and verifying domain ownership with Terraform

In this tutorial, you will use Terraform to create an [address](../../postbox/concepts/glossary.md#adress) in [Yandex Cloud Postbox](../../postbox/index.md) and add [resource records](../../dns/concepts/resource-record.md#txt) to your domain’s [DNS zone](../../dns/concepts/dns-zone.md) to verify domain ownership and send emails.

You can add a resource record for domain ownership verification to [Yandex Cloud DNS](../../dns/index.md), if you have [delegated](#delegate) the domain, or with your domain registrar.

To access Yandex Cloud Postbox, the tutorial uses an API compatible with AWS SESv2, so the [AWS](https://github.com/hashicorp/terraform-provider-aws) provider is used to create and manage Yandex Cloud Postbox resources. To manage all other resources, you will use the [Yandex Cloud](https://github.com/yandex-cloud/terraform-provider-yandex) provider.

1. [Get your cloud ready](#before-you-begin).
1. [Delegate your domain to Cloud DNS](#delegate).
1. [Prepare keys for signing emails](#generate-keys).
1. [Create the infrastructure](#deploy).
1. [Test the service](#test).

If you no longer need the resources you created, [delete them](#clear-out).


## Get your cloud ready {#before-begin}

Sign up for Yandex Cloud and create a [billing account](../../billing/concepts/billing-account.md):
1. Navigate to the [management console](https://console.yandex.cloud) and log in to Yandex Cloud or create a new account.
1. On the **[Yandex Cloud Billing](https://center.yandex.cloud/billing/accounts)** page, make sure you have a billing account linked and it has the `ACTIVE` or `TRIAL_ACTIVE` [status](../../billing/concepts/billing-account-statuses.md). If you do not have a billing account, [create one](../../billing/quickstart/index.md) and [link](../../billing/operations/pin-cloud.md) a cloud to it.

If you have an active billing account, you can create or select a [folder](../../resource-manager/concepts/resources-hierarchy.md#folder) for your infrastructure on the [cloud page](https://console.yandex.cloud/cloud).

[Learn more about clouds and folders here](../../resource-manager/concepts/resources-hierarchy.md).


### Required paid resources {#paid-resources}

The costs to support the infrastructure for creating an address, verifying domain ownership, and sending emails include:
* Fee for sent [emails](../../postbox/concepts/index.md) (see [Yandex Cloud Postbox pricing](../../postbox/pricing.md)).
* Fee for public DNS queries and [DNS zones](../../dns/concepts/dns-zone.md) if using [Yandex Cloud DNS](../../dns/index.md) (see [Cloud DNS pricing](../../dns/pricing.md)).


## Delegate your domain to Cloud DNS {#delegate}

If you have a registered domain name, you can use Yandex Cloud DNS to manage the domain.

To delegate a domain to Cloud DNS, in your account on your domain registrar's website, specify the DNS server addresses in the domain settings:

* `ns1.yandexcloud.net`
* `ns2.yandexcloud.net`

Delegation does not take effect immediately. Internet provider servers normally update records within 24 hours (86,400 seconds). This depends on the TTL value which specifies how long domain records are cached.

You can check domain delegation using [Whois](https://www.reg.com/whois/check_site) or the `dig` utility:

```bash
dig +short NS example.com
```

Result:

```
ns2.yandexcloud.net.
ns1.yandexcloud.net.
```


## Prepare keys for signing emails {#generate-keys}

To sign emails, create an [RSA](https://en.wikipedia.org/wiki/RSA_(cryptosystem)) key. Use the key creation script, as the AWS provider expects the key not in [PEM](https://en.wikipedia.org/wiki/Privacy-Enhanced_Mail) format but as a string where line breaks and the first and last lines are removed.

1. Create a `generate-key.sh` script with the following contents:

   ```bash
   #!/bin/bash

   # Generate private key
   openssl genrsa -out raw_privatekey.pem 2048

   # Generate public key from the private key
   openssl rsa -in raw_privatekey.pem -pubout -out publickey.pem

   # Process private key for AWS (remove headers and line breaks)
   cat raw_privatekey.pem | grep -v "BEGIN" | grep -v "END" | tr -d '\n' > privatekey.pem

   # Format public key for DKIM DNS TXT record
   # Remove headers, strip newlines and concatenate for DNS TXT record
   DKIM_DNS_VALUE=$(cat publickey.pem | grep -v "BEGIN" | grep -v "END" | tr -d '\n')
   echo "$DKIM_DNS_VALUE" > dkim_dns_value.txt

   echo "Keys generated:"
   echo "- privatekey.pem (AWS-formatted private key)"
   echo "- publickey.pem (Public key)"
   echo "- raw_privatekey.pem (Original private key with headers)"
   echo "- dkim_dns_value.txt (Public key formatted for DKIM DNS TXT record)"
   ```

1. In the terminal, navigate to the directory with the script and run it:

   ```bash
   ./generate-key.sh
   ```

The script will create:
* `privatekey.pem`: Private key in the AWS provider’s format.
* `publickey.pem`: Public key.
* `raw_privatekey.pem`: Original private key.
* `dkim_dns_value.txt`: Value for creating a DKIM record.


## Create the infrastructure {#deploy}

With [Terraform](https://www.terraform.io/), you can quickly create a cloud infrastructure in Yandex Cloud and manage it using configuration files. These files store the infrastructure description written in HashiCorp Configuration Language (HCL). If you change the configuration files, Terraform automatically detects which part of your configuration is already deployed, and what should be added or removed.

Terraform is distributed under the [Business Source License](https://github.com/hashicorp/terraform/blob/main/LICENSE). The [Yandex Cloud provider for Terraform](https://github.com/yandex-cloud/terraform-provider-yandex) is distributed under the [MPL-2.0](https://www.mozilla.org/en-US/MPL/2.0/) license.

For more information about the provider resources, see the guides on the [Terraform](https://www.terraform.io/docs/providers/yandex/index.html) website or [its mirror](../../terraform/index.md).

To create your infrastructure via Terraform:
1. [Install Terraform](../infrastructure-management/terraform-quickstart.md#install-terraform), [get authentication credentials](../infrastructure-management/terraform-quickstart.md#get-credentials), and specify the source for installing the Yandex Cloud provider. For details, see [Configure your provider](../infrastructure-management/terraform-quickstart.md#configure-provider), step 1.
1. Prepare your infrastructure description files:

     1. Clone the repository containing the configuration files.

        ```bash
        git clone https://github.com/yandex-cloud-examples/yc-postbox-tf.git
        ```

     1. Navigate to the repository directory. It should now contain the following files:
        * `postbox-email-identity.tf`: New infrastructure configuration.
        * `postbox-email-identity.auto.tfvars`: User data file.

   For more on the properties of resources used in Terraform, see these provider guides:
   * [Service account](../../iam/concepts/users/service-accounts.md): [yandex_iam_service_account](../../terraform/resources/iam_service_account.md).
   * [Assigning access permissions](../../iam/concepts/access-control/roles.md): [yandex_resourcemanager_folder_iam_member](../../terraform/resources/resourcemanager_folder_iam_member.md).
   * [Static access key](../../iam/concepts/authorization/access-key.md): [yandex_iam_service_account_static_access_key](../../terraform/resources/iam_service_account_static_access_key.md).
   * [DNS zone](../../dns/concepts/dns-zone.md): [yandex_dns_zone](../../terraform/resources/dns_zone.md).
   * [DNS resource record](../../dns/concepts/resource-record.md): [yandex_dns_recordset](../../terraform/resources/dns_recordset.md).

1. In the `postbox-email-identity.auto.tfvars` file, set the following user-defined properties:
   * `folder_id`: [Folder ID](../../resource-manager/operations/folder/get-id.md).
   * `domain_signing_selector`: Selector for domain signing, e.g., `_postbox`.
   * `domain`: Domain for sending emails, e.g., `mail.example.com`.
   * `dns_zone_name`: Name of an existing DNS zone to which the record will be added.

1. Create the resources:

   1. In the terminal, navigate to the configuration file directory.
   1. Make sure the configuration is correct using this command:
   
      ```bash
      terraform validate
      ```
   
      If the configuration is valid, you will get this message:
   
      ```bash
      Success! The configuration is valid.
      ```
   
   1. Run this command:
   
      ```bash
      terraform plan
      ```
   
      You will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.
   1. Apply the configuration changes:
   
      ```bash
      terraform apply
      ```
   
   1. Type `yes` and press **Enter** to confirm the changes.

{% note info %}

If using a different DNS service, you need to add the DKIM record yourself as described in the service documentation. You can use the following Terraform code to get the DKIM record value:

```hcl
output "dkim_record" {
  value = {
    value = "v=DKIM1;h=sha256;k=rsa;p=${trim(local.public_key, "\n")}"
    name  = "${var.domain_signing_selector}._domainkey.${var.domain}"
    type  = "TXT"
    ttl   = 3600
  }
}
```

{% endnote %}

After creating the infrastructure, [test the service](#test).


## Test the service {#test}

Make sure the address was successfully created and send a test email:
1. In the [management console](https://console.yandex.cloud), select the folder where you created the address.
1. Navigate to **Cloud Postbox**.
1. Select the address you created and make sure the test status on the address page has changed to `Success`.
1. [Send](../../postbox/operations/send-email.md) a test email.


## How to delete the resources you created {#clear-out}

To stop paying for the resources you created:

1. Open the `postbox-email-identity.tf` file and delete your infrastructure description from it.
1. Apply the changes:

    1. In the terminal, navigate to the configuration file directory.
    1. Make sure the configuration is correct using this command:
    
       ```bash
       terraform validate
       ```
    
       If the configuration is valid, you will get this message:
    
       ```bash
       Success! The configuration is valid.
       ```
    
    1. Run this command:
    
       ```bash
       terraform plan
       ```
    
       You will see a list of resources and their properties. No changes will be made at this step. Terraform will show any errors in the configuration.
    1. Apply the configuration changes:
    
       ```bash
       terraform apply
       ```
    
    1. Type `yes` and press **Enter** to confirm the changes.