Take the 2-minute tour ×

I have a flask app hosted on Heroku that needs to run commands on an AWS EC2 instance (Amazon Linux AMI) using boto.cmdshell. A couple of questions:

  1. Is using a key pair to access the EC2 instance the best practice? Or is using username/password better?
  2. If using a key pair is the preferred method, what's the best practice on managing/storing private keys on Heroku? Obviously putting the private key in git is not an option.


share|improve this question
add comment

3 Answers

Heroku lets you take advantage of config variables to manage your application. Here is an exmaple of my config.py file that lives inside my flask application:

import os

# flask
PORT = int(os.getenv("PORT", 5000))
basedir = str(os.path.abspath(os.path.dirname(__file__)))
SECRET_KEY = str(os.getenv("APP_SECRET_KEY"))
DEBUG = str(os.getenv("DEBUG"))
TESTING = os.getenv("TESTING", False)

# s3
S3_BUCKET = str(os.getenv("S3_BUCKET"))

Now i can have two different sets of results. It pulls from my Environment variables. One when my application is on my local computer and from Heroku config variables when in production. For example.

 DEBUG = str(os.getenv("DEBUG")) 

is "TRUE" on my local computer. But False on Heroku. In order to check your Heroku config run.

Heroku config

Also keep in mind that if you ever want to keep some files part of your project locally but not in heroku or on github you can use git ignore. Of course those files won't exist on your production application then.

share|improve this answer
add comment

You can use config vars to store config items in an application running on Heroku.

You can use a username/password combination. You may make the username something easy; but be sure to generate a strong password, e.g., with something like openssl rand -base64 32.

share|improve this answer
add comment
up vote 2 down vote accepted

What I was looking for was guidance on how to deal with private keys. Both @DrewV and @yfeldblum pointed me to the right direction. I ended up turning my private key into a string and storing it in a Heroku config variables.

If anyone is looking to do something similar, here's a sample code snippit using paramiko:

import paramiko, base64
import StringIO
import os

key = paramiko.RSAKey.from_private_key(StringIO.StringIO(str(os.environ.get("AWS_PRIVATE_KEY"))))
ssh = paramiko.SSHClient()
ssh.connect(str(os.environ.get("EC2_PUBLIC_DNS")), username='ec2-user', pkey=key)
stdin, stdout, stderr = ssh.exec_command('ps')

for line in stdout:
    print '... ' + line.strip('\n')

Thanks to @DrewV and @yfeldblum for helping (upvote for both).

share|improve this answer
add comment

Your Answer


