Openshift动作钩子无法访问环境变量

时间:2015-02-21 21:49:36

标签: database jenkins openshift

对于我在Openshift上的应用程序,我正在尝试编写一个访问数据库的pre_build脚本。目标是在部署代码时执行的数据库版本之间具有迁移脚本。该脚本会将当前数据库版本与应用程序代码所需的版本进行比较,然后运行正确的脚本来迁移数据库。

现在的问题是,显然pre_build脚本是在Jenkins上执行而不是在目标盒上执行,因此带有数据库连接参数的环境变量不可用。

这是我到目前为止编写的pre_build脚本:

#!/usr/bin/env python

print "*** Database migration script ***"

# get goal version
import os

homedir = os.environ["OPENSHIFT_HOMEDIR"]
migration_scripts_dir = homedir + "app-root/runtime/repo/.openshift/action_hooks/migration-scripts/"
f = open(migration_scripts_dir + "db-version.txt")
goal = int(f.read())
f.close()

print "I need database version " + str(goal)

# get database connection details
# TODO: find a solution of not hard coding the connection details here!!!
# Maybe by using jenkins environment variables like OPENSHIFT_APP_NAME and JOB_NAME

db_host = "..."
db_port = "..."
db_user = "..."
db_password = "..."
db_name = "..."

import psycopg2

try:
    conn = psycopg2.connect("dbname='" + db_name + "' user='" + db_user + "' host='" + db_host + "' password='" + db_password + "' port='" + db_port + "'")
    print "Successfully connected to the database"
except:
    print "I am unable to connect to the database"

cur = conn.cursor()


def get_current_version(cur):
    try:
        cur.execute("""SELECT * from db_version""")
    except:
        conn.set_isolation_level(0)
        cur.execute("""CREATE TABLE db_version (db_version bigint NOT NULL)""")
        cur.execute("""INSERT INTO db_version VALUES (0)""")
        cur.execute("""SELECT * from db_version""")     

    current_version = cur.fetchone()[0]

    print "The current database version is " + str(current_version)
    return current_version


def recursive_execute_migration(cursor):
    current_version = get_current_version(cursor)
    if (current_version == goal):
        print "Database is on the correct version"
        return
    elif (current_version < goal):
        sql_filename = "upgrade" + str(current_version) + "-" + str(current_version + 1) + ".sql"
        print "Upgrading database with " + sql_filename
        cursor.execute(open(migration_scripts_dir + sql_filename, "r").read())
        recursive_execute_migration(cursor)
    else:
        sql_filename = "downgrade" + str(current_version) + "-" + str(current_version - 1) + ".sql"
        print "Downgrading database with " + sql_filename
        cursor.execute(open(migration_scripts_dir + sql_filename, "r").read())
        recursive_execute_migration(cursor)     


conn.set_isolation_level(0)
recursive_execute_migration(cur)

cur.close()
conn.close()

是否有另一种自动数据库迁移方式?

感谢您的帮助。

0 个答案:

没有答案