Posts Tagged ‘cloud computing’

Deploying Play Framework 2 apps, with Java AND Scala, to Openshift

Let’s Play! in the cloud

A couple of weeks, Mark Atwood, Jorge Aliss, and me, Sebastián Scarano participated in Red Hat’s webinar LET’S PLAY! IN THE CLOUD: DEVELOPING JAVA WEB APPS ON OPENSHIFT

In the webinar Mark gave a neat introduction to Openshift, Red Hat’s free Platform as a Service:

Then we developed a basic contact manager web application, combining Java and Scala source code in the same Play 2 application, and deployed it on Openshift.

With this quickstart ( you’ll be able to take any Play 2 application and deploy it on openshift. Just follow this instructions.

And here ( you will find the contact demo app.

In the demo, in spite our internet connection conspiring against us, we managed to cover the following topics:

You can also check this article in which we explain in detail how we took advantage of the new “do-it-yourself” application type on Openshift to achieve native support for Play Framework application on Openshift.

So, if you want to start deploying your play apps on openshift right away, just sign up at and enter PLAY!WEBINAR as promotional code, and you’ll get 3 gears, each with 1GB ram and 512 MB data space, for free.

Have fun playing on the cloud!

Troubleshooting Play Framework 2 apps on Openshift

Troubleshooting Openshift

With the do-it-yourself application type you really get a lot of freedom to support almost any framework or server that can be built and run on a linux box. But you do have to make your homework, and do some research.

So in this article I’ll show you a couple of tips I learnt playing around with Openshift and Play Framework.

Comments are more than welcome, so I hope you can also provide me some more tips to help us all get our apps running on the cloud.

Providing native support for play framework application

Right now, the solution we found for deploying Play 2.0 apps on openshift is quite handy, but we could make it a little better..

The problem is that we have to compile the app locally (issuing play stage) and then push 30 MB of libraries to Openshift. The ideal thing, and that’s what we did with the Play 1.x quickstart and with the latest version of Openshift module for Play Framework 1.x, would be to just upload our sources and then let Openshift download and install Play, compile our app, and start it.

Unfortunately we’ve ran with some memory constraints (seems like compiling Play 2 apps is a bit memory demanding) that eventually raised some issues. We are trying to work them out, but perhaps, with this tips, you could help has troubleshoot it.

With the opensourcing of Openshift and the new Origin livecd we have more tools available for us to further investigate what’s going on, I just didn’t have time yet to start playing with it.

So, enought chatter, and let’s get our hands dirty.

Houston, we have a problem

All right, you’ve just read this guide or followed our steps on the Play Framework webinar using this Play 2.0 quickstart (in fact, some of this tips will help trouble shoot any app running on Openshift) and something went wrong.

First of all, have a look at the logs. Just issue

rhc app tail -a myapp -l -p mysecretpass

Leave that window open, it will become quite handy later.

Then we’ll ssh into our remote machine. Just issue:

rhc app show -a myapp -l -p mysecretpass

and you’ll get something like

Application Info
    Framework: diy-0.1
     Creation: 2012-04-19T14:20:16-04:00
         UUID: 0b542570e41b42e5ac2a255c316871bc
      Git URL: ssh://
   Public URL:


Take the part after the ssh of the Git URL stuff, and log into you openshift machine:


(If you are lazy like me, go on and vote for an easier way to ssh into openshift)

It’s also a good idea to open another command window, ssh into openshift, and run something like “top” or “watch -n 2 free -m” to keep an eye on memory usage.

Troubleshooting Play

You know the old motto, “write once, run everywhere”… well it just “should” work, but just in case you could try compiling your app with the same JDK version as the one running on openshift.

Just run

java -version
java version "1.6.0_22"
OpenJDK Runtime Environment (IcedTea6 1.10.6) (rhel-
OpenJDK Server VM (build 20.0-b11, mixed mode)

And install the same jdk version on your box. Then compile your app and redeploy (you can use the convenience script openshift_deploy)

If that doesn’t work, try to do the whole process manually on Openshift. You should do something like this:

# download play
curl -o

#stop app

#clean everything - watch for errors, if it fails retry a couple more times
${OPENSHIFT_DATA_DIR}play-2.0.1/play clean 

if you get something like:

/var/lib/stickshift/0b542570e41b42e5ac2a255c316871bc/myapp/data/play-2.0.1/framework/build: line 11: 27439 Killed 

It means it failed miserably (that’s the memory problem I told you about)

And it’s such a bad tempered error that you’ll also loose you command prompt. Just blindily type “reset” and hit enter, you’ll get your prompt back.

And then just try again…

You might also get this message:

This project uses Play 2.0!
Update the Play sbt-plugin version to 2.0.1 (usually in project/plugins.sbt)

That means you created the app with Play 2.0 and you are now trying to compile it with a different version.

Just update project/plugins.sbt file or download the appropiate version.

Now compile and stage your app.

#compile everything - watch for errors, if it fails retry a couple more times
${OPENSHIFT_DATA_DIR}play-2.0.1/play compile

#stage - watch for errors, if it fails retry a couple more times
${OPENSHIFT_DATA_DIR}play-2.0.1/play stage

Then run it (don’t be shy and have a look at the action hooks scripts on the quickstart repo).

target/start -Dhttp.port=8080 -Dhttp.address=${OPENSHIFT_INTERNAL_IP} -Dconfig.resource=openshift.conf

Go check it at

If everything works ok, just stop it with ctrl-c, and then run:


You should see your app starting in the console with the logs files

Now you can log out from the ssh session with ctrl-d, and issue:

rhc app restart -a myapp -l -p mysecretpass

and you should see something like

Stopping play application
Trying to kill proccess, attempt number 1
kill -SIGTERM 19128
/var/lib/stickshift/0b542570e41b42e5ac2a255c316871bc/openbafici/repo/target/start "-DapplyEvolutions.default=true" -Dhttp.port=8080 -Dhttp.address= -Dconfig.resource=openshift.conf
Play server process ID is 21226
[info] play - Application started (Prod)
[info] play - Listening for HTTP on port 8080...

I hope this tips will become useful. As I told, I’m looking forward to start playing with the Openshift Origin livecd, and then I’ll tell you about.

In the meantime I’ll leave you with the company of the good old Openshift Rocket Bear, I know you miss him too, so why not get him back?

Desplegando aplicaciones de Play Framework 2, con Java Y Scala, en Openshift

Play framework en la nube de Red Hat

Hace un par de semanas, Mark Atwood, Jorge Aliss, y quien les escribe, Sebastián Scarano participamos del webinar LET’S PLAY! IN THE CLOUD: DEVELOPING JAVA WEB APPS ON OPENSHIFT organizado por Red Hat.

En el webinar, Mark dio una completa introducción a Openshift, la plataforma de cloud computing de Red Hat:

Luego junto con Jorge desarrollamos una simple agenda de contactos, usando Play Framework 2.0, combinando en una misma aplicación código fuente en Java y en Scala, y luego la pusimos en producción en Openshift.

Con este quickstart ( podrán desplegar cualquier aplicación de Play 2.0 en Openshift. Simplemente sigan estas instrucciones.

Y aquí ( encontrarán el código fuente de la agenda de contactos.

En la demo, a pesar de que nuestra conexión a internet nos jugó una mala pasada, logramos abordar los siguientes temas:

También pueden consultar este artículo en el cual analizamos en detalle cómo aprovechar el nuevo tipo de aplicación “do-it-yourself” (hagalo usted mismo) de Openshift para brindar soporte nativo a las aplicaciones de Play.

Si que si desean empezar a jugar con Openshift ya mismo, regístrense en ingresen PLAY!WEBINAR como código de promoción, y recibirán 3 gears, cada uno con 1GB de memoria ram y 512 MB de espacio de almacemiento, gratis.

¡Esperamos que les guste!

Soporte nativo para Play framework en Openshift con el nuevo tipo de aplicación DIY

Por Sebastián Scarano @develsas. La versión original de este artículo está disponible en el Blog oficial de Openshift

Ya está en línea el contenido del webinar en el que mostramos cómo desarrollar una aplicación de Play 2.0, combinando Java Y Scala en la misma aplicación, y ponerla en producción en Openshift.

Cuando todas las opciones no son suficientes

Hace tan sólo algunos días nos enteremos del lanzamiento de un nuevo tipo de aplicación en Openshift denominada “do-it-yourself” o “hágalo-usted-mismo”. En este artículo mostraremos cómo podemos sacar el máximo provecho de esta nueva herramienta que se suma al arsenal de Openshift.

¿Qué es Play? Play es un framework que nos permite desarrollador aplicaciones Web, con Java o Scala, de una manera mucho más fácil, permitiéndonos alcanzar niveles de productividad que hasta el momento parecían patrimonio exclusivo de los frameworks basados en lenguajes dinámicos, como rails o django. Play forma parte también de los nuevos frameworks que se atrevieron a darle la espalda a la API de servlets y decidieron tomar otro rumbo. Es así como Play implementa su propio servidor http, sumamente liviano y optimizado, preparado para funcionar de manera asincrónica. Todo esto haciendo uso de Netty, una librería específicamente pensada para desarrollar este tipo de servidores, y que casualmente forma parte del stack de Jboss.

Ahora bien, si ya conoce Openshift, sabrá que le brinda múltiples opciones a la hora de desarrollar y poner en producción sus aplicaciones en la nube de Red Hat. Puede elegir trabajar con PHP, Ruby, Perl, Python, Node.js o Java. Y en lo que respecta a la base de datos puede elegir entre MySQL, PostreSQL y MongoDB.

Sin embargo, a pesar de esta abundante cantidad de opciones, el desarrollo de aplicaciones web se mueve a un ritmo tan rápido que ninguna plataforma es capaz de seguirle el paso. Cada día es más común trabajar con servidores http hechos a medida, construidos pensando en alta escalabilidad con bajo consumo de recursos. En lo que respecta a Java, el omnipresente servlet container, ya ha dejado de ser la única opción disponible.

Frente a este panorama, ¿qué podemos hacer para soportar todas estas heterogéneas tecnologías en constante movimiento? Bueno, los ingenieros de Red Hat dieron con una solución muy simple, pero al mismo tiempo sumamente poderosa.

Presentando el tipo de aplicación DIY – Hágalo-usted-mismo

Estos son los tipos de aplicación actualmente soportados en Openshift: jbossas-7, python-2.6, jenkins-1.4, ruby-1.8, diy-0.1, php-5.3, and perl-5.10

Bueno, no cuesta mucho darse cuenta de qué trata cada uno, salvo uno de ellos que se ve un tanto sospechoso: diy-0.1

Una aplicación “DIY” no es más que una aplicación completamente vacía, sin ningún framework ni servidor previamente cargado, listo para que lo personalicemos según nuestras propias necesidades. Con este nuevo tipo de aplicación, Openshift está comenzado a hacer más difusa la línea que separa un IaaS (Infraestructura como servicio) de un PaaS (Plataforma como servicio), poniendo a nuestro alcance un entorno controlado y escalable, pero al mismo tiempo dándonos la libertad para implementar la tecnología que mejor se ajuste a nuestras necesidades. [Tenga en cuenta que al momento de escribir este artículo, el tipo de aplicación DIY se encuentra en estado experimental]

Soporte nativo de Play en Openshift

Para mostrar las posibilidades que este nuevo tipo de aplicación pone en nuestras manos, implementaremos uno de los pedidos más votados en Openshift: soporte nativo para Play framework.

Hasta el día de hoy, para poner en producción una aplicación Play en Openshift, la única opción que teníamos era empaquetarla en un archivo war y desplegarla en un servlet container, lo cual funcionaba muy bien y era muy fácil, como explica este artículo. La única contra era que al hacerlo desperciábamos preciosos recursos y no podíamos hacer uso de prestaciones avanzadas de Play, como el manejo de requests asincrónicos.

Para darse una idea de qué es lo que nos proponemos conseguir, pueden echar una mirada al quickstart que preparamos para este artículo. Simplemente tienen que crear una nueva aplicación en Openshift, eligiendo como tipo diy-0.1, hacer un pull de los fuentes del quickstart, y luego hacer un push a su repositorio de openshift… ¡y eso es todo! Aquí están los pasos:

rhc app create -a play -t diy-0.1 -l
cd play 
git remote add quickstart -m master
git pull -s recursive -X theirs quickstart master 
git push 

Luego de completados esos pasos, su aplicación estará lista y esperándolo en

También hemos preparado un quickstart para Play framework 2.

Ahora, si tiene ganas de meterse a fondo y ver cómo hemos logrado esto, y al mismo tiempo prepararse para empezar a crear sus propios quickstarts, no tiene más que seguir leyendo…

¡Adiós a los servlets!

Antes de intentar crear una aplicación de tipo DIY en Openshift, tendrá que familizarse con la tecnología que planea poner en producción. Es preciso conocer en detalle los pasos necesarios para configurar todas las herramientas necesarias en su propia estación de trabajo, para luego replicar esto en Openshift.

En el caso de una aplicación de Play framework, no necesitaremos un completo servidor de aplicaciones como Jboss, ni tampoco un servidor web al estilo Tomcat, es más, ni siquiera un simple servlet container. Tan sólo tendremos que instalar Play e iniciar el servidor http que trae incluido.

Hacer esto en su propia estación de trabajo es tan fácil como descargar Play de la web, descomprimirlo y ejecutar:

play new demo 
cd demo 
play start

Y para detener la aplicación:

play stop

Ahora tan solo tendremos que hacer esto mismo en nuestro servidor en Openshift.

Conociendo nuestra propia nube

Vamos a crear una nueva aplicación en Openshift, de tipo diy-1.0, llamada ‘raw’.

rhc app create -a raw -t diy-0.1 -l

Ahora echémosle una mirada a lo que acabamos de crear

rhc app show -a raw -l

Application Info
    Framework: diy-0.1
     Creation: 2012-03-19T01:18:31-04:00
         UUID: youruuid
      Git URL: ssh://
   Public URL:

Puede navegar a para ver la página de nuestro sitio.

Es la misma página estática que encontraremos en raw/index.html

Ahora veamos que nos espera en nuestro repositorio local:

cd raw
ls -a

.git                      # nuestro repositorio local de git
misc                      # un directorio vacío, puede borrarlo, nadie extrañará su presencia
.openshift/action_hooks   # aquí están los scripts para iniciar y frenar nuestra aplicación
raw                       # la paǵina estática de error
README                    # información de utilidad

Como ya dijimos, una aplicación completamente vacía, pero hay una carpeta que nos resultará particularmente interesante:

ls .openshift/actions_hooks
build  deploy  post_deploy  pre_build  start  stop

Estos son los scripts que Openshift utiliza para compilar, desplegar, iniciar y detener nuestra aplicación. Estos escripts son ejecutados en el servidor remoto de Openshift luego de cada push. Así que ahora los analizaremos en detalle para conocer mejor el entorno en que correrá nuestra aplicación.

Tomemos la salida del comando `rhc app show -a raw` y ejecutemos el siguiente comando:


De esta manera podrá acceder a su máquina remota en openshift. En su directorio HOME encontrará los siguientes directorios:

    .env            # Contiene la definición de las variables de entorno

    .git  # Aquí está su propio repositorio de git, disponible en ssh://

    repo            # $OPENSHIFT_DATA_DIR - Aquí está el contenido de la carpeta de su aplicación.
                    # Cada vez que hace un push, los datos se guardan aquí.

    data            # $OPENSHIFT_DATA_DIR - Este es un directorio persistente, 
                    # la info que guarde allí no se irá con cada reinicio del servidor

    logs            # $OPENSHIFT_LOG_DIR - Aquí debería guardar los archivos de log de su aplicación
                    # Es la carpeta que consulta el comando 'rhc app tail'

/tmp/             # $OPENSHIFT_TMP_DIR - Carpeta temporal, aquí tenemos permiso de lectura y escritura

Estas son básicamente las carpetas que más nos interesan.

Basta de discursos, queremos ver el código

Para este artículo tomaremos una versión simplificada del quickstart para desplegar aplicaciones Play 1.x en Openshift. Agregamos links a los scripts originales para que pueda consultarlos.

Antes que nada tendremos que desarrollar el script .openshift/action_hooks/pre_build, que será el encargado de verificar que el framework se encuentre instalado. De no ser así, deberá descargarlo de la web y descomprimirlo.

El script podría ser algo tan simple como esto:

.openshift/action_hooks/pre_build (script en github)

if ! [[ -d ${OPENSHIFT_DATA_DIR}play-1.2.4 ]]; then

Luego, para iniciar la aplicación:

.openshift/action_hooks/start (script en github)



#le indicamos a Play que guarde los archivos de auditoria en el directorio OPENSHIFT_LOG_DIR

#ejecutamos la aplicación con el id openshift
${OPENSHIFT_DATA_DIR}play-1.2.4/play start --%openshift

No olvide configurar el su aplicación para que el servidor http escuche en el puerto ${OPENSHIFT_INTERNAL_PORT} de la dirección ${OPENSHIFT_INTERNAL_IP}

En nuestro caso simplemente deberemos agregar estas líneas al archivo application.conf:


Y ahora solo nos queda el script para detener la aplicación

.openshift/action_hooks/stop (script en github)


if [[ -f “” ]]; then
${OPENSHIFT_DATA_DIR}play-1.2.4/play stop

¡Eso es todo!

Simplemente nos resta guardar los cambios en nuestro repositorio git y hacer un push a openshift:

git add .
git commit -m "nuestra aplicación de Play corriendo en Openshift"
git push

Entonces verá a nuestra criatura en acción, descargando e instalando play 1.2.4 del sitio de Play, y finalmente ejecutando nuestra aplicación. No sea tímido, hágale una visita en :

Recuerde que esta es una versión simplificada del quickstart original, no estamos chequeando errores ni guardando información en el archivo de logs. Para un ejemplo más completo consulte los scripts del quickstart en Openshift.

Play y Openshift, jugando en la nube de Red Hat

Desde sus inicios Openshift se destacó por brindar soporte a una amplísima gama de frameworks y servidores web. Con esta nueva opción, también nos brinda las herramientas necesarias para personalizarlo según nuestras necesidades. Lo único que necesita es familiarizarse con el entorno de Openshift y comenzar a programar unos simples scripts en bash. Me pregunto qué creará la comunidad con este nuevo tipo de aplicación Do-It-Yourself en Openshift.

Por Sebastián Scarano @develsas

Sebastián Scarano es un desarrollador web de Buenos Aires, apasionado por compartir su conocimiento y desarrollar buenos sitios web. Actualmente se desempeña como líder de proyectos en el Ministerio de Trabajo, Empleo y Seguridad Social de la República Argentina. Durante el último año ha estado participando activamente de la comunidad Play. Más recientemente publicó el módulo Openshift para Play, para que todos puedan desplegar fácilmente sus aplicaciones en la nube de Red Hat.

Play!, Openshift y Twitter Bootstrap: Combo para programadores perezosos pero impacientes

Ya que estan, por que no se pegan una vuelta por el sitio de openshift y votan para agregar soporte nativo para Play en Openshift.

Hace rato que descubri en Play un poderosisimo web framework para Java, y tengo la suerte de poder aplicarlo diariamente en mi actual trabajo. Sin entrar en demasiados detalles tenemos todos los beneficios del conocido patron MVC, junto con un poderoso WebApp container y un sistema de templates muy amigable. Pero lo que lo hace mas amigable y poderoso a mi parecer es la comunidad y lo facil que resulta desarrollar e integrar los famosos modulos de Play. El que mas nos ocupa hoy es el de Openshift cuyo autor es Sebastian Scarano akka @opensas (el que “mas” lo digo porque el desarrollo incluye dos mas que son nativos: CRUD y Secure)

Disclaimer: Como entiendo que mi post es acotado y especifico quizas cometa el error de dar por sentado un monton de cosas, pero si necesitan que me extienda en algun punto por favor haganmelo saber.

Instalacion y armado del entorno

Deben contar con Git y !Play instalado. Si todavia no lo hicieron, vayan a al sitio de !Play. Y tambien

(sudo) apt-get install git-core

Tambien van a necesitar el cliente de Openshift. Para ello

(sudo) gem install rhc


(sudo) gem install test-unit

A continuacion en su directorio de trabajo ejecutan

(sudo) play install openshift

Con esto ya tenemos el modulo de Openshift instalado en nuestro stack de !Play. A continuacion creamos nuestra aplicacion de la siguiente manera:

play new myApp --with openshift

Acto seguido haran vuestra magia con la aplicacion, corriendola en modo local y versionadolo debidamente ;-). Pero atentos que deben trabajar con Git puntualmente ya que OpenShift les creara un repo propio a donde el modulo hara el deployment.

Aca viene lo interesante: con vuestra cuenta debidamente creada en OpenShift deben agregar estas entradas en el archivo application.conf de la aplicacion en cuestion:

openshift.rhlogin = myuserOpenShift
openshift.password = myPassOplenshift = myApp@Openshift

Acto seguido vamos a instalar/desplegar por primera vez nuestra aplicacion:

play rhc:deploy -o

Cuando este comando se procese y al no existir aun la aplicacion en la nube nos preguntara si queremos crearla y si ademas queremos tener un repo en Openshift. A todo le responderemos que SI, ya que por mas que parezca en ese sentido no existe un libre albeldrio. Lo siento ;).

Hasta aqui todo muy bonito pero nuestra aplicacion es standalone y no tiene persistencia de ningun tipo. Entonces con estos comandos :

rhc-ctl-app -a myApp -e add-mysql-5.1 --rhlogin Myuser -p mypass
rhc-ctl-app -a myApp -e add-myphpadmin-3.4 --rhlogin Myuser -p mypass

y con el output de esos comandos se generan estas nuevas entradas en el application.conf


Ya tenemos mysql en nuestro box al cual podemos administrar con phpmyadmin.

Pero la cereza del postre seria que pudieramos cambiar ese feo dominio por algo mas chevere. Para eso agregan un cname tipo host en donde tengan registrado su dominio (en es caso lo hice con GoDaddy), declarando la ip de la url anterior (con un ping ya lo tienen) y desde sus maquinas corran el siguiente comando:

rhc-ctl-app -a myApp -e add-alias --rhlogin Myuser -p mypass

y voila!!! Esto agrega el dominio en vuestra aplicacion. Dicho sea de paso pueden agregar mas de un dominio a una sola aplicacion.

Ok, hasta aqui llego hoy. Para no aturdilos mucho, en la proxima entrega les explico en forma muuuuy sencilla como agregue a esta misma aplicacion el Css Framework de twitter: Bootstrap.

La aplicacion la pueden ver en progreso en Blog’s @DiegoRam

Las mas grande agradecimiento para Sebastian Scarano (@opensas) y Luis Farzati (@luisfarzati) que me dieron una mano terrible en el proceso.

Saludos y comenten.

Iba a hacer una version con acentos, pero que mierda!! el codigo no lleva acentos y, como ya dije en el título de este artículo, soy muy perezoso 😉

Play framework on the cloud made easy: Openshift module

Consider voting for Play framework native support on Openshift.

Just a couple of years ago finding an afordable hosting solution for a java web application was a hard task, and looking for a free one was an impossible mission. Not to mention that even thinking about things like auto-scaling, one-command deploy, continuos integration, and that sort of stuff was plain science fiction.

This last year has witnessed a cloud revolution, and nowdays there’s a really appalling amount of alternatives to choose from. It seemed like every medium-to-large size IT player had to come out with their own Platform as a Service (PaaS) cloud offering.

In this scenario, an offering from Red Hat couldn’t go unnoticed. Red Hat engineers really know a lot about managing servers, and, lucklily for us, they also know a lot about java web applications. Fortunately, they took the challenge, and what they have to offer would certainly not disappoint us.

openshift homepage

Isn't that panda bear cute?

So, here comes Openshift. Openshift is Red Hat’s free, auto-scaling, cloud-based platform-as-a-service for Java, Perl, PHP, Python, and Ruby applications. It’s a quickly evolving platform, that managed to shape a vibrant and helpful community supporting it. Moreover, it’s free offering largely surpases anything that the competence has to offer. Just by entering your email and choosing a password, you get five applicacions namespaces, each of them with a git repository and half GB of data (code + database) to use as you like it. Add to that support for mysql (with phpmyadmin), PostgreSQL, MongoDB 2.0 (with MongoRock) and even a fully functional Jenkins instance to have a continuous integration environment.

Deploying a java web application to openshift is really easy, just git add, git commit, git push… and that’s it. But we, play developers, spoiled by our beloved framework as we are, would rather just type something like play rhc:deploy and forget about it.

That’s what openshift module for play framework is about.

The short story

So you have everything set up to deploy a play framework application to openshift. That means you have installed JDK 1.6 or 1.5, play framework, ruby, ruby gems, openshift client tools, and that you have signed up at openshift and also created a domain.

In that case, you just have to:

$ play install openshift

and then

$ play new <my app> --with openshift
$ cd <my app>
$ play rhc:deploy -o

… and that’s it.

Your application is ready... and running on Openshift!

Every time you want to deploy your changes to openshift, just issue once again play rhc:deploy -o. The -o parameters just tells the module to open your application on a web browser right after deployment.

From zero to the cloud

Just as a reminder to myself, here are the steps required to go from a bare linux installation to deployment on openfhit:

1. Install Java jdk 1.6

on debian based linux distributions (like ubuntu, mint and others)

$ sudo apt-get install openjdk-6-jdk

on rmp based linux distributions (like fedora, red hat, centos, and others)

$ sudo yum install java-1.6.0-openjdk-devel.i686

2. Install play framework

Here’s my quick and dirty list of commands to install play framework.

$ cd ~
$ mkdir dev
$ cd dev
$ wget
$ unzip 

$ echo "export PATH=$PATH:~/dev/play-1.2.4" >> ~/.profile

$ source ~/.profile

And then test it with:

$ play version
~        _            _ 
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/   
~ play! 1.2.4,

Note: If you are running on fedora, you might need to issue sudo yum remove sox, because the sox package comes with it’s own play command that conflicts with play framework.

3. Sign up for openshift

Go to enter your email and choose a password.

4. Install, git and ruby gems

On a Debian based linux distro:

$ sudo apt-get install git ruby rubygems

Rpm version:

$ sudo yum install git ruby rubygems

5. Install openshift client tools

Once you have installed ruby gems, installing red hat cloud tools is as easy as:

$ sudo gem install rhc

6. Create a domain

Your domain namespace is used to help identify your applications and as part of the URLs to your applications. It’s unique to you across all of openshift. For example, let’s say you have the namespace awesome, when you create a new app called wicked, you’ll find it at When you create a new app called freakin, it’ll be at

So go to your openshift control panel at and click on edit on the NAMESPACE section. Then enter something like playdemo (well, that one is already taken) and click save.

7. Create and register your SSH keys

Now you’ll have to a SSH key, which in fact means creating a private and a public key, so that openshift can validate that it’s really you the one trying to push something to the remote git repository. Just follow the steps at, you just have to open a terminal and then

$ cd ~/.ssh

If you get a No such file or directory error, don’t worry, it means that you didn’t have any SSH key on your system. On the other hand, if you already have a SSH key, it would be a good idea to make a backup.

$ ssh-keygen -t rsa -C "<my email>"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/sas/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /home/sas/.ssh/id_rsa.
Your public key has been saved in /home/sas/.ssh/
The key fingerprint is:
22:7b:cd:f3:98:4f:92:de:80:1d:ad:d6:ea:73:20:c2 <my email>
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
|                 |
|         .       |
|   .. . S .      |
|    Eo.*.=       |
|    ..o.@.o      |
|     . o.@.      |
|       .*++      |

And then, you can setup your username and email, like this:

$ git config --global "<my name>"
$ git config --global "<my email>"

Now you have to register this key at openshift. Just copy the content of the (be careful not to copy the file id_rsa, it’s your private key, and you should keep that to yourself) and add it as a new SSH KEY from your control panel.

On Fedora is pretty annoying having to enter your passphrase on every git operation. To avoid it, just run ssh-add and enter your passphrase for the last time.

Alternatively, you can also use the following command

$ rhc-create-domain -l <your email> -p <your password> -n <pick a domain>

and let openshift create a a pair of private and public keys as libra_id_rsa and at your .ssh/ directory. I had a couple of conflicts between my own SSH keys and the libra ones created by openshift, so I prefer to handle the ssh keys myself.

Note: You won’t be able to push anything to your git repository unless you have a valid public key registered at openshift. Take into account that you can add as many keys as needed.

Go to your control panel at to check that everything is right.

Going to the cloud

And now yes, we are ready to deploy our play framework application to the cloud.

$ play install openshift
$ play new <my app> --with openshift
$ cd <my app>

Now, for every command you’ll have to enter, at least, your username and password. You can spare yourself this trouble by adding the following keys to your conf/application.conf file:

# Openshift module configuration
openshift.rhlogin=<my login>
openshift.password=<my password>

After that you should check that you have installed all the prerequisites. Just run:

$ play rhc:chk

It will check for a java 1.6 or 1.5 install, git, ruby, rubygem, and openshift client tools 0.84.15 or higher. It will also check that the application exists on openshift, otherwise it will ask you to create it, and finally it will check that you have a local git repository pointing at the remote repository at openshift.

Then you can deploy your app with:

$ play rhc:deploy -o

The first time it will take quite some time to issue the deploy, because the module has to upload all of the play framework libraries. After that initial deploy, subsequent commits will be much faster, because git is smart enough to send only the changed files. Moreover, the module will ask your permission to create the app on openshift, and also to create a local repo. If you just want the script to create everything withour asking for permission, just add a --bypass or -b parameter to the command.

Your application will now be available at: http://<my app>-<my domain>

If you have already deployed your application to openshift, and you just want to retrieve it from your remote git repository, just issue:

$ play rhc:fetch

Take into account that this is a destructive operation. It will completely remove your local application and replace it with the contents of your remote repository.

To have a look at your server logs, issue:

$ play rhc:logs
Openshift log files

Having a look at openshift log files with "play rhc:logs"

To display information about your applications on openshift run:

$ play rhc:info

Which is just a short-hand for the rhc-domain-info command.

You can open your application at openshift anytime issuing:

$ play rhc:open

Which is also a short-hand for opening a web browser at http://<my app>-<my domain>

Finally, if you think you want to remove your application from openshift, just run:

$ play rhc:destroy

Installing the openshift module

There are two ways to install openshift module. One is just to issue play install openshift, which will install the module directly with your framework, at <play install folder>/modules/openshift-0.1.1. That way it will be available to every app you create with

$ play new my-app --with openshift

The other way is to manually configure it as a dependency. Just add the following line to your conf/dependencies.yml file:

# Application dependencies
    - play
    - play -> openshift 0.1.1

And then issue

play deps

Note: play keeps a cache of fetched dependencies at ~/.ivy2/cache. If you are having troubles with dependencies just clean that directory and try again.

Along with the module there’s a sample application at <openshift module folder>/samples_and_tests/openshift-demo. Just go to that folder and issue play deps and then play run to see it running locally. It just displays play configuration and the host environment variables to let you check that your app is running on openshift.

Openshift module demo application

Openshift module demo application

Then run play rhc:chk to verify that you have installed all the prerequisites. After that issue play rhc:deploy -o to create your remote application at openshift, create a local git repo, package your app as a war file, commit your new app, and deploy to openshift. Thanks to the -o parameter the module will open your openshift app in a web browser after deployment.

Getting help

You can have a look at the module’s commands issuing:

$ play help
~        _            _ 
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/   
~ play! 1.2.4,

~ Modules commands:
~ ~~~~~~~~~~~~~~~~~
~ rhc:chk             Check openshift prerequisites, application and git repo.
~ rhc:deploy          Deploys application on openshift.
~ rhc:destroy         Destroys application on openshift.
~ rhc:fetch           Fetches application from remote openshift repository.
~ rhc:info            Displays information about user and configured applications.
~ rhc:logs            Show the logs of the application on openshift.
~ rhc:open            Opens the application deployed on openshift in web browser.
~ Also refer to documentation at

Then you can get more help about parameters with the -h or --help parameter:

$ play rhc:chk -h
~        _            _ 
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/   
~ play! 1.2.4,
Usage: play [options]

  -h, --help            show this help message and exit
  -a APP, --app=APP     Application name  (alphanumeric) (required)
  -s SUBDOMAIN, --subdomain=SUBDOMAIN
                        Application subdomain, root by default  (alphanumeric)
  -l RHLOGIN, --rhlogin=RHLOGIN
                        Red Hat login (RHN or OpenShift login with OpenShift
                        Express access)
  -p PASSWORD, --password=PASSWORD
                        RHLogin password  (optional, will prompt)
  -d, --debug           Print Debug info
  -m MESSAGE, --message=MESSAGE
                        Commit message
  --timeout=TIMEOUT     Timeout, in seconds, for connection
  -o, --open            Open site after deploying
  -b, --bypass          Bypass warnings

You can also specify these options in the conf/application.conf file with the following keys:

openshift.rhlogin: Red Hat login (RHN or OpenShift login with OpenShift Express access)
openshift.password: RHLogin password  (optional, will prompt) Application name  (alphanumeric) (required)
openshift.application.subdomain: Application subdomain, root by default  (alphanumeric)
openshift.debug: Print Debug info
openshift.timeout: Timeout, in seconds, for connection

You can see all versions of the module at the openshift module’s page on

You can check the documentation at, or running locally your app in dev mode with play run, and then going to http://localhost:9000/@documentation/modules/openshift/home.

Local documentation

Browsing module documentation locally

You can ask questions at the play framework discussion list at, or you can try with it’s spanish cousin at

Known issues

Unfortunately, right now the openshift module doesn’t work with windows. That’s because the module issues many git commands, and you can’t do that on windows from the standard shell, it requires a special “git bash” prompt.

Further steps

In the next version I’ll be exploring the possibility of building a java only version of the module using openshift’s java api. That way we won’t be needing git, ruby, nor the rhc tools installation. Morevoer, we should be able to use it all from windows as well.


Play framework openshift module page:

Latest version:

Project at github:

Detailed tutorial about how to deploy a Play Framework application to openshift:—deploy-to-openshift

Excellent tutorial about deploying java applications to openshift:

A couple of articles on jboss planet:

Divide and conquer: Play framework modules

It’s usually the case that you start developing an application and go on fulfilling requirements. When your application grows bigger you start to realize the convenience of separating it into different components. Moreover, when you develop your second or third application, your begin to recognize certain features that could be reused across different applications.

These are two good reasons to modularize an application. Ideally we should aim at components with high cohesion and low coupling.

The Java language has proven itself quite fit to accomplish this kind of tasks. It provides general means to enforce the use of well defined API thru interfaces, abstract classes, etc.

Play framework developers think that this is perfectly fine for developing a general purpose library, but in the case of a web application reusability and modularization could be best achieved by other means. Have a look at this excerpt taken from play framework’s FAQ:

Java itself is a very generic programming language and not originally designed for web application development. It is a very different thing to write a generic and reusable Java library and to create a web application. A web application itself doesn’t need to be designed to be reusable. You need less abstraction, less configuration. Reusability does exist for web applications, but through web service APIs rather than language-level integration.

So when it comes to reusability, play provides us with a solution better suited for web applications.

Play modules

A module is just another Play framework application. The only difference is that a module is not meant to be run on his own, it needs to be included into a containing application.

Nevertheless, there area a couple of differences between a module and a regular application, mainly that a module has no conf file (it has to be provided by the main application) and everything in a module is optional.

Doing is better than saying, so as usual we will look for a fine opportunity to make a simple module to show how it works.

Creating a new play framework application and deploying it to the cloud

As many of you already know, we are working on the spanish translation of play framework site. We wanted to add web analytics to it so that we can see how people were using it.

So in order to follow this example, we’ll need a play framework app deployed somewhere on the Internet. Nowadays there are lots of Java hosting options available for free. Here you have a couple of tutorials for deploying on openshift, google application engine and heroku.

First let’s create a play framework application, I’ll create the app at ~/devel/apps/module-test, you can choose whatever location you like, just be sure to update the commands appropriately.

To create the app, run the following command at an os prompt:

sas@ubuntu:~/devel/apps/module-test$ play new analytics-app
~        _            _
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/
~ play! 1.2.4,
~ The new application will be created in /home/sas/Dropbox/Public/devel/play/apps/module-test/analytics-app
~ What is the application name? [analytics-app]
~ OK, the application is created.
~ Start it with : play run analytics-app
~ Have fun!

Now it would be a good time to deploy it somewhere. For this tutorial we will deploy it at openshift, you can use any host you want (For more information on setting up your environment for openshift deployment follow this tutorial)

Consider voting for Play framework native support on Openshift.

Create a new directory at ~/devel/apps/module-test/openshift, go to that directory and run:

rhc-create-app -l -p mypassword -t jbossas-7.0 -a analyticsapp

Attempting to create remote application space: analyticsapp
Now your new domain name is being propagated worldwide (this might take a minute)...
Pulling new repo down


Successfully created application: analyticsapp

Next, we’ll get rid of the demo app:

cd ~/devel/apps/module-test/openshift/analyticsapp
rm -fr pom.xml src

And we’ll compile and package the newly created app as an exploded war. Go to ~/devel/apps/module-test folder and run:

cd ~/devel/apps/module-test
play war analytics-app -o openshift/analyticsapp/deployments/ROOT.war
~        _            _
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/
~ play! 1.2.4,
JPDA port 8000 is already used. Will try to use any free port for debugging
Listening for transport dt_socket at address: 53978
00:22:38,021 INFO  ~ Starting /home/sas/Dropbox/Public/devel/play/apps/module-test/analytics-app
00:22:39,891 INFO  ~ Precompiling ...
00:22:49,075 INFO  ~ Done.
~ Packaging current version of the framework and the application to /home/sas/Dropbox/Public/devel/play/apps/module-test/openshift/analyticsapp/deployments/ROOT.war ...
~ Done !
~ You can now load /home/sas/Dropbox/Public/devel/play/apps/module-test/openshift/analyticsapp/deployments/ROOT.war as a standard WAR into your servlet container
~ You can't use play standard commands to run/stop/debug the WAR application...
~ ... just use your servlet container commands instead
~ Have fun!

Now we just need to commit the application and push it to our git repo on openshift:

cd ~/devel/apps/module-test/openshift/analyticsapp
touch deployments/ROOT.war.dodeploy
git add -A
git commit -m "deploy play framework app"
git push origin

Note: The first time it will take a couple of minutes to push the application, because of play framework libraries. Later pushes will be much quicker, git is smart enough to only send updated files.

And that’s it, you’ve just deployed your first app to red hat’s cloud. You can see it running at (of course, you’ll have to replace “opensas” with your own openshift user name).

Google web analytics & play framework

Adding Google web analytics to a play app is really easy. You just need a gmail account, then go to Google Analytics web site, click on “sign up”, login with your gmail account, and complete all the required data.

In the account name enter “analytics-app”, in the website’s url enter, agree to the terms and conditions and click on “Create account”.

You’ll be taken to your analytics-app account page, there you can see the tracking code. You’ll just have to paste it in your app. So open the file at ~/devel/apps/module-test/analytics-app/app/views/main.html and paste the tracking code before the closing head tag, like this:

<script charset="${_response_encoding}" type="text/javascript" src="@{'/public/javascripts/jquery-1.6.4.min.js'}"></script>#{get 'moreScripts' /}<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

Note: Google will provide you with your own UA-XXXXXXXX-1 account code, so just copy and paste the code from your Google analytics account page, and NOT from this page!

Now you just have to generate the war folder, commit, and push it once again to openshift to deploy your changes. Every time you make a change you’ll have to follow these same steps to deploy it to openshift.

cd ~/devel/apps/module-test
play war analytics-app/ -o openshift/analyticsapp/deployments/ROOT.war
cd openshift/analyticsapp/
git add -A
git commit -m "added tracking code"
git push origin

Visit again your page at, and see the source of the page to check that the tracking code has been added. You can also see it in action on Google’s analytics page, click on “Home”, Real-Time (BETA), and the Overview. You should have one visitor (yes, it’s you!).

So far now we created a new play application and deployed it to openshift. Then we created a Google analytic account and added the tracking code the our play application. Everything is working ok and our app is being tracked by Google. Now we are going to move that functionality to a module so that we can reuse it from other apps.

Creating a module

To create a new module you have to use the “new-module” play command, like this:

cd /home/sas/devel/apps/module-test/
play new-module analytics

Now, in order to tell our main application (in our case analytics-app) to include this module, we have to configure a local repository.

Edit ~/devel/apps/module-test/analytics-app/conf/dependencies.yml like this:

# Application dependencies

    - play
    - analytics -> analytics

    - My local modules:
        type:       local
        artifact:   ${application.path}/../[module]
            - analytics

and after that run the following command to tell play to resolve dependencies.

cd ~/devel/apps/module-test/analytics-app
play dependencies
~        _            _
~  _ __ | | __ _ _  _| |
~ | '_ \| |/ _' | || |_|
~ |  __/|_|\____|\__ (_)
~ |_|            |__/
~ play! 1.2.4,
~ Resolving dependencies using /home/sas/devel/apps/module-test/analytics-app/conf/dependencies.yml,
~ 	analytics->analytics -> (from My local modules)
~ Installing resolved dependencies,
~ 	modules/analytics -> /home/sas/devel/apps/module-test/analytics/../analytics
~ Done!

You can now start the main application on your workstation:

cd ~/devel/apps/module-test/analytics-app
play run

You can see your app running at http://localhost:9000.

Moving the tracking code to a reusable tag

Now we will move the tracking code to a tag defined in the module, so we’ll create a file ~/devel/apps/module-test/analytics/app/views/analytics.html with the tracking code, like this:

<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-XXXXXXXX-1']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

And now, replace the tracking code in main.html with a call to the tag, like this:

<script charset="${_response_encoding}" type="text/javascript" src="@{'/public/javascripts/jquery-1.6.4.min.js'}"></script>
        #{get 'moreScripts' /}

#{analytics /}



Getting module configuration from the application.conf file

Our module is almost ready, there’s just one thing that’s preventing us from really reusing it on another application: the Google analytics code is hardcoded in our tag! So we will read it from the application.conf file. Just edit the analytics.html tag like this:

    String code = play.Play.configuration.getProperty("analytics.code", "")
#{if code!=""}<script type="text/javascript">
  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', '${code}}']);
  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);

and add the following to your main application configuration file at ~/devel/apps/module-test/analytics-app/conf/application.conf


Prevent tracking in dev mode

This tag will will update the tracker every time the page is rendered, even when we are working on our development workstation!

So we will add a minor improvement to prevent the module from logging the page activity while working in development mode.

Just add the following condition to the code:

    String code = play.Play.configuration.getProperty("analytics.code", "")
#{if play.mode.isProd() && code!=""}
<script type="text/javascript">

  var _gaq = _gaq || [];

Troubleshooting Openshift

Openshift won’t be able to resolve the relative reference to the module location (and in fact any war deployed application will have the same problem), so you’ll have to tell play to copy the module sources to the containing application before generating the war folder. Just issue:

cd ~/devel/apps/module-test/analytics-app
play dependencies --forceCopy

And that’s it, now you can deploy to openshift in the usual way:

cd ~/devel/apps/module-test
play war analytics-app/ -o openshift/analyticsapp/deployments/ROOT.war
cd openshift/analyticsapp/
git add -A
git commit -m "added analytics module"
git push origin

Run your site locally with “play run”, and also open it from (go on, give it a try, every click counts), check the source code of both sites, you should see that the app running at openshift contains the tracking code, contrary to your local application.


In this post we saw how to deploy a play framework app to openshift and, more important, how to move features from your application to a module in order to reuse it from other applications.

In the meantime, I’ve also added google analytics support to Play! framework spanish translation site. Here you can see it in action:

Google analytics realtime in action
Tracking visits from Colombia, Argentina, Perú, El Salvador
Venezuela, Costa Rica, Ecuador, México, Spain… in realtime

You can learn more about modules on this article or reading play’s documentation.

If you speak spanish you can help us with the translation, and you can also have a look at our work right here… You can be sure every click you make will be tracked!

%d bloggers like this: