[Yandex Cloud documentation](../../../index.md) > [Yandex Compute Cloud](../../index.md) > [Step-by-step guides](../index.md) > Using a VM > Using Yandex Cloud from within a VM

# Using Yandex Cloud from within a VM

This section describes how to use Yandex Cloud from within a [VM](../../concepts/vm.md) via the API or CLI.

To automate working with Yandex Cloud from within a VM, we recommend using [service accounts](../../../iam/concepts/users/service-accounts.md). This is secure, since you do not need to keep your token on the VM and can restrict access permissions for your service account.

Yandex Cloud provides simplified API and CLI authentication from within a VM for service accounts. To authenticate:
1. If you do not have a service account, [create one](../../../iam/operations/sa/create.md).
1. [Assign](../../../iam/operations/sa/assign-role-for-sa.md) to the service account a [role](../../../iam/concepts/access-control/roles.md) consistent with the actions you want to perform from within the VM. For example, for Compute Cloud resource management, this could be the `compute.admin` [role](../../../iam/roles-reference.md#compute-admin) for a folder or the primitive `editor` [role](../../security/index.md#primitive-roles).
1. [Link the service account](#link-sa-with-instance) to your VM.
1. [Get authenticated from within your VM](#auth-inside-vm).

## Link your service account {#link-sa-with-instance}

Link your service account to an existing or new VM.

{% note info %}

You can only link one service account to a virtual machine.

{% endnote %}

To link a service account to a VM, you need a permission to use this account. This permission comes with the [iam.serviceAccounts.user](../../../iam/security/index.md#iam-serviceAccounts-user) and [editor](../../../iam/roles-reference.md#editor) roles or higher.

### Linking to an existing VM {#link-with-exist-instance}

{% list tabs group=instructions %}

- Management console {#console}

  1. In the [management console](https://console.yandex.cloud), select the [folder](../../../resource-manager/concepts/resources-hierarchy.md#folder) the VM belongs to.
  1. Navigate to **Compute Cloud**.
  1. Click the VM name.
  1. In the top-right corner of the page, click ![image](../../../_assets/console-icons/pencil.svg) **Edit VM**.
  1. Under **Additional**, select an existing service account or create a new one.
  1. Click **Save changes**.

- CLI {#cli}

  If you do not have the Yandex Cloud CLI yet, [install and initialize it](../../../cli/quickstart.md#install).

  The folder used by default is the one specified when [creating](../../../cli/operations/profile/profile-create.md) the CLI profile. To change the default folder, use the `yc config set folder-id <folder_ID>` command. You can also specify a different folder for any command using `--folder-name` or `--folder-id`. If you access a resource by its name, the search will be limited to the default folder. If you access a resource by its ID, the search will be global, i.e., through all folders based on access permissions.

  Update the VM parameters by specifying the service account using `--service-account-name` or `--service-account-id`:

  ```bash
  yc compute instance update my-instance --service-account-name test
  ```

- Terraform {#tf}

  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).
  
  If you do not have Terraform yet, [install it and configure the Yandex Cloud provider](../../../tutorials/infrastructure-management/terraform-quickstart.md#install-terraform).
  
  
  To manage infrastructure using Terraform under a service account or user accounts (a Yandex account, a federated account, or a local user), [authenticate](../../../terraform/authentication.md) using the appropriate method.

  1. Open the Terraform configuration file with the description of the VM you want to link the service account to. See [an example of the VM configuration file](../vm-create/create-linux-vm.md#tf_1).
  1. In the section with the `yandex_compute_instance` resource description, add the `service_account_id` parameter and specify the service account ID:

      ```hcl
      resource "yandex_compute_instance" "vm-1" {
        ...
        service_account_id = "<service_account_ID>"
        ...
      }
      ```

  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.

     Terraform will change all required resources. You can check the new resources in the [management console](https://console.yandex.cloud).

  For more information about the `yandex_compute_instance` resource properties, see [this provider guide](../../../terraform/data-sources/compute_instance.md).

- API {#api}

  Use the [update](../../api-ref/Instance/update.md) REST API method for the [Instance](../../api-ref/Instance/index.md) resource or the [InstanceService/Update](../../api-ref/grpc/Instance/update.md) gRPC API call. Specify the service account ID in your request.

{% endlist %}

### Linking to a new VM {#link-with-new-instance}

{% list tabs group=instructions %}

- Management console {#console}

  In the management console, you can link a service account to a virtual machine. This service account must be in the same [folder](../../../resource-manager/concepts/resources-hierarchy.md#folder) as the VM. If the service account is in a different folder, use the CLI or API.

  To link a service account to a VM, select it under **Additional** in the **Service account** field when [creating the VM](../index.md#vm-create). You can select an existing service account or create a new one.

- CLI {#cli}

  If you do not have the Yandex Cloud CLI yet, [install and initialize it](../../../cli/quickstart.md#install).

  The folder used by default is the one specified when [creating](../../../cli/operations/profile/profile-create.md) the CLI profile. To change the default folder, use the `yc config set folder-id <folder_ID>` command. You can also specify a different folder for any command using `--folder-name` or `--folder-id`. If you access a resource by its name, the search will be limited to the default folder. If you access a resource by its ID, the search will be global, i.e., through all folders based on access permissions.

  Create a VM by specifying the service account using `--service-account-name` or `--service-account-id`:

  ```bash
  yc compute instance create \
    --name my-instance \
    --network-interface subnet-name=default,nat-ip-version=ipv4 \
    --ssh-key ~/.ssh/id_ed25519.pub \
    --service-account-name my-robot
  ```

- Terraform {#tf}

  1. Open the Terraform configuration file with the description of the VM you want to link the service account to. See [an example of the VM configuration file](../vm-create/create-linux-vm.md#tf_1).
  1. In the section with the `yandex_compute_instance` resource description, add the `service_account_id` parameter and specify the service account ID:

      ```hcl
      resource "yandex_compute_instance" "vm-1" {
        ...
        service_account_id = "<service_account_ID>"
        ...
      }
      ```

  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.

     Terraform will create all the required resources. You can check the new resources in the [management console](https://console.yandex.cloud).

  For more information about the `yandex_compute_instance` resource properties, see [this provider guide](../../../terraform/data-sources/compute_instance.md).

- API {#api}

  Use the [create](../../api-ref/Instance/create.md) REST API method for the [Instance](../../api-ref/Instance/index.md) resource or the [InstanceService/Create](../../api-ref/grpc/Instance/create.md) gRPC API call. Specify the service account ID in your request.

{% endlist %}

## Authentication from within a VM {#auth-inside-vm}

{% note warning %}

Simplified authentication to the Yandex Cloud API or CLI from within a VM is only possible using a service account [associated](#link-sa-with-instance) with the VM.

{% endnote %}

{% list tabs group=instructions %}

- CLI {#cli}

  1. [Connect](ssh.md) to the VM over SSH.

  1. If you do not have the Yandex Cloud CLI yet, [install and initialize it](../../../cli/quickstart.md#install).

  1. Create a new profile:

     ```bash
     yc config profile create my-robot-profile
     ```

  1. Configure your profile to run commands.

     Some commands require that you specify unique IDs for your cloud and folder. You can specify their details in the profile or use a specific flag for these commands.
     
     1. Specify the cloud in your profile:
     
         ```bash
         yc config set cloud-id <cloud_ID>
         ```
     
         You can also use the `--cloud-id` parameter to [run commands](../../../cli/concepts/index.md#manage-properties).
     1. Specify a folder in the profile:
     
         ```bash
         yc config set folder-id <folder_ID>
         ```
     
         You can also use the `--folder-id` parameter to [run commands](../../../cli/concepts/index.md#manage-properties).
     
     All operations in this profile will be performed on behalf of the linked service account. You can [change the profile parameters](../../../cli/operations/profile/manage-properties.md) or [switch to another profile](../../../cli/operations/profile/profile-activate.md).

     You can also get a [IAM token](../../../iam/concepts/authorization/iam-token.md), e.g., to get authenticated with the API:

     ```bash
     yc iam create-token
     ```

     The [lifetime of an IAM token](../../../iam/concepts/authorization/iam-token.md#lifetime) in this case will be less than 12 hours. Request an IAM token more often, e.g., every hour. To learn the remaining token lifetime, follow the steps for the API.

- API {#api}

  1. Connect to the VM [over SSH](ssh.md).
  1. Get an IAM token from metadata in Google Compute Engine format:

     ```bash
     curl \
       --header Metadata-Flavor:Google http://169.254.169.254/computeMetadata/v1/instance/service-accounts/default/token
     ```

     Result:

     ```text
     {"access_token":"CggVAgAAA...","expires_in":39944,"token_type":"Bearer"}
     ```

     The response will return an IAM token in the `access_token` field. The remaining lifetime of the IAM token is specified in the `expires_in` field.

  1. Specify the received IAM token when accessing Yandex Cloud resources via the API. Provide the IAM token in the `Authorization` header in the following format:
     
     ```yaml
     Authorization: Bearer <IAM_token>
     ```
     
     If you have saved your IAM token to a variable, use the latter:
     
     ```yaml
     Authorization: Bearer ${IAM_TOKEN}
     ```

    Keep track of the IAM token lifetime or request a new token more often, e.g., every hour.

{% endlist %}