- 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
- 1Password subscription.
- 1Password desktop app.
- An Environment that contains the secret you want to rotate.
- Basic knowledge of Python.
- Familiarity with 1Password SDKs. To learn how to get started, see the end-to-end setup tutorial.
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 and add the secret you want to rotate. For our example, we’ll use an Environment namedProduction that contains a secret named API_KEY.
Step 2: Create a service account with write access to the Environment
Service accounts 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 theProduction Environment, so it can edit the secret.
- Use the service account creation wizard on 1Password.com.
- Give your service account a name. For example,
Secret Rotation Service Account. - Choose the
ProductionEnvironment and give the service account write access. This can’t be changed later. - 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 to theOP_SERVICE_ACCOUNT_TOKEN environment variable.
- Bash, Zsh, sh
- fish
- PowerShell
Step 2: Generate a new value
Use theSecrets.generate_password() method to generate the new value. In our example, we generate a 32-character random string with letters and digits.
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.Step 4: Store the new value in the Environment
Use theenvironments.edit_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:
Part 3: Run the script on a schedule
Run the script from any scheduler that can set theOP_SERVICE_ACCOUNT_TOKEN environment variable. For example, to run it every day at 02:00 with cron, add this line to your crontab: