> ## Documentation Index
> Fetch the complete documentation index at: https://www.1password.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Tutorial: Rotate a secret in a 1Password Environment on a schedule

In this tutorial, you'll learn how to rotate a secret stored in a [1Password Environment](https://www.1password.dev/environments.md) on a schedule using 1Password SDKs.

We'll walk through the process using an example script that generates a new API key, updates it at your provider, then stores the new value in your Environment. Any application that reads the Environment picks up the new value the next time it starts. By the end, you'll understand how to:

* Create a service account with write access to an Environment.
* Generate a new secret value with the 1Password SDK.
* Edit a secret in an Environment without exposing its value.
* Run the rotation script on a schedule.

## Prerequisites

1. [1Password subscription](https://1password.com/pricing/password-manager).
2. [1Password desktop app](https://1password.com/downloads/).
3. An [Environment](https://www.1password.dev/environments.md#create-an-environment) that contains the secret you want to rotate.
4. Basic knowledge of Python.
5. Familiarity with 1Password SDKs. To learn how to get started, see the [end-to-end setup tutorial](https://www.1password.dev/sdks/setup-tutorial.md).

## Part 1: Set up the Environment and service account

In the first part of this tutorial, you'll make sure the secret you want to rotate is stored in an Environment, then create a service account that can edit it.

### Step 1: Add the secret to an Environment

If you haven't already, [create an Environment](https://www.1password.dev/environments.md#create-an-environment) and [add the secret](https://www.1password.dev/environments.md#add-secrets-to-an-environment) you want to rotate. For our example, we'll use an Environment named `Production` that contains a secret named `API_KEY`.

### Step 2: Create a service account with write access to the Environment

[Service accounts](https://www.1password.dev/service-accounts.md) are a token-based authentication method that you can scope to specific Environments. For this tutorial, create a service account that has write access to the `Production` Environment, so it can edit the secret.

> [!TIP]
>
> If you don't see the option to create service accounts, ask your administrator to [give you access to create and manage service accounts](https://www.1password.dev/service-accounts/manage-service-accounts.md#manage-who-can-create-service-accounts).

1. Use the [service account creation wizard](https://start.1password.com/developer-tools/infrastructure-secrets/serviceaccount/?source=dev-portal) on 1Password.com.
2. Give your service account a name. For example, `Secret Rotation Service Account`.
3. Choose the `Production` Environment and give the service account write access. This can't be changed later.
4. Select **Create Account**, then select **Save in 1Password** to save the service account token in your 1Password account.

## Part 2: Write the rotation script

In the second part of this tutorial, you'll write a Python script that generates a new value for the secret, updates it at your provider, and stores it in the Environment.

### Step 1: Export your service account token

Export the service account token you saved [in part one](#step-2-create-a-service-account-with-write-access-to-the-environment) to the `OP_SERVICE_ACCOUNT_TOKEN` environment variable.

> [tab] Bash, Zsh, sh
>
> ```shell theme={null}
> export OP_SERVICE_ACCOUNT_TOKEN=<your-token>
> ```

> [tab] fish
>
> ```shell theme={null}
> set -x OP_SERVICE_ACCOUNT_TOKEN <your-token>
> ```

> [tab] PowerShell
>
> ```powershell theme={null}
> $Env:OP_SERVICE_ACCOUNT_TOKEN = <your-token>
> ```

### Step 2: Generate a new value

Use the [`Secrets.generate_password()`](https://www.1password.dev/sdks/manage-items#generate-a-password) method to generate the new value. In our example, we generate a 32-character random string with letters and digits.

```python theme={null}
from onepassword import PasswordRecipeRandom, PasswordRecipeRandomInner, Secrets

new_value = Secrets.generate_password(
    PasswordRecipeRandom(
        parameters=PasswordRecipeRandomInner(
            length=32,
            includeDigits=True,
            includeSymbols=False,
        )
    ),
)
```

### Step 3: Update the credential at your provider

Set the new value at the service that accepts the credential, such as your API provider or database. This step depends on your provider's API, so the example uses a placeholder function. Replace its body with the API call your provider documents.

```python theme={null}
def update_provider(new_value: str) -> None:
    # TODO: Replace with the API call that sets the new credential at your provider.
    ...
```

Update the provider before you update the Environment. If the provider call fails, the Environment still holds the value that works.

### Step 4: Store the new value in the Environment

Use the [`environments.edit_secret()`](https://www.1password.dev/sdks/environments#edit-a-secret) method to store the new value. Pass only the `value` so the secret keeps its name and default visibility. The script prints the secret's name, not its value.

Here's the complete script:

```python theme={null}
import asyncio
import os

from onepassword import (
    Client,
    EditEnvironmentSecretInput,
    PasswordRecipeRandom,
    PasswordRecipeRandomInner,
    Secrets,
)

ENVIRONMENT_ID = "your-environment-id"  # Replace with your Environment's ID
SECRET_NAME = "API_KEY"


def update_provider(new_value: str) -> None:
    # TODO: Replace with the API call that sets the new credential at your provider.
    ...


async def main():
    client = await Client.authenticate(
        os.getenv("OP_SERVICE_ACCOUNT_TOKEN"), "Secret Rotation", "v1.0.0"
    )

    # Generate a new value
    new_value = Secrets.generate_password(
        PasswordRecipeRandom(
            parameters=PasswordRecipeRandomInner(
                length=32,
                includeDigits=True,
                includeSymbols=False,
            )
        ),
    )

    # Update the credential at your provider
    update_provider(new_value)

    # Store the new value in the Environment
    secret = await client.environments.edit_secret(
        ENVIRONMENT_ID,
        SECRET_NAME,
        EditEnvironmentSecretInput(value=new_value),
    )
    print(f"Rotated {secret.name} in Environment {ENVIRONMENT_ID}")


asyncio.run(main())
```

Run the script once to confirm it works. Then check the secret in the [1Password desktop app](https://www.1password.dev/environments.md#manage-your-environments).

## Part 3: Run the script on a schedule

Run the script from any scheduler that can set the `OP_SERVICE_ACCOUNT_TOKEN` environment variable. For example, to run it every day at 02:00 with `cron`, add this line to your crontab:

```shell theme={null}
0 2 * * * OP_SERVICE_ACCOUNT_TOKEN=<your-token> /usr/bin/python3 /path/to/rotate.py
```

To run the script in AWS instead, see the [Rotate an API key with AWS EventBridge](https://github.com/SimonBarendse/1password-sdks-rotation-demo/tree/main/rotation-service) example project.

## Conclusion

In this tutorial, you learned how to rotate a secret in a 1Password Environment on a schedule, without exposing its value or giving the rotation script access to anything else in your account.

You can extend the script to rotate several secrets in one run, or to rotate secrets across multiple Environments.

## Learn more

* [Manage Environments and secrets using 1Password SDKs](https://www.1password.dev/sdks/environments.md)
* [Programmatically access 1Password Environments](https://www.1password.dev/environments/programmatic-access.md)
* [Generate a password using 1Password SDKs](https://www.1password.dev/sdks/manage-items.md#generate-a-password)
* [Tutorial: Get started with 1Password SDKs](https://www.1password.dev/sdks/setup-tutorial.md)
* [Workflow: Secure your deployments](https://www.1password.dev/get-started/secure-deployment.md)


## Related topics

- [Rotate a secret in an Environment](https://www.1password.dev/cli/rotate-environment-secret.md)
- [Manage 1Password Environments and secrets using 1Password SDKs](https://www.1password.dev/sdks/environments.md)
- [1Password SDK tutorials and examples](https://www.1password.dev/sdks/tutorials.md)
