Monday, October 12, 2015

Utilizing User-Provided Services to Link Bluemix Apps to External Databases

Recently, I wrote a Bluemix app which only utilized one of the provided runtimes (Python, node.js, Java, ...). The database was external to the Bluemix environment and didn't come out of the many offerings in the "Data and Analytics" catalog. As I wanted to keep my app as generic as possible, I searched for a way of how to link app and database. One solution is to use so-called user-provided service. Here is what I did.

Once I had provisioned my runtime on Bluemix (Python for this example), the app showed up on the dashboard. As can be seen, it is not linked to any service. Because the database is not provided out of the Bluemix catalog, there isn't any entry or reference to the database yet. What can be done now is to create a Cloud Foundry user-provided service using the command-line interface (CLI):
 
App with Runtime only on Bluemix



[hloeser@mymachine] cf cups mydb2 -p '{
"jdbcUrl": "jdbc:db2://hl1234.integration.ibmcloud.com:15141/testdb","username": "dbuser2", "password": "no_secrets" }'


Creating user provided service mydb2 in org hloeser@de.ibm.com / space dev as hloeser@de.ibm.com...
 

OK

The above command creates that service in Bluemix and an entry is added to the dashboard (see screenshot below). The option "cups" is a shorthand for "create-user-provided-service". The specified JSON document is the description of that service, all what Bluemix or the app need to know in order to use it. But before the app can use it, it needs to be bound to that service. This is accomplished by binding the two together (bind-service):

Bluemix app with user-provided service
[hloeser@mymachine] cf bind-service hl-external-db mydb2
Binding service mydb2 to app hl-external-db in org hloeser@de.ibm.com / space dev as hloeser@de.ibm.com...
OK
TIP: Use 'cf push' to ensure your env variable changes take effect



Once the app is now restarted or pushed again, the app tile on the dashboard has changed as it has picked up the changes. The tile for the service "mydb2" also has a reference to the app.
User-provided service with reference to app

When looking at the details of the app, in our case the environment variables, the previously defined properties of our user-provided service can be seen. Our app could now access the VCAP_SERVICES environment variable and pick up the information about the database to use in the user-provided services section. The service description can be changed depending on where our database is hosted (on premise and accessible via a Secure Gateway, somewhere as a DBaaS the cloud, ...). Our app does not need to care where the data is hosted as it picks up the database properties through the Bluemix environment.
User-provided service in the VCAP_SERVICES variable on Bluemix