Forem

Bradford Fults
Bradford Fults Subscriber

Posted on

Copy Config Vars from One Heroku App to Another

Below is a quick little script I threw together to copy config vars from one Heroku app to another, e.g. when trying to create a staging or test app that [largely] mirrors another.

It relies on a Heroku app.json to specify which config vars are required, combined with a dump of your other app’s config vars via heroku config --shell -a <app-name> >foo.env to get the <env-file> input.

#!/usr/bin/env ruby
# frozen_string_literal: true

require 'json'

# Usage: env-setter <app.json> <env-file> [-a <heroku-app-name>]

app_json_file   = ARGV[0]
env_file        = ARGV[1]
env_var_keys    = []
heroku_app_name = nil

# parse command line -a switch to get Heroku app name
if ARGV.include?('-a')
  heroku_app_name = ARGV[ARGV.index('-a') + 1]
end

# Pull required config vars from app.json
begin
  parsed_json = JSON.parse(File.read(app_json_file))
  env_var_keys = parsed_json['env'].map {|k,v| k if v.is_a?(Hash) && v['required'] }.compact
rescue JSON::ParserError, EOFError
  puts "Error parsing JSON file: #{app_json_file}"
  exit 1
end
# puts "Required config vars from app.json: #{env_var_keys.join(', ')}"

# Pull env vars from env file
begin
  env_vars = Hash[*File.readlines(env_file).map(&:chomp).map { |line| line.split('=', 2) }.flatten]
rescue EOFError
  puts "Error reading env file: #{env_file}"
  exit 1
end
# puts "Loaded env var names from #{env_file}: #{env_vars.keys.join(', ')}"

# Check if any required env vars are missing
missing_vars = env_var_keys - env_vars.keys
if missing_vars.any?
  puts "Missing required env vars from #{env_file}: #{missing_vars.join(', ')}"
  exit 1
end

# Set config vars on Heroku if app name provided
if heroku_app_name
  puts "Setting config vars on Heroku app #{heroku_app_name}..."
  system('heroku', 'config:set', '--app', heroku_app_name, *env_vars.map {|k,v| "#{k}=#{v}" }.flatten)
end
Enter fullscreen mode Exit fullscreen mode

Image of Datadog

How to Diagram Your Cloud Architecture

Cloud architecture diagrams provide critical visibility into the resources in your environment and how they’re connected. In our latest eBook, AWS Solution Architects Jason Mimick and James Wenzel walk through best practices on how to build effective and professional diagrams.

Download the Free eBook

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more