<@U04UQ68083H> when changing identity schema, how ...
# ory-copilot
m
@chilly-king-10285 when changing identity schema, how to run a migration?
b
A message from kapa.ai
When changing the identity schema in Ory, you need to ensure that existing identities are updated to match the new schema. The migration process involves updating each identity’s schema ID and traits to conform to the new schema. Here’s how you can run such a migration: 1. Update the Project’s Active Schema Change the active schema for your project using the Ory Console or CLI. This will only affect new identities; existing identities will still use the old schema until migrated. 2. List Existing Identities Retrieve all identities in your project:
Copy code
ory list identities --format json-pretty
3. Patch Each Identity to the New Schema For each identity, update the
schema_id
and adjust the
traits
as needed to match the new schema. This can be done using the [patchIdentity API](https://www.ory.sh/docs/reference/api#tag/identity/operation/patchIdentity). Here’s an example using cURL:
Copy code
curl --location --request PATCH "https://$<http://ORY_SLUG.projects.oryapis.com/admin/identities/$IDENTITY_ID|ORY_SLUG.projects.oryapis.com/admin/identities/$IDENTITY_ID>" \    --header "Authorization: Bearer $ORY_API_KEY" \    --header "Content-Type: application/json" \    --data-raw '[      {        "op": "replace",        "path": "/schema_id",        "value": "{new-schema-id}"      },      {        "op": "remove",        "path": "/traits/foo"      },      {        "op": "add",        "path": "/traits/bar",        "value": "barfoo"      }    ]'
Repeat this for each identity that needs to be migrated. 4. (Optional) Bulk Update with SDK You can automate this process using the Ory SDKs. Here’s a Go example that checks and updates the schema for a single identity:
Copy code
go    // ... (see full code in the knowledge source)    _, _, err = ory.IdentityApi.PatchIdentity(ctx, identityID).JsonPatch(jsonPatch).Execute()
This approach can be extended to process all identities in a loop. 5. Verify Migration After patching, verify that each identity’s
schema_id
matches the new schema and that their traits conform to the new requirements. Note: - Identity schemas are immutable; you cannot update an existing schema, but you can create a new one and migrate identities to it. - Always assess and transform traits as needed to avoid inconsistencies. - For large migrations, consider scripting the process or using the batch API. For more details and code examples, see the official documentation on [updating identities to use a new schema](https://www.ory.sh/docs/identities/model/manage-identity-schema#update-identities-to-use-a-new-schema) and [identity schema best practices](https://www.ory.sh/docs/kratos/manage-identities/best-practices)