[Yandex Cloud documentation](../../../index.md) > [Yandex Identity and Access Management](../../index.md) > [Step-by-step guides](../index.md) > Service accounts > Setting up service account access permissions

# Setting up service account access permissions

This section describes how to assign [roles](../../concepts/access-control/roles.md) for the [service account](../../concepts/users/service-accounts.md) as a resource. To assign the service account a role for another resource, follow the instructions in [Assigning roles to a service account](assign-role-for-sa.md).

{% note info %}

To assign a role for a service account, you need the `iam.serviceAccounts.admin` role.

{% endnote %}

## Assigning a role for a service account {#assign-role-to-sa}

{% list tabs group=instructions %}

- Management console {#console}

    1. In the [management console](https://console.yandex.cloud), click ![image](../../../_assets/console-icons/layout-side-content-left.svg) or ![image](../../../_assets/console-icons/chevron-down.svg) in the top panel and select the folder the service account belongs to.
    1. In the list of services, select **Identity and Access Management**.
    1. In the left-hand panel, select ![FaceRobot](../../../_assets/console-icons/face-robot.svg) **Service accounts** and then select the required service account.
    1. Navigate to the **Access bindings** tab.
    1. Click **Assign roles**.
    1. In the Who to grant access to field of the Granting access window, select a user from the list or search by user.
    1. Click **Add role**.
    1. Choose the role.
    1. Click **Save**.

- 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.

    1. View the description of the command to assign a role for a service account as a resource:

        ```bash
        yc iam service-account add-access-binding --help
        ```

    1. Select a service account, e.g., `my-robot`:

        ```bash
        yc iam service-account list
        ```

        Result:

        ```
        +----------------------+----------+------------------+
        |          ID          |   NAME   |   DESCRIPTION    |
        +----------------------+----------+------------------+
        | ajebqtreob2d******** | test-sa  | test-description |
        | aje6o61dvog2******** | my-robot |                  |
        +----------------------+----------+------------------+
        ```

    1. Choose the [role](../../concepts/access-control/roles.md).

        ```bash
        yc iam role list
        ```

        Result:

        ```
        +--------------------------------+-------------+
        |               ID               | DESCRIPTION |
        +--------------------------------+-------------+
        | admin                          |             |
        | compute.images.user            |             |
        | editor                         |             |
        | ...                            |             |
        +--------------------------------+-------------+
        ```

    1. Find out the user ID from the login or email address. To assign a role to a service account or a user group rather than to a single user, see the [examples](#examples) below.

        ```bash
        yc iam user-account get test-user
        ```

        Result:

        ```
        id: gfei8n54hmfh********
        yandex_passport_user_account:
            login: test-user
            default_email: test-user@yandex.ru
        ```

    1. Assign the `editor` role for the `my-robot` service account to `test-user`. In the subject, specify the `userAccount` type and user ID:

        ```bash
        yc iam service-account add-access-binding my-robot \
          --role editor \
          --subject userAccount:gfei8n54hmfh********
        ```

- Terraform {#tf}

    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. Add the resource parameters to the configuration file and specify the users' role to access the service account:

       * `service_account_id`: ID of the service account to configure access for.
       * `role`: Role being assigned. This is a required setting.
       * `members`: List of users or service accounts the role is being assigned to. Use one of these formats: `userAccount:<user_ID>` or `serviceAccount:<service_account_ID>`. This is a required setting.

       Here is an example of the configuration file structure:

       ```
       resource "yandex_iam_service_account_iam_binding" "admin-account-iam" {
         service_account_id = "<service_account_ID>"
         role               = "<role>"
         members            = [
           "federatedUser:<user_ID>",
         ]
       }
       ```

       For more information about the resources you can create with Terraform, see [this provider guide](../../../terraform/resources/iam_service_account_iam_binding.md).

    1. Make sure the configuration files are correct.

       1. In the terminal, navigate to the directory where you created your configuration file.
       1. Run a check using this command:

          ```
          terraform plan
          ```

       If the configuration is correct, the terminal will display a list of the resources and their settings. Otherwise, Terraform will show any detected errors.

    1. Deploy the cloud resources.

       1. If the configuration is correct, run this command:

          ```
          terraform apply
          ```

       1. Confirm creating the resources by typing `yes` and pressing **Enter**.

       This will create all the resources you need in the specified folder. You can check the new resource using the [management console](https://console.yandex.cloud) or this [CLI](../../../cli/quickstart.md) command:

       ```
       yc resource-manager service-account list-access-bindings <service_account_name_or_ID>
       ```

- API {#api}

    Use the [updateAccessBindings](../../api-ref/ServiceAccount/updateAccessBindings.md) REST API method for the [ServiceAccount](../../api-ref/ServiceAccount/index.md) resource or the [ServiceAccountService/UpdateAccessBindings](../../api-ref/grpc/ServiceAccount/updateAccessBindings.md) gRPC API call. You will need the ID of the service account and the ID of the user to whom you want to assign the role for the service account.

    1. Find out the service account ID using the [list](../../api-ref/ServiceAccount/list.md) REST API method:

        ```bash
        curl \
          --header "Authorization: Bearer <IAM_token>" \
          https://iam.api.cloud.yandex.net/iam/v1/serviceAccounts?folderId=b1gvmob95yys********
        ```

        Result:

        ```
        {
        "serviceAccounts": [
            {
            "id": "aje6o61dvog2********",
            "folderId": "b1gvmob95yys********",
            "createdAt": "2018-10-19T13:26:29Z",
            "name": "my-robot"
            }
            ...
        ]
        }
        ```

    1. Find out the user ID from the login using the [getByLogin](../../api-ref/YandexPassportUserAccount/getByLogin.md) REST API method:
        
        ```bash
        curl \
          --header "Authorization: Bearer <IAM_token>" \
          https://iam.api.cloud.yandex.net/iam/v1/yandexPassportUserAccounts:byLogin?login=test-user
        ```

        Result:

        ```
        {
        "id": "gfei8n54hmfh********",
        "yandexPassportUserAccount": {
            "login": "test-user",
            "defaultEmail": "test-user@yandex.ru"
        }
        }
        ```

    1. Assign the `editor` role for the `my-robot` sevice account. Set the `action` property to `ADD` and specify the `userAccount` type and user ID in the `subject` property:

       ```bash
       curl \
         --request POST \
         --header 'Content-Type: application/json' \
         --header "Authorization: Bearer <IAM_token>" \
         --data '{
         "accessBindingDeltas": [{
             "action": "ADD",
             "accessBinding": {
                 "roleId": "editor",
                 "subject": {
                     "id": "gfei8n54hmfh********",
                     "type": "userAccount"
         }}}]}' \
         https://iam.api.cloud.yandex.net/iam/v1/serviceAccounts/aje6o61dvog2********:updateAccessBindings
        ```

{% endlist %}

## Examples {#examples}

* [Assigning multiple roles](#multiple-roles)
* [Setting up access of one service account to another service account](#access-to-sa)

### Assigning multiple roles {#multiple-roles}

{% list tabs group=instructions %}

- CLI {#cli}

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

    The `add-access-binding` command allows you to add only one role. You can assign multiple roles using the `set-access-binding` command.

    {% note alert %}

    The `set-access-binding` command completely overwrites access permissions for the resource! All roles previously assigned for this resource will be deleted.

    {% endnote %}

    1. Make sure the resource has no important roles assigned before proceeding:
    
        ```bash
        yc iam service-account list-access-bindings my-robot
        ```

    1. For example, assign a role to multiple users:

        ```bash
        yc iam service-account set-access-bindings my-robot \
          --access-binding role=editor,subject=userAccount:gfei8n54hmfh******** \
          --access-binding role=viewer,subject=userAccount:helj89sfj80a********
        ```

- Terraform {#tf}

  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.

  To assign several roles to a service account created with Terraform:

  1. Add the resource parameters to the configuration file and specify the users' role to access the service account:

       * `service_account_id`: ID of the service account to configure access for.
       * `role`: Role being assigned. This is a required setting.

       {% note info %}

       For each role, you can only use one `yandex_iam_service_account_iam_binding` resource.

       {% endnote %}

       * `members`: List of users or service accounts the role is being assigned to. Use one of these formats: `userAccount:<user_ID>` or `serviceAccount:<service_account_ID>`. This is a required setting.

     {% cut "Example of assigning multiple roles to a service account using Terraform" %}

     ```hcl
     ...
     resource "yandex_iam_service_account_iam_binding" "admin-account-iam" {
       service_account_id = "aje82upckiqh********"
       role               = "admin"
       members = [
         "userAccount:aje82upckiqh********",
       ]
     }
     resource "yandex_iam_service_account_iam_binding" "admin-account-iam2" {
       service_account_id = "aje82upckiqh********"
       role               = "viewer"
       members = [
         "userAccount:aje82upckiqh********",
       ]
     }
     ...
     ```

     {% endcut %}

     For more information about the resources you can create with Terraform, see [this provider guide](../../../terraform/resources/iam_service_account_iam_binding.md).
 
  1. Validate your configuration using this command:
     ```
     terraform validate
     ``` 

     If the configuration is valid, you will get this message:

     ```
     Success! The configuration is valid.
     ```

  1. Run this command:
     ```
     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:
     ```
     terraform apply
     ```

  1. Confirm the changes: type `yes` into the terminal and press **Enter**.

     You can check the folder update using the [management console](https://console.yandex.cloud) or this [CLI](../../../cli/quickstart.md) command:

     ```
     yc resource-manager service-account list-access-bindings <service_account_name_or_ID>
     ```

- API {#api}

    Assign the `editor` role to one user and the `viewer` role to another user:

    ```bash
    curl \
      --request POST \
      --header 'Content-Type: application/json' \
      --header "Authorization: Bearer <IAM_token>" \
      --data '{
      "accessBindingDeltas": [{
          "action": "ADD",
          "accessBinding": {
              "roleId": "editor",
              "subject": {
                  "id": "gfei8n54hmfh********",
                  "type": "userAccount"
              }
          }
      },{
          "action": "ADD",
          "accessBinding": {
              "roleId": "viewer",
              "subject": {
                  "id": "helj89sfj80a********",
                  "type": "userAccount"
      }}}]}' \
      https://iam.api.cloud.yandex.net/iam/v1/serviceAccounts/aje6o61dvog2********:updateAccessBindings
    ```

    You can also assign roles using the [setAccessBindings](../../api-ref/ServiceAccount/setAccessBindings.md) REST API method for the [ServiceAccount](../../api-ref/ServiceAccount/index.md) resource or the [ServiceAccountService/SetAccessBindings](../../api-ref/grpc/ServiceAccount/setAccessBindings.md) gRPC API call.

    {% note alert %}

    The `setAccessBindings` method completely overwrites access permissions for the resource! All roles previously assigned for this resource will be deleted.

    {% endnote %}

    ```bash
    curl \
      --request POST \
      --header 'Content-Type: application/json' \
      --header "Authorization: Bearer <IAM_token>" \
      --data '{
      "accessBindings": [{
          "roleId": "editor",
          "subject": { "id": "ajei8n54hmfh********", "type": "userAccount" }
      },{
          "roleId": "viewer",
          "subject": { "id": "helj89sfj80a********", "type": "userAccount" }
      }]}' \
      https://iam.api.cloud.yandex.net/iam/v1/serviceAccounts/aje6o61dvog2********:setAccessBindings
    ```

{% endlist %}

### Setting up access from one service account to another service account {#access-to-sa}

Allow the `test-sa` service account to manage the `my-robot` service account:

{% list tabs group=instructions %}

- CLI {#cli}

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

  1. Find out the ID of the `test-sa` service account you want to assign the role to. To do this, get a list of available service accounts:

      ```bash
      yc iam service-account list
      ```

      Result:

      ```
      +----------------------+----------+------------------+
      |          ID          |   NAME   |   DESCRIPTION    |
      +----------------------+----------+------------------+
      | ajebqtreob2d******** | test-sa  | test-description |
      | aje6o61dvog2******** | my-robot |                  |
      +----------------------+----------+------------------+
      ```

  1. Assign the `editor` role to the `test-sa` service account by specifying its ID. In the subject type, specify `serviceAccount`:

      ```bash
      yc iam service-account add-access-binding my-robot \
        --role editor \
        --subject serviceAccount:ajebqtreob2d********
      ```

- Terraform {#tf}

  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.

  To allow the `test-sa` service account to manage the `my-robot` service account created with Terraform:

    1. Add the resource parameters to the configuration file and specify the users' role to access the service account:

       * `service_account_id`: ID of the service account to configure access for.
       * `role`: Role being assigned. This is a required setting.
       * `members`: List of users or service accounts the role is being assigned to. Use one of these formats: `userAccount:<user_ID>` or `serviceAccount:<service_account_ID>`. This is a required setting.

     {% cut "Example of granting the `test-sa` service account permissions to manage the `my-robot` service account using Terraform" %}

     ```hcl
     ...
     resource "yandex_iam_service_account_iam_binding" "admin-account-iam" {
       service_account_id = "aje82upckiqh********"
       role               = "admin"
       members = [
         "serviceAccount:aje82upckiqh********",
       ]
     }
     ...
     ```

     {% endcut %}

     For more information about the resources you can create with Terraform, see [this provider guide](../../../terraform/resources/iam_service_account_iam_binding.md).

  1. Validate your configuration using this command:
     ```
     terraform validate
     ```

     If the configuration is valid, you will get this message:

     ```
     Success! The configuration is valid.
     ```

  1. Run this command:
     ```
     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:
     ```
     terraform apply
     ```

  1. Confirm the changes: type `yes` into the terminal and press **Enter**.

     You can check the folder update using the [management console](https://console.yandex.cloud) or this [CLI](../../../cli/quickstart.md) command:

     ```
     yc resource-manager service-account list-access-bindings <service_account_name_or_ID>
     ```

- API {#api}

  1. Find out the ID of the `test-sa` service account you want to assign the role to. To do this, get a list of available service accounts:

      ```bash
      curl \
        --header "Authorization: Bearer <IAM_token>" \
        https://iam.api.cloud.yandex.net/iam/v1/serviceAccounts?folderId=b1gvmob95yys********
      ```

      Result:

      ```
      {
       "serviceAccounts": [
        {
         "id": "ajebqtreob2d********",
         "folderId": "b1gvmob95yys********",
         "createdAt": "2018-10-18T13:42:40Z",
         "name": "test-sa",
         "description": "test-description"
        },
        {
         "id": "aje6o61dvog2********",
         "folderId": "b1gvmob95yys********",
         "createdAt": "2018-10-15T18:01:25Z",
         "name": "my-robot"
        }
       ]
      }
      ```

  1. Assign the `editor` role to the `test-sa` service account for another service account named `my-robot`. In the `subject` property, specify the `serviceAccount` type and `test-sa` ID. In the request URL, specify the `my-robot` ID as a resource:

      ```bash
      curl \
        --request POST \
        --header 'Content-Type: application/json' \
        --header "Authorization: Bearer <IAM_token>" \
        --data '{
        "accessBindingDeltas": [{
            "action": "ADD",
            "accessBinding": {
                "roleId": "editor",
                "subject": {
                    "id": "ajebqtreob2d********",
                    "type": "serviceAccount"
        }}}]}' \
        https://iam.api.cloud.yandex.net/iam/v1/serviceAccounts/aje6o61dvog2********:updateAccessBindings
      ```

{% endlist %}

#### Useful links {#see-also}

* [Using impersonation](impersonate-sa.md)