[Yandex Cloud documentation](../../index.md) > [Tutorials](../index.md) > [Security](index.md) > Service account with an OS Login profile for VM management via Ansible

# Using a service account with an OS Login profile for VM management via Ansible

To manage [virtual machines](../../compute/concepts/vm.md) via [Ansible](https://www.ansible.com/), you can use a [service account](../../iam/concepts/users/service-accounts.md) provided with an [OS Login profile](../../organization/concepts/os-login.md#os-login-profiles) with an SSH key. This configuration will allow you to have a separate account for VM management via Ansible with scheduled or manual SSH key revocation.

In addition, with this configuration you can temporarily elevate the privileges of this account by assigning additional [roles](../../iam/concepts/access-control/roles.md) to the service account. For example, to use the `become` directive in Ansible tasks, you will have to temporarily assign the `compute.osAdminLogin` [role](../../compute/security/index.md#compute-osadminlogin) to the service account.

To configure a service account for VM management via Ansible:
1. [Get your cloud ready](#before-you-begin).
1. [Create a service account with an SSH key in the OS Login profile](#create-ssh-key).
1. [Configure Ansible to run on behalf of a service account](#configure-ansible).

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

### Set up your environment {#prepare}

1. 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. [Create](../../compute/operations/vm-create/create-linux-vm.md) a virtual machine from a public image with enabled OS Login access, e.g., [Ubuntu 22.04 LTS OS Login](https://yandex.cloud/en/marketplace/products/yc/ubuntu-2204-lts-oslogin).
1. In your organization settings, [enable](../../organization/operations/os-login-access.md) OS Login access using SSH keys.
1. [Install](https://docs.ansible.com/ansible/latest/installation_guide/installation_distros.html) Ansible.

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

The cost of supporting the infrastructure created in the guide includes:
* Fee for a continuously running VM (see [Yandex Compute Cloud pricing](../../compute/pricing.md)).
* Fee for using a public IP address (see [Yandex Virtual Private Cloud pricing](../../vpc/pricing.md)).

## Create a service account with an SSH key in the OS Login profile {#create-ssh-key}

1. [Create](../../iam/operations/sa/create.md) a service account named `my-ansible-sa` and [assign](../../iam/operations/sa/assign-role-for-sa.md) the `compute.osLogin` [role](../../compute/security/index.md#compute-oslogin) to it. You also need the `resource-manager.auditor` role or higher for the folder housing the VM.
1. [Create](../../organization/operations/os-login-profile-create.md) an [OS Login profile](../../organization/concepts/os-login.md#os-login-profiles) with the `my-ansible-sa-profile` login for `my-ansible-sa`.
1. Create an SSH key pair of the `ed25519` type the service account will use to connect to virtual machines:

    ```bash
    ssh-keygen \
      -t ed25519 \
      -f <path>/my-ansible-sa-profile
    ```
    
    Where `-f` is the name of the SSH key being created and the path to the directory where the files with the private and public parts of the key will be saved, e.g., `-f /home/user/ansible-key/my-ansible-sa-profile`.

    As a result, two SSH key files will be created in the specified directory: `my-ansible-sa-profile` and `my-ansible-sa-profile.pub`.

1. Add the new SSH key to the OS Login profile of the `my-ansible-sa` service account:

    {% list tabs group=instructions %}

    - CLI {#cli}

      ```bash
      yc organization-manager oslogin user-ssh-key create \
        --name <key_name> \
        --organization-id <organization_ID> \
        --subject-id <service_account_ID> \
        --data "<public_SSH_key>" \
        --expires-at <key_expiration_date>

      ```
      Where:
      * `--name`: Uploaded key name, e.g., `ssh-my-ansible-sa`.
      * `--organization-id`: ID of the [organization](../../organization/operations/organization-get-id.md) the `my-ansible-sa` service account belongs to.
      * `--subject-id`: [ID](../../iam/operations/sa/get-id.md) of the service account to whose profile you are adding the SSH key.
      * `--data`: Contents of the file with the public part of the SSH key (`my-ansible-sa-profile.pub`).
      * `--expires-at`: Uploaded key expiration date. This is an optional setting. If the parameter is not set, the key will have no expiration date.

          You can specify the value in two formats:
          * Key expiration date in [ISO 8601](https://ru.wikipedia.org/wiki/ISO_8601) format, e.g., `YYYY-MM-DDT00:00:00Z`.
          * Key validity period in hours and minutes, e.g., `1h` or `3h30m`.

      Result:

      ```text
      id: bpfejaidgt9u********
      subject_id: ajeqdl8mdv12********
      data: ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOra4Rg9OpwS5cozMHDGpdp6ug/jYUnWtTFD********
      name: ssh-my-ansible-sa
      fingerprint: SHA256:gkEtFdaTmT7PK4/fCrZqnSjFDBsvLeNfkAR********
      organization_id: bpfaidqca8vd********
      created_at: "2024-06-21T10:10:11.946355750Z"
      expires_at: "2024-06-21T20:10:11.380653492Z"
      ```

      For more information about the `yc organization-manager oslogin user-ssh-key create` command, see the [CLI reference](../../cli/cli-ref/organization-manager/cli-ref/oslogin/user-ssh-key/create.md).

    {% endlist %}

    {% note tip %}
    
    For security purposes, it is recommended to rotate SSH keys from time to time. It is not safe to use an SSH key with unlimited validity period.

    {% endnote %}

1. Check if you can log in to the VM using the service account's OS Login profile:

    ```bash
    ssh my-ansible-sa-profile@<VM_IP_address> -i <path_to_private_SSH_key>
    ```
 
    Where:
    * `<VM_IP_address>`: [Public IP address](../../vpc/concepts/address.md#public-addresses) of the VM with enabled OS Login access.
    * `<path_to_private_SSH_key>`: Path to the file containing the private part of the previously created SSH key, e.g., `/home/user/ansible-key/my-ansible-sa-profile`.

## Configure Ansible to run on behalf of a service account {#configure-ansible}

Make sure Ansible can connect to the virtual machine on behalf of the new service account. To do this, create an inventory file and test it using the `ansible.builtin.ping` module: 

1. Create the `inventory.ini` file with the `yc` group:

    ```ini
    [yc:vars]
    ansible_connection=ssh
    ansible_user=my-ansible-sa-profile
    ansible_ssh_private_key_file=<path_to_private_SSH_key>

    [yc]
    <VM_IP_address>
    ```
    Where:
    * `<path_to_private_SSH_key>`: Path to the file containing the private part of the previously created SSH key, e.g., `/home/user/ansible-key/my-ansible-sa-profile`.
    * `<VM_IP_address>`: Public IP address of the VM with enabled OS Login access.

1. Run Ansible with the `ansible.builtin.ping` module:

    ```bash
    ansible -i inventory.ini -m ping yc
    ```

    Result:
    ```text
    158.160.**.*** | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python3"
    },
    "changed": false,
    "ping": "pong"
    }
    ```

Connection to the VM is established. You can now manage virtual machines via Ansible under a service account with an OS Login profile and a limited-validity SSH key.

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

To stop paying for the resources you created:
1. [Delete](../../compute/operations/vm-control/vm-delete.md) the VM.
1. [Delete](../../iam/operations/sa/delete.md) the service account if you need to.