[Yandex Cloud documentation](../../../index.md) > [Yandex Identity and Access Management](../../index.md) > [Step-by-step guides](../index.md) > [Service accounts](index.md) > Assigning roles to a service account

# Assigning a role to a service account

This section describes how to assign a [role](../../concepts/access-control/roles.md) for a resource to a service account. To learn how to assign a role for a [service account](../../concepts/users/service-accounts.md) as a resource to another user, see [Setting up service account access permissions](set-access-bindings.md).

You can assign roles to a service account for any resources in any cloud if these resources belong to the same organization as the service account. You can also assign roles for the entire organization.

## Assigning a role for a resource {#binding-role-resource}

Child resources inherit access permissions from their parent resources. For example, if a service account gets a role for a cloud, it will also get the required permissions for all resources across the cloud's folders.

To assign a role for a resource, you need the `admin` or `service-name.admin` role, where `service-name` is the name of the service to which the resource belongs.

[Learn](../../concepts/access-control/resources-with-access-control.md) which resources you can assign a role for.

To assign a role for a resource:

{% list tabs group=instructions %}

- Management console {#console}

    Roles are assigned to a service account the same way as to a user account.
    
    To assign a role for a cloud or folder to a service account:

    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 cloud or folder.
    1. Navigate to the **Access bindings** tab.
    1. Click **Configure access**.
    1. In the window that opens, select **Service accounts**.
    1. Select the service account from the list or use the search bar.
    1. Click ![image](../../../_assets/console-icons/plus.svg) **Add role** and select the role from the list or use the search bar.
    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.

  To assign a role for a cloud or folder to a service account, run this command:

  ```bash
  yc resource-manager <resource_category> add-access-binding <resource_name_or_ID> \
    --role <role_ID> \
    --service-account-id <service_account_ID>
  ```

  Where:

  * `<resource_category>`: `cloud` to assign a role for a cloud or `folder` to assign a role for a folder.
  * `<resource_name_or_ID>`: Name or ID of the resource to assign the role for.
  * `--role`: Role ID, e.g., `viewer`.
  * `--service-account-id`: ID of the service account you are assigning the role to.

  For example, to assign a role for a [folder](../../../resource-manager/concepts/resources-hierarchy.md#folder) to a service account:

  1. Select a role to assign to the service account. For role descriptions, see the [Yandex Cloud role reference](../../roles-reference.md) in the Yandex Identity and Access Management documentation.
  1. Get the ID of the service account by its name:
  
      ```bash
      yc iam service-account get <service_account_name>
      ```
  
      Result:
  
      ```text
      id: aje6o61dvog2********
      folder_id: b1gvmob95yys********
      created_at: "2018-10-15T18:01:25Z"
      name: my-robot
      ```
  
      If you do not know the name of your service account, get a list of service accounts with their IDs:
  
      ```bash
      yc iam service-account list
      ```
  
      Result:
      
      ```bash
      +----------------------+------------------+-----------------+
      |          ID          |       NAME       |   DESCRIPTION   |
      +----------------------+------------------+-----------------+
      | aje6o61dvog2******** | my-robot         | my description  |
      +----------------------+------------------+-----------------+
      ```
  
  1. Assign the role to the service account using its ID:
  
      ```bash
      yc resource-manager folder add-access-binding <folder_name_or_ID> \
        --role <role> \
        --service-account-id <service_account_ID>
      ```
  
  
      Where:
  
      * `--role`: ID of the role to assign.
      * `--service-account-id`: Service account ID. You can also use the `--service-account-name` parameter and specify the username instead of the ID.

- 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. In the configuration file, describe the resources you want to create:

      Here is an example of the configuration file structure for assigning a role for a folder:

      ```hcl
      resource "yandex_resourcemanager_folder_iam_member" "admin-account-iam" {
        folder_id   = "<folder_ID>"
        role        = "<role>"
        member      = "serviceAccount:<service_account_ID>"
      }
      ```

      Where:
      * `folder_id`: [Folder ID](../../../resource-manager/operations/folder/get-id.md). This is a required setting.
      * `role`: Role. For role descriptions, see the [Yandex Cloud role reference](../../roles-reference.md) in the Yandex Identity and Access Management documentation. This is a required setting.
      * `member`: [Subject](../../concepts/access-control/index.md#subject) getting the role. For a service account, specify `serviceAccount:<service_account_ID>`.

          {% cut "Subject designations" %}

          To indicate a subject, use a combination of its type and unique ID, i.e., `<subject_type>:<ID>`. Here is how you can designate a subject:
          
          #|
          || **Subject type** | **Subject designation** ||
          || `userAccount`    | `userAccount:<user_ID>` ||
          || `serviceAccount` | `serviceAccount:<service_account_ID>` ||
          || `federatedUser`  | `federatedUser:<user_ID>` ||
          || `group`          | `group:<group_ID>` ||
          || `system`         | `system:allAuthenticatedUsers`
          
          (`All authenticated users` group) ||
          || ^                | `system:allUsers`
          
          (`All users` group) ||
          || ^                | `system:group:organization:<organization_ID>:users`
          
          (`All users in organization X` group) ||
          || ^                | `system:group:federation:<federation_ID>:users`
          
          (`All users in federation N` group) ||
          || ^                | `system:group:userpool:<pool_ID>:users`
          
          (`All users in userpool P` group) ||
          |#

          {% endcut %}

      For more information about the resources you can create with Terraform, see [this provider guide](../../../terraform/index.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.

      This will assign access permissions for the folder. You can check the role assignment using the [management console](https://console.yandex.cloud) or this [CLI](../../../cli/quickstart.md) command:

      ```bash
      yc resource-manager folder list-access-bindings <folder_name_or_ID>
      ```

- API {#api}

  To assign a role for a cloud or folder to a service account, use the `updateAccessBindings` REST API method for the [Cloud](../../../resource-manager/api-ref/Cloud/index.md) or [Folder](../../../resource-manager/api-ref/Folder/index.md) resource:
  
  1. Select a role to assign to the service account. For role descriptions, see the [Yandex Cloud role reference](../../roles-reference.md) in the Yandex Identity and Access Management documentation.
  1. [Get](../../../resource-manager/operations/folder/get-id.md) the ID of the folder with service accounts.
  1. [Get](../iam-token/create.md) an IAM token for authentication in the Yandex Cloud API.
  1. Get a list of service accounts in the folder to find out their IDs:
  
      ```bash
      export FOLDER_ID=<folder_ID>
      export IAM_TOKEN=<IAM_token>
      curl \
        --header "Authorization: Bearer ${IAM_TOKEN}" \
        "https://iam.api.cloud.yandex.net/iam/v1/serviceAccounts?folderId=${FOLDER_ID}"
      ```
  
      Result:
  
  
      ```json
      {
       "serviceAccounts": [
        {
         "id": "ajebqtreob2d********",
         "folderId": "b1gvmob95yys********",
         "createdAt": "2018-10-18T13:42:40Z",
         "name": "my-robot",
         "description": "my description"
        }
       ]
      }
      ```
  
  1. Create a request body, e.g., in the `body.json` file. Specify `ADD` in the `action` property:
  
      ```json
      {
        "accessBindingDeltas": [{
          "action": "ADD",
          "accessBinding": {
            "roleId": "<role>",
            "subject": {
              "id": "<service_account_ID>",
              "type": "serviceAccount"
            }
          }
        }]
      }
      ```
  
      Where:
  
      * `roleId`: Role.
      * `subject`: [Subject](../../concepts/access-control/index.md#subject) getting the role.
  
          {% cut "Subject designations" %}
  
          To indicate a subject, use a combination of its type and unique ID in the `subject.type` and `subject.id` fields of the request. Here are possible combinations:
          
          #|
          || **subject.type** | **subject.id** ||
          || `userAccount`    | `<user_ID>` ||
          || `serviceAccount` | `<service_account_ID>` ||
          || `federatedUser`  | `<user_ID>` ||
          || `group`          | `<group_ID>` ||
          || `system`         | `allAuthenticatedUsers`
          
          (`All authenticated users` group) ||
          || ^                | `allUsers`
          
          (`All users` group) ||
          || ^                | `group:organization:<organization_ID>:users`
          
          (`All users in organization X` group) ||
          || ^                | `group:federation:<federation_ID>:users`
          
          (`All users in federation N` group) ||
          || ^                | `group:userpool:<pool_ID>:users`
          
          (`All users in userpool P` group) ||
          |#
  
          {% endcut %}
  
  1. Assign a role to a service account, e.g., for the folder with the `b1gvmob95yys********` ID:
     
     ```bash
     export FOLDER_ID=b1gvmob95yys********
     export IAM_TOKEN=CggaAT********
     curl \
       --request POST \
       --header "Content-Type: application/json" \
       --header "Authorization: Bearer ${IAM_TOKEN}" \
       --data '@body.json' \
       "https://resource-manager.api.cloud.yandex.net/resource-manager/v1/folders/${FOLDER_ID}:updateAccessBindings"
     ```

{% endlist %}

## Assigning a role for an organization {#binding-role-organization}

All resources created within an organization inherit access permissions assigned to that organization. For example, if a service account gets a role for an organization, it will also get the required permissions for all resources across the organization's clouds.

To grant organization access permissions to a service account, you need the `organization-manager.admin` role or higher.

{% list tabs group=instructions %}

- Cloud Center UI {#cloud-center}

  1. Log in to [Yandex Identity Hub](https://center.yandex.cloud/organization) using an administrator or organization owner account.

  1. In the left-hand panel, select ![persons-lock](../../../_assets/console-icons/persons-lock.svg) **Access bindings**.

  1. In the **Account type** filter, select `Service accounts`.

  1. If the service account you need already has at least one role assigned, click ![icon-context-menu](../../../_assets/console-icons/ellipsis.svg) in the row with that service account and select **Assign roles**.

      If the service account is not on the list, click **Assign roles** in the top-right corner. In the window that opens, go to **Service accounts** and select the account from the list or use the search bar to locate it.

  1. Click ![plus](../../../_assets/console-icons/plus.svg) **Add role** and select a [role](../../concepts/access-control/roles.md) to assign to the service account. You can assign multiple roles.

      For descriptions of available roles, see the [Yandex Cloud role reference](../../roles-reference.md) in the Yandex Identity and Access Management documentation.

  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.

  To assign a role for an organization to a service account, run this command:

  ```bash
  yc organization-manager organization add-access-binding <organization_name_or_ID> \
    --role <role_ID> \
    --service-account-id <service_account_ID>
  ```

  Where:

  * `<organization_name_or_ID>`: Technical name or [ID](../../../organization/operations/organization-get-id.md) of the organization.
  * `--role`: Role ID, e.g., `viewer`.
  * `--service-account-id`: ID of the service account you are assigning the role to.

  For example, to assign the `viewer` role for the `MyOrg` organization to a service account:

  1. Select a role to assign to the service account. For role descriptions, see the [Yandex Cloud role reference](../../roles-reference.md) in the Yandex Identity and Access Management documentation.
  1. Get a list of available organizations to find out their IDs and technical names:

      ```bash
      yc organization-manager organization list
      ```

      Result:

      ```text
      +---------------------------------+---------------------------------+----------------------+
      |               ID                |              NAME               |        TITLE         |
      +---------------------------------+---------------------------------+----------------------+
      | bpf1smsil5q0********            | hdt5j5uw********                | MyOrg                |
      +---------------------------------+---------------------------------+----------------------+
      ```

      The organization's technical name is in the `NAME` column, and its ID, in the `ID` column.

  1. Get the ID of the service account by its name:

      ```bash
      yc iam service-account get my-robot
      ```

      Result:

      ```text
      id: aje6o61dvog2********
      folder_id: b1gvmob95yys********
      created_at: "2018-10-15T18:01:25Z"
      name: my-robot
      ```

      If you do not know the name of your service account, get a full list of service accounts with their IDs:

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

      Result:

      ```bash
      +----------------------+------------------+-----------------+
      |          ID          |       NAME       |   DESCRIPTION   |
      +----------------------+------------------+-----------------+
      | aje6o61dvog2******** | my-robot         | my description  |
      +----------------------+------------------+-----------------+
      ```

  1. Assign the `my-robot` service account the `viewer` role for the organization with the `bpf1smsil5q0********` ID:

      ```bash
      yc organization-manager organization add-access-binding bpf1smsil5q0******** \
        --role viewer \
        --service-account-id aje6o61dvog2********
      ```

- 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. In the configuration file, describe the resources you want to create:

     Here is an example of the configuration file structure:

     ```
     resource "yandex_organizationmanager_organization_iam_binding" "editor" {
       organization_id   = "<organization_ID>"
       role              = "<role>"
       members           = ["serviceAccount:<service_account_ID>",]
     }
     ```

     Where:
     * `organization_id`: [Organization ID](../../../organization/operations/organization-get-id.md). This is a required setting.
     * `role`: Role. For role descriptions, see the [Yandex Cloud role reference](../../roles-reference.md) in the Yandex Identity and Access Management documentation. For each role, you can only use one `yandex_organizationmanager_organization_iam_binding` resource. This is a required setting.
     * `members`: List of [subjects](../../concepts/access-control/index.md#subject) getting the role. This is a required setting.

     For more on the properties of the `yandex_organizationmanager_organization_iam_binding` resource, see [this provider guide](../../../terraform/resources/organizationmanager_organization_iam_binding.md).

  1. Make sure the settings are correct.

      1. In the command line, navigate to the directory that contains the current Terraform configuration files defining the infrastructure.
      1. Run this command:
      
         ```bash
         terraform validate
         ```
      
         Terraform will show any errors found in your configuration files.

  1. Assign the role.

      1. Run this command to view the intended changes:
      
         ```bash
         terraform plan
         ```
      
         If you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
      
      1. If everything looks correct, apply the changes:
      
         1. Run this command:
      
            ```bash
            terraform apply
            ```
      
         1. Confirm updating the resources.
         1. Wait for the operation to complete.

     This will assign access permissions for the organization. You can check the role assignment using the [management console](https://console.yandex.cloud) or this [CLI](../../../cli/quickstart.md) command:

     ```bash
     yc organization-manager organization list-access-bindings <organization_name_or_ID>
     ```

- API {#api}

  To assign a role for an organization to a service account, use the [updateAccessBindings](../../../organization/api-ref/Organization/updateAccessBindings.md) REST API method for the [Organization](../../../organization/api-ref/Organization/index.md) resource or the [OrganizationService/UpdateAccessBindings](../../../organization/api-ref/grpc/Organization/updateAccessBindings.md) gRPC API call:

  1. Select a role to assign to the service account. For role descriptions, see the [Yandex Cloud role reference](../../roles-reference.md) in the Yandex Identity and Access Management documentation.
  1. [Get](../../../resource-manager/operations/folder/get-id.md) the ID of the folder with service accounts.
  1. [Get](../iam-token/create.md) an IAM token for authentication in the Yandex Cloud API.
  1. Get a list of service accounts in the folder to find out their IDs:

      ```bash
      export FOLDER_ID=<folder_ID>
      export IAM_TOKEN=<IAM_token>
      curl \
        --header "Authorization: Bearer ${IAM_TOKEN}" \
        "https://iam.api.cloud.yandex.net/iam/v1/serviceAccounts?folderId=${FOLDER_ID}"
      ```

      Result:


      ```json
      {
       "serviceAccounts": [
        {
         "id": "ajebqtreob2d********",
         "folderId": "b1gvmob95yys********",
         "createdAt": "2018-10-18T13:42:40Z",
         "name": "my-robot",
         "description": "my description"
        }
       ]
      }
      ```

  1. Get a list of organizations to find out their IDs:

      ```bash
      export IAM_TOKEN=<IAM_token>
      curl \
        --header "Authorization: Bearer ${IAM_TOKEN}" \
        --request GET \
        "https://organization-manager.api.cloud.yandex.net/organization-manager/v1/organizations"
      ```

      Result:

      ```text
      {
       "organizations": [
        {
         "id": "bpfaidqca8vd********",
         "createdAt": "2023-04-07T08:11:54.313033Z",
         "name": "xvdq9q22********",
         "title": "MyOrg"
        }
       ]
      }
      ```

  1. Create a request body, e.g., in the `body.json` file. Specify `ADD` in the `action` property:

      **body.json:**

      ```json
      {
        "accessBindingDeltas": [{
          "action": "ADD",
          "accessBinding": {
            "roleId": "<role>",
            "subject": {
              "id": "<service_account_ID>",
              "type": "serviceAccount"
            }
          }
        }]
      }
      ```

      Where:

      * `roleId`: Role.
      * `subject`: [Subject](../../concepts/access-control/index.md#subject) getting the role.

          {% cut "Subject designations" %}

          To indicate a subject, use a combination of its type and unique ID in the `subject.type` and `subject.id` fields of the request. Here are possible combinations:
          
          #|
          || **subject.type** | **subject.id** ||
          || `userAccount`    | `<user_ID>` ||
          || `serviceAccount` | `<service_account_ID>` ||
          || `federatedUser`  | `<user_ID>` ||
          || `group`          | `<group_ID>` ||
          || `system`         | `allAuthenticatedUsers`
          
          (`All authenticated users` group) ||
          || ^                | `allUsers`
          
          (`All users` group) ||
          || ^                | `group:organization:<organization_ID>:users`
          
          (`All users in organization X` group) ||
          || ^                | `group:federation:<federation_ID>:users`
          
          (`All users in federation N` group) ||
          || ^                | `group:userpool:<pool_ID>:users`
          
          (`All users in userpool P` group) ||
          |#

          {% endcut %}


  1. Assign the role to the service account:

      ```bash
      export ORGANIZATION_ID=<organization_ID>
      export IAM_TOKEN=<IAM_token>
      curl \
        --header "Content-Type: application/json" \
        --header "Authorization: Bearer ${IAM_TOKEN}" \
        --data '@body.json' \
        --request POST \
        "https://organization-manager.api.cloud.yandex.net/organization-manager/v1/organizations/${ORGANIZATION_ID}:updateAccessBindings"
      ```

{% endlist %}

#### What's next {#what-is-next}

* [Creating a static access key](../authentication/manage-access-keys.md#create-access-key).
* [Setting up service account access permissions](set-access-bindings.md).
* [Assigning multiple roles at once](../roles/grant.md#multiple-roles).