[Yandex Cloud documentation](../../../index.md) > [Tutorials](../../index.md) > [Security](../index.md) > [Storing a static access key in a Yandex Lockbox secret](index.md) > Terraform

# Using a Yandex Lockbox secret to store a static access key using Terraform

To [use a static access key](index.md) saved in a Yandex Lockbox secret using Terraform:

1. [Set up your environment](#prepare).
1. [Create your infrastructure](#deploy).
1. [Use the key from the Yandex Lockbox secret for your operations with the service](#use-key).

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


## Getting started {#before-you-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 infrastructure support costs include:

* Fee for storing one version of the Yandex Lockbox secret (see [Yandex Lockbox pricing](../../../lockbox/pricing.md#secrets)).
* Fee for data storage in Object Storage, data operations, and outgoing traffic (you will not be charged unless there is data in the bucket). See [Object Storage pricing](../../../storage/pricing.md#rules).


## Set up your environment {#prepare}

[Install](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html) the AWS CLI.

You do not need to configure the utility at this step. The required parameters, such as IDs and access keys, will be described and used in commands and environment variables further on in this guide.


## Create your 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 relevant documentation on the [Terraform](https://www.terraform.io/docs/providers/yandex/index.html) website or [its mirror](../../../terraform/index.md).

To create an infrastructure using Terraform:

1. [Install Terraform](../../infrastructure-management/terraform-quickstart.md#install-terraform), [get the authentication credentials](../../infrastructure-management/terraform-quickstart.md#get-credentials), and specify the source for installing the Yandex Cloud provider (see [Configure your provider](../../infrastructure-management/terraform-quickstart.md#configure-provider), Step 1).
1. Set up your infrastructure description file:

    {% list tabs group=infrastructure_description %}

    - Ready-made configuration {#ready}

      1. Clone the repository with configuration files.

          ```bash
          git clone https://github.com/yandex-cloud-examples/yc-static-keys-in-lockbox
          ```

      1. Navigate to the repository directory. It should now contain the `static-key-in-lockbox-config.tf` file with the new infrastructure configuration.

    - Manually {#manual}

      1. Create a folder for configuration files.
      1. Create a configuration file named `static-key-in-lockbox-config.tf` in the folder:

          {% cut "static-key-in-lockbox-config.tf" %}

          ```hcl
          # Declaring user-defined variables
          
          locals {
            zone      = "<availability_zone>"
            folder_id = "<folder_ID>"
          }
          
          terraform {
            required_providers {
              yandex = {
                source  = "yandex-cloud/yandex"
                version = ">= 0.47.0"
              }
            }
          }
          
          # Configuring a provider
          
          provider "yandex" {
            zone = local.zone
          }
          
          # Creating a service account and assigning roles
          
          resource "yandex_iam_service_account" "sa" {
            folder_id = local.folder_id
            name      = "storage-bucket-sa"
          }
          
          resource "yandex_resourcemanager_folder_iam_member" "sa-admin" {
            folder_id = local.folder_id
            role      = "storage.admin"
            member    = "serviceAccount:${yandex_iam_service_account.sa.id}"
          }
          
          resource "yandex_resourcemanager_folder_iam_member" "lockboxview" {
            folder_id = local.folder_id
            role      = "lockbox.payloadViewer"
            member    = "serviceAccount:${yandex_iam_service_account.sa.id}"
          }
          
          # Creating a secret
          
          resource "yandex_lockbox_secret" "my_secret" {
            name                = "static-key"
            folder_id           = local.folder_id
            deletion_protection = true
          }
          
          # Creating a static access key
          
          resource "yandex_iam_service_account_static_access_key" "sa-static-key" {
            service_account_id = yandex_iam_service_account.sa.id
            description        = "static access key for object storage"
            output_to_lockbox {
              secret_id            = yandex_lockbox_secret.my_secret.id
              entry_for_access_key = "key_id"
              entry_for_secret_key = "key"
            }
          }
          
          # Data source of the secret version
          
          data "yandex_lockbox_secret_version" "my_secret_version" {
            secret_id  = yandex_lockbox_secret.my_secret.id
            version_id = yandex_iam_service_account_static_access_key.sa-static-key.output_to_lockbox_version_id
            depends_on = [
              yandex_lockbox_secret.my_secret
            ]
          }
          
          # Output variables
          
          output "key_id" {
            value = data.yandex_lockbox_secret_version.my_secret_version.entries[1].text_value
          }
          
          output "key" {
            value = data.yandex_lockbox_secret_version.my_secret_version.entries[0].text_value
          }
          ```

          {% endcut %}

    {% endlist %}

    Learn more about the properties of Terraform resources in the relevant Terraform guides:

    * [Service account](../../../iam/concepts/users/service-accounts.md): [yandex_iam_service_account](../../../terraform/resources/iam_service_account.md).
    * Assigning a [role](../../../iam/concepts/access-control/roles.md) to a service account: [yandex_resourcemanager_folder_iam_member](../../../terraform/resources/resourcemanager_folder_iam_member.md).
    * [Secret](../../../terraform/resources/lockbox_secret.md): [yandex_lockbox_secret](../../../lockbox/concepts/secret.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).
    * [Secret version](../../../lockbox/concepts/secret.md#version): [yandex_lockbox_secret_version](../../../terraform/resources/lockbox_secret_version.md).

1. In the `static-key-in-lockbox-config.tf` file, set the following user-defined properties:
    * `zone_id`: [Availability zone](../../../overview/concepts/geo-scope.md).
    * `folder_id`: [Folder ID](../../../resource-manager/operations/folder/get-id.md).

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.

Once the infrastructure is created, [use the key from the secret for your operations with the service](#use-key).


## Use the key from the Yandex Lockbox secret for your operations with the service {#use-key}

The example below is for MacOS and Linux. To run it on Windows, [check the details on working with Bash in Microsoft Windows](../../../overview/concepts/console-syntax-guide.md).

Use the key from the Yandex Lockbox secret and create a bucket in Object Storage:

1. Save the key ID, secret key, and placement region to the AWS CLI environment variables:

    ```bash
    AWS_ACCESS_KEY_ID=$(terraform output key_id)
    AWS_SECRET_ACCESS_KEY=$(terraform output key)
    AWS_DEFAULT_REGION="ru-central1"
    ```

    The AWS CLI will use the environment variables you created for authentication when performing operations with the service resources.

1. Create a bucket in Object Storage, specifying a unique [bucket name](../../../storage/concepts/bucket.md#naming) in the command:

    {% list tabs group=instructions %}
    
    - AWS CLI {#aws-cli}
    
      ```bash
      aws --endpoint-url=https://storage.yandexcloud.net \
        s3 mb s3://<bucket_name>
      ```
    
      Result:
    
      ```bash
      make_bucket: my-first-bucket
      ```
    
    {% endlist %}
    
    This will create a new bucket in Object Storage. When creating a bucket, a static access key is used obtained from the Yandex Lockbox secret and saved in environment variables.
    
    You can also include the key ID, secret key, and placement region values directly in each AWS CLI command:

    {% list tabs group=instructions %}

    - AWS CLI {#aws-cli}

      ```bash
      AWS_ACCESS_KEY_ID=$(terraform output key_id) \
      AWS_SECRET_ACCESS_KEY=$(terraform output key) \
      AWS_DEFAULT_REGION="ru-central1" \
      aws --endpoint-url=https://storage.yandexcloud.net \
        s3 mb s3://<bucket_name>
      ```

      Result:

      ```bash
      make_bucket: my-first-bucket
      ```

    {% endlist %}


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

To stop paying for the resources you created:

1. [Delete](../../../storage/operations/buckets/delete.md) the bucket.
1. Open the `static-key-in-lockbox-config.tf` configuration 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.

#### See also {#see-also}

* [Using a Yandex Lockbox secret to store a static access key via the CLI](console.md)