-
Notifications
You must be signed in to change notification settings - Fork 209
DOC-4990 AMR connection page for Go #1605
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
5c657ff
DOC-4990 started Go AMR page
andy-stark-redis ea33034
DOC-4990 rounded out Go AMR page
andy-stark-redis 69e9b7c
Apply suggestions from code review
andy-stark-redis 45b941e
DOC-4990 implemented PR feedback
andy-stark-redis 9d9e46f
Apply suggestions from code review
andy-stark-redis 0ab1114
DOC-4990 added extra example suggested in feedback
andy-stark-redis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,261 @@ | ||
--- | ||
categories: | ||
- docs | ||
- develop | ||
- stack | ||
- oss | ||
- rs | ||
- rc | ||
- oss | ||
- kubernetes | ||
- clients | ||
description: Learn how to authenticate to an Azure Managed Redis (AMR) database | ||
linkTitle: Connect to AMR | ||
title: Connect to Azure Managed Redis | ||
weight: 15 | ||
--- | ||
|
||
The [`go-redis-entraid`](https://github.com/redis/go-redis-entraid) package | ||
lets you authenticate your app to | ||
[Azure Managed Redis (AMR)](https://azure.microsoft.com/en-us/products/managed-redis) | ||
using [Microsoft Entra ID](https://learn.microsoft.com/en-us/entra/identity/). | ||
You can authenticate using a system-assigned or user-assigned | ||
[managed identity](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/overview) | ||
or a [service principal](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals), | ||
letting `go-redis-entraid` fetch and renew the authentication tokens for you automatically. | ||
|
||
## Install | ||
|
||
Install [`go-redis`]({{< relref "/develop/clients/go" >}}) if you | ||
have not already done so. Note that `go-redis-entraid` | ||
requires `go-redis` v9.9.0 or above, so you should upgrade if you | ||
are using an earlier version. | ||
|
||
Install `go-redis-entraid` with the following command: | ||
|
||
```bash | ||
go get github.com/redis/go-redis-entraid | ||
``` | ||
|
||
## Create a `StreamingCredentialsProvider` instance | ||
|
||
The `StreamingCredentialsProvider` interface defines methods | ||
to provide credentials for authentication. Use an object that | ||
implements this interface to obtain the authentication credentials you | ||
need when you connect to Redis. See the sections below to learn how | ||
to create the `StreamingCredentialsProvider` instances for AMR | ||
using the factory functions that `go-redis-entraid` provides. | ||
|
||
|
||
### `StreamingCredentialsProvider` for a service principal | ||
|
||
Use the `NewConfidentialCredentialsProvider()` factory function to create a | ||
`StreamingCredentialsProvider` that authenticates to AMR using a | ||
service principal (see the | ||
[Microsoft documentation](https://learn.microsoft.com/en-us/entra/identity-platform/app-objects-and-service-principals) to learn more about service principals). | ||
|
||
You will need the following details of your service principal to make the connection: | ||
|
||
- Client ID | ||
- Client secret | ||
- Tenant ID | ||
|
||
Use an `AuthorityConfiguration` instance to pass the tenant ID. | ||
This type has the following fields: | ||
|
||
- `AuthorityType`: This should have one of the values | ||
- `identity.AuthorityTypeDefault` ("default") | ||
- `identity.AuthorityTypeMultiTenant` ("multi-tenant") | ||
- `identity.AuthorityTypeCustom` ("custom") | ||
- `TenantID`: Pass your tenant ID string here, or use "common" for | ||
a multi-tentant application. | ||
- `Authority`: Custom authority URL. This is only required if you | ||
specified `AuthorityTypeCustom` in the `AuthorityType` field. | ||
|
||
The example below shows how to import the required modules and call | ||
`NewConfidentialCredentialsProvider()`: | ||
|
||
```go | ||
import ( | ||
"github.com/redis-developer/go-redis-entraid/entraid" | ||
"github.com/redis-developer/go-redis-entraid/identity" | ||
... | ||
) | ||
. | ||
. | ||
provider, err := entraid.NewConfidentialCredentialsProvider( | ||
entraid.ConfidentialCredentialsProviderOptions{ | ||
ConfidentialIdentityProviderOptions: identity.ConfidentialIdentityProviderOptions{ | ||
ClientID: "<your-azure-client-id>", | ||
ClientSecret: "<your-azure-client-secret>", | ||
CredentialsType: identity.ClientSecretCredentialType, | ||
Authority: identity.AuthorityConfiguration{ | ||
AuthorityType: identity.AuthorityTypeDefault, | ||
TenantID: "<your-azure-tenant-id>", | ||
}, | ||
}, | ||
}, | ||
) | ||
``` | ||
|
||
### `StreamingCredentialsProvider` for a managed identity | ||
|
||
Use the `NewManagedIdentityCredentialsProvider()` function to create a | ||
`StreamingCredentialsProvider` that authenticates to AMR using a | ||
managed identity (see the | ||
[Microsoft documentation](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/overview) to learn more about managed identities). | ||
|
||
The example below shows how to import the required modules and call | ||
`NewManagedIdentityCredentialsProvider()`. | ||
Pass `identity.SystemAssignedIdentity` or `identity.UserAssignedIdentity` | ||
as the `ManagedIdentityType` parameter. | ||
|
||
```go | ||
import ( | ||
"github.com/redis-developer/go-redis-entraid/entraid" | ||
"github.com/redis-developer/go-redis-entraid/identity" | ||
... | ||
) | ||
. | ||
. | ||
provider, err := entraid.NewManagedIdentityCredentialsProvider( | ||
entraid.ManagedIdentityCredentialsProviderOptions{ | ||
ManagedIdentityProviderOptions: identity.ManagedIdentityProviderOptions{ | ||
ManagedIdentityType: identity.UserAssignedObjectID, | ||
UserAssignedObjectID: "<your-user-assigned-client-id>", | ||
}, | ||
}, | ||
) | ||
``` | ||
|
||
### Custom configuration | ||
|
||
The examples above use a default configuration but you can also provide a custom | ||
configuration using the `TokenManagerOptions` field of `CredentialsProviderOptions`: | ||
|
||
```go | ||
options := entraid.CredentialsProviderOptions{ | ||
TokenManagerOptions: manager.TokenManagerOptions{ | ||
ExpirationRefreshRatio: 0.7, | ||
LowerRefreshBounds: 10000, | ||
RetryOptions: manager.RetryOptions{ | ||
MaxAttempts: 3, | ||
InitialDelay: 1000 * time.Millisecond, | ||
MaxDelay: 30000 * time.Millisecond, | ||
BackoffMultiplier: 2.0, | ||
IsRetryable: func(err error) bool { | ||
return strings.Contains(err.Error(), "network error") || | ||
strings.Contains(err.Error(), "timeout") | ||
}, | ||
}, | ||
}, | ||
} | ||
``` | ||
|
||
You can then pass this configuration when you create the | ||
`StreamingCredentialsProvider`. The example below shows how to do this | ||
with the `NewManagedIdentityCredentialsProvider()` method: | ||
|
||
```go | ||
provider, err := entraid.NewManagedIdentityCredentialsProvider( | ||
entraid.ManagedIdentityCredentialsProviderOptions{ | ||
CredentialsProviderOptions: options, | ||
ManagedIdentityProviderOptions: identity.ManagedIdentityProviderOptions{ | ||
ManagedIdentityType: identity.UserAssignedObjectID, | ||
UserAssignedObjectID: "<your-user-assigned-client-id>", | ||
}, | ||
}, | ||
) | ||
``` | ||
|
||
The fields of `TokenManagerOptions` are explained below: | ||
|
||
- `ExpirationRefreshRatio`: A `float` value representing the fraction | ||
of a token's lifetime that should elapse before attempting to | ||
refresh it. For example, a value of 0.75 means that you want to | ||
refresh the token after 75% of its lifetime has passed. | ||
- `LowerRefreshBounds`: The minimum amount of the token's lifetime | ||
(in milliseconds) remaining before attempting to refresh, regardless | ||
of the `expirationRefreshRatio` value. Set this to zero if you want | ||
the refresh time to depend only on `expirationRefreshRatio`. | ||
- `RetryOptions`: This object specifies how to retry a token request | ||
after failure. The available options are: | ||
- `MaxAttempts`: The maximum number of times to retry a token request | ||
The default value is 3. | ||
- `InitialDelay`: The initial delay between retries in milliseconds. This | ||
will be modified during successive attempts by the `BackoffMultiplier` | ||
value (see below). The default is 1000ms. | ||
- `BackoffMultiplier`: The factor by which the `InitialDelay` is multiplied | ||
between attempts, following an | ||
[exponential backoff](https://en.wikipedia.org/wiki/Exponential_backoff) | ||
strategy. The default multiplier is 2.0. | ||
- `IsRetryable`: A function that receives an `error` parameter and returns | ||
a boolean `true` result if an attempt that failed with that error is | ||
retryable and `false` otherwise. Use this to implement your own custom | ||
logic to decide which errors should be retried. | ||
|
||
|
||
## Connect | ||
|
||
When you have created your `StreamingCredentialsProvider` instance, you are ready to | ||
connect to AMR. | ||
The example below shows how to pass the instance as a parameter to the standard | ||
`NewClient()` connection method. It also illustrates how to use | ||
[`os.Getenv()`](https://pkg.go.dev/os#Getenv) to get the connection details | ||
from environment variables rather than include their values in the code. | ||
|
||
```go | ||
package main | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"log" | ||
"os" | ||
"strings" | ||
|
||
"github.com/redis-developer/go-redis-entraid/entraid" | ||
"github.com/redis/go-redis/v9" | ||
) | ||
|
||
func main() { | ||
// Get required environment variables | ||
redisEndpoint := os.Getenv("REDIS_ENDPOINT") | ||
if redisEndpoint == "" { | ||
log.Fatal( | ||
"REDIS_ENDPOINT environment variable is required" | ||
) | ||
} | ||
|
||
// Create credentials provider for system assigned identity | ||
provider, err := entraid.NewManagedIdentityCredentialsProvider( | ||
entraid.ManagedIdentityCredentialsProviderOptions{ | ||
ManagedIdentityProviderOptions: identity.ManagedIdentityProviderOptions{ | ||
ManagedIdentityType: identity.SystemAssignedIdentity, | ||
}, | ||
} | ||
) | ||
if err != nil { | ||
log.Fatalf("Failed to create credentials provider: %v", err) | ||
} | ||
|
||
// Create Redis client | ||
client := redis.NewClient(&redis.Options{ | ||
Addr: redisEndpoint, | ||
StreamingCredentialsProvider: provider, | ||
}) | ||
defer client.Close() | ||
|
||
// Test connection | ||
ctx := context.Background() | ||
if err := client.Ping(ctx).Err(); err != nil { | ||
log.Fatalf("Failed to connect to Redis: %v", err) | ||
} | ||
log.Println("Connected to Redis!") | ||
} | ||
``` | ||
|
||
## More information | ||
|
||
See the [`go-redis-entraid`](https://github.com/redis/go-redis-entraid) | ||
GitHub repository for full source code and more examples and details. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@andy-stark-redis do you think it will be beneficial to have a complete example on where those options are supposed to be passed?
For example, just after initiating this
options
variable, have something like :There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@ndyakov Yeah, that's a good idea. I've added the code you suggested with some small changes to the text to help it fit in.