IBM Cloud App Configuration SDK is used to perform feature flag and property evaluation based on the configuration on IBM Cloud App Configuration service.
IBM Cloud App Configuration is a centralized feature management and configuration service on IBM Cloud for use with web and mobile applications, microservices, and distributed environments.
Instrument your applications with App Configuration Go SDK, and use the App Configuration dashboard, API or CLI to define feature flags or properties, organized into collections and targeted to segments. Change feature flag states in the cloud to activate or deactivate features in your application or environment, when required. You can also manage the properties for distributed applications centrally.
- Go version 1.16 or newer
Note: The v1.x.x versions of the App Configuration Go SDK have been retracted. Use the latest available version of the SDK.
There are a few different ways to download and install the IBM App Configuration Go SDK project for use by your Go application:
Use this command to download and install the SDK (along with its dependencies) to allow your Go application to use it:
go get -u github.com/IBM/appconfiguration-go-sdk@latest
If your application is using Go modules, you can add a suitable import to your Go application, like this:
import (
AppConfiguration "github.com/IBM/appconfiguration-go-sdk/lib"
)
then run go mod tidy
to download and install the new dependency and update your Go application's go.mod file.
Initialize the sdk to connect with your App Configuration service instance.
collectionId := "airlines-webapp"
environmentId := "dev"
appConfigClient := AppConfiguration.GetInstance()
appConfigClient.Init("region", "guid", "apikey")
appConfigClient.SetContext(collectionId, environmentId)
đź”´ Important đź”´
The Init()
and SetContext()
are the initialisation methods and should be invoked only once using
appConfigClient. The appConfigClient, once initialised, can be obtained across modules
using AppConfiguration.GetInstance()
. See this example below.
- region : Region name where the App Configuration service instance is created. Use
AppConfiguration.REGION_US_SOUTH
for DallasAppConfiguration.REGION_EU_GB
for LondonAppConfiguration.REGION_AU_SYD
for SydneyAppConfiguration.REGION_US_EAST
for Washington DCAppConfiguration.REGION_EU_DE
for Frankfurt
- guid : Instance Id of the App Configuration service. Obtain it from the service credentials section of the App Configuration dashboard.
- apikey : ApiKey of the App Configuration service. Obtain it from the service credentials section of the App Configuration dashboard.
- collectionId: Id of the collection created in App Configuration service instance under the Collections section.
- environmentId: Id of the environment created in App Configuration service instance under the Environments section.
Set the SDK to connect to App Configuration service by using a private endpoint that is accessible only through the IBM Cloud private network.
appConfigClient.UsePrivateEndpoint(true)
This must be done before calling the Init
function on the SDK.
In order for your application and SDK to continue its operations even during the unlikely scenario of App Configuration service across your application restarts, you can configure the SDK to work using a persistent cache. The SDK uses the persistent cache to store the App Configuration data that will be available across your application restarts.
appConfigClient.SetContext(collectionId, environmentId, AppConfiguration.ContextOptions{
PersistentCacheDirectory: "/var/lib/docker/volumes/",
})
- PersistentCacheDirectory: Absolute path to a directory which has read & write permission for the user. The SDK will
create a file -
appconfiguration.json
in the specified directory, and it will be used as the persistent cache to store the App Configuration service information.
When persistent cache is enabled, the SDK will keep the last known good configuration at the persistent cache. In the case of App Configuration server being unreachable, the latest configurations at the persistent cache is loaded to the application to continue working.
Please ensure that the cache file is not lost or deleted in any case. For example, consider the case when a kubernetes pod is restarted and the cache file (appconfiguration.json) was stored in ephemeral volume of the pod. As pod gets restarted, kubernetes destroys the ephermal volume in the pod, as a result the cache file gets deleted. So, make sure that the cache file created by the SDK is always stored in persistent volume by providing the correct absolute path of the persistent directory.
The SDK is also designed to serve configurations, perform feature flag & property evaluations without being connected to App Configuration service.
appConfigClient.SetContext(collectionId, environmentId, AppConfiguration.ContextOptions{
BootstrapFile: "saflights/flights.json",
LiveConfigUpdateEnabled: false,
})
- BootstrapFile: Absolute path of the JSON file, which contains configuration details. Make sure to provide a proper
JSON file. You can generate this file using
ibmcloud ac export
command of the IBM Cloud App Configuration CLI. - LiveConfigUpdateEnabled: Live configuration update from the server. Set this value to
false
if the new configuration values shouldn't be fetched from the server. By default, this value is set totrue
.
feature, err := appConfigClient.GetFeature("online-check-in")
if err == nil {
fmt.Println("Feature Name", feature.GetFeatureName())
fmt.Println("Feature Id", feature.GetFeatureID())
fmt.Println("Feature Type", feature.GetFeatureDataType())
if (feature.IsEnabled()) {
// feature flag is enabled
} else {
// feature flag is disabled
}
}
features, err := appConfigClient.GetFeatures()
if err == nil {
feature := features["online-check-in"]
fmt.Println("Feature Name", feature.GetFeatureName())
fmt.Println("Feature Id", feature.GetFeatureID())
fmt.Println("Feature Type", feature.GetFeatureDataType())
fmt.Println("Is feature enabled?", feature.IsEnabled())
}
Use the feature.GetCurrentValue(entityId, entityAttributes)
method to evaluate the value of the feature flag.
GetCurrentValue returns one of the Enabled/Disabled/Overridden value based on the evaluation.
entityId := "john_doe"
entityAttributes := make(map[string]interface{})
entityAttributes["city"] = "Bangalore"
entityAttributes["country"] = "India"
featureVal := feature.GetCurrentValue(entityId, entityAttributes)
-
entityId: entityId is a string identifier related to the Entity against which the feature will be evaluated. For example, an entity might be an instance of an app that runs on a mobile device, a microservice that runs on the cloud, or a component of infrastructure that runs that microservice. For any entity to interact with App Configuration, it must provide a unique entity ID.
-
entityAttributes: entityAttributes is a map of type
map[string]interface{}
consisting of the attribute name and their values that defines the specified entity. This is an optional parameter if the feature flag is not configured with any targeting definition. If the targeting is configured, then entityAttributes should be provided for the rule evaluation. An attribute is a parameter that is used to define a segment. The SDK uses the attribute values to determine if the specified entity satisfies the targeting rules, and returns the appropriate feature flag value.
property, err := appConfigClient.GetProperty("check-in-charges")
if err == nil {
fmt.Println("Property Name", property.GetPropertyName())
fmt.Println("Property Id", property.GetPropertyID())
fmt.Println("Property Type", property.GetPropertyDataType())
}
properties, err := appConfigClient.GetProperties()
if err == nil {
property := properties["check-in-charges"]
fmt.Println("Property Name", property.GetPropertyName())
fmt.Println("Property Id", property.GetPropertyID())
fmt.Println("Property Type", property.GetPropertyDataType())
}
Use the property.GetCurrentValue(entityId, entityAttributes)
method to evaluate the value of the property.
GetCurrentValue returns the default property value or its overridden value based on the evaluation.
entityId := "john_doe"
entityAttributes := make(map[string]interface{})
entityAttributes["city"] = "Bangalore"
entityAttributes["country"] = "India"
propertyVal := property.GetCurrentValue(entityId, entityAttributes)
- entityId: entityId is a string identifier related to the Entity against which the property will be evaluated. For example, an entity might be an instance of an app that runs on a mobile device, a microservice that runs on the cloud, or a component of infrastructure that runs that microservice. For any entity to interact with App Configuration, it must provide a unique entity ID.
- entityAttributes: entityAttributes is a map of type
map[string]interface{}
consisting of the attribute name and their values that defines the specified entity. This is an optional parameter if the property is not configured with any targeting definition. If the targeting is configured, then entityAttributes should be provided for the rule evaluation. An attribute is a parameter that is used to define a segment. The SDK uses the attribute values to determine if the specified entity satisfies the targeting rules, and returns the appropriate property value.
secretPropertyObject, err := appConfigClient.GetSecret(propertyID, secretsManagerService)
- propertyID: propertyID is the unique string identifier, using this we will be able to fetch the property which will provide the necessary metadata to fetch the secret.
- secretsManagerService: an initialised secrets manager client, which will be used for getting the secret data during the secret property evaluation. Create a secret manager client by referring the doc: https://cloud.ibm.com/apidocs/secrets-manager/secrets-manager-v2?code=go#authentication
Use the secretPropertyObject.GetCurrentValue(entityId, entityAttributes)
method to evaluate the value of the secret property.
GetCurrentValue returns the secret value based on the evaluation.
entityId := "john_doe"
entityAttributes := make(map[string]interface{})
entityAttributes["city"] = "Bangalore"
entityAttributes["country"] = "India"
getSecretRes, detailedResponse, err := secretPropertyObject.GetCurrentValue(entityId, entityAttributes)
// See below to know how to access the secret data from the detailedResponse
- entityId: entityId is a string identifier related to the Entity against which the property will be evaluated. For example, an entity might be an instance of an app that runs on a mobile device, a microservice that runs on the cloud, or a component of infrastructure that runs that microservice. For any entity to interact with App Configuration, it must provide a unique entity ID.
- entityAttributes: entityAttributes is a map of type
map[string]interface{}
consisting of the attribute name and their values that defines the specified entity. This is an optional parameter if the property is not configured with any targeting definition. If the targeting is configured, then entityAttributes should be provided for the rule evaluation. An attribute is a parameter that is used to define a segment. The SDK uses the attribute values to determine if the specified entity satisfies the targeting rules, and returns the appropriate value.
Full example :
import (
"github.com/IBM/go-sdk-core/v5/core"
sm "github.com/IBM/secrets-manager-go-sdk/v2/secretsmanagerv2"
)
secretsManagerService, err := sm.NewSecretsManagerV2(&sm.SecretsManagerV2Options{
URL: "<SECRETS_MANAGER_INSTANCE_URL>",
Authenticator: &core.IamAuthenticator{
ApiKey: "<SECRETS_MANAGER_APIKEY>",
},
})
secretPropertyObject, err := appConfigClient.GetSecret(propertyID, secretsManagerService)
getSecretRes, detailedResponse, err := secretPropertyObject.GetCurrentValue(entityId, entityAttributes)
// For Arbitrary secret type
secretData := *detailedResponse.Result.(*sm.ArbitrarySecret).Payload
// For username-password secret type
secretData := *detailedResponse.Result.(*sm.UsernamePasswordSecret).Username
secretData := *detailedResponse.Result.(*sm.UsernamePasswordSecret).Password
// For key-value secret type
secretData := detailedResponse.Result.(*sm.KVSecret).Data["key1"]
secretData := detailedResponse.Result.(*sm.KVSecret).Data["key2"]
The GetCurrentValue will be sending the 3 objects as part of response.
- getSecretRes: this will give the meta data and payload.
- detailedResponse: this will give entire data which includes the http response header data, meta data and payload.
- err: this will give the error response if the request is invalid or failed for some reason.
Once the SDK is initialized, the appConfigClient can be obtained across other modules as shown below:
// **other modules**
import (
AppConfiguration "github.com/IBM/appconfiguration-go-sdk/lib"
)
appConfigClient := AppConfiguration.GetInstance()
feature, err := appConfigClient.GetFeature("online-check-in")
if (err == nil) {
enabled := feature.IsEnabled()
featureValue := feature.GetCurrentValue(entityId, entityAttributes)
}
App Configuration service allows to configure the feature flag and properties in the following data types : Boolean, Numeric, SecretRef, String. The String data type can be of the format of a text string , JSON or YAML. The SDK processes each format accordingly as shown in the below table.
View Table
Feature value or Property value | DataType | DataFormat | Type of data returned by GetCurrentValue() |
Example output |
---|---|---|---|---|
true |
BOOLEAN | not applicable | bool |
true |
25 |
NUMERIC | not applicable | float64 |
25 |
{ |
SECRETREF(this type is applicable only for Property ) |
not applicable | map[string]interface{} |
{ Note: Along with the above data we will also provide the detailedResponse and error data. For more info on the response data refer #how-to-access-the-payload-secret-data-from-the-response |
"a string text" | STRING | TEXT | string |
a string text |
{ |
STRING | JSON | map[string]interface{} |
map[browsers:map[firefox:map[name:Firefox pref_url:about:config]]] |
men: |
STRING | YAML | map[string]interface{} |
map[men:[John Smith Bill Jones] women:[Mary Smith Susan Williams]] |
Feature flag
feature, err := appConfigClient.GetFeature("json-feature")
if err == nil {
feature.GetFeatureDataType() // STRING
feature.GetFeatureDataFormat() // JSON
// Example (traversing the returned map)
result := feature.GetCurrentValue(entityID, entityAttributes) // JSON value is returned as a Map
result.(map[string]interface{})["key"] // returns the value of the key
}
feature, err := appConfigClient.GetFeature("yaml-feature")
if err == nil {
feature.GetFeatureDataType() // STRING
feature.GetFeatureDataFormat() // YAML
// Example (traversing the returned map)
result := feature.GetCurrentValue(entityID, entityAttributes) // YAML value is returned as a Map
result.(map[string]interface{})["key"] // returns the value of the key
}
Property
property, err := appConfigClient.GetProperty("json-property")
if err == nil {
property.GetPropertyDataType() // STRING
property.GetPropertyDataFormat() // JSON
// Example (traversing the returned map)
result := property.GetCurrentValue(entityID, entityAttributes) // JSON value is returned as a Map
result.(map[string]interface{})["key"] // returns the value of the key
}
property, err := appConfigClient.GetProperty("yaml-property")
if err == nil {
property.GetPropertyDataType() // STRING
property.GetPropertyDataFormat() // YAML
// Example (traversing the returned map)
result := property.GetCurrentValue(entityID, entityAttributes) // YAML value is returned as a Map
result.(map[string]interface{})["key"] // returns the value of the key
}
The SDK provides mechanism to notify you in real-time when feature flag's or property's configuration changes. You can subscribe to configuration changes using the same appConfigClient.
appConfigClient.RegisterConfigurationUpdateListener(func () {
// **add your code**
// To find the effect of any configuration changes, you can call the feature or property related methods
// feature, err := appConfigClient.GetFeature("json-feature")
// newValue := feature.GetCurrentValue(entityID, entityAttributes)
})
appConfigClient.FetchConfigurations()
appConfigClient.EnableDebug(true)
Try this sample application in the examples folder to learn more about feature and property evaluation.
This project is released under the Apache 2.0 license. The license's full text can be found in LICENSE