-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcopy_env.rb
More file actions
70 lines (59 loc) · 1.72 KB
/
copy_env.rb
File metadata and controls
70 lines (59 loc) · 1.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
require 'json'
# Usage examples:
# Copy from an EB environment to another EB environment:
# copy_env({name: "abc-eb-app", source: :eb, profile: "def"}, {name: "def-eb-app", source: :eb, profile: "def"})
#
# Copy from a Heroku app to an EB environment:
# copy_env({name: "your-heroku-app", source: :heroku}, {name: "def-eb-app", source: :eb, profile: "def"})
def copy_env(from, to)
from_name = from[:name]
from_source = from[:source] || :eb
from_profile = from[:profile]
to_name = to[:name]
to_profile = to[:profile]
env_vars = case from_source
when :heroku
EnvVars.from_heroku(from_name)
else
EnvVars.from_eb(from_name, from_profile)
end
env_vars.set_eb_env!(to_name, to_profile)
end
class EnvVars
def initialize(vars)
@vars = vars.map { |k, v| EnvVar.new(k, v) }
end
def self.from_eb(env_name, profile = nil)
cmd = "eb printenv #{env_name}"
cmd += " --profile #{profile}" if profile
env_lines = `#{cmd}`.split("\n").select { |v| v =~ / = / }
vars = env_lines.map { |v| v.strip.split(" = ") }
EnvVars.new(vars)
end
def self.from_heroku(app)
json_str = `heroku config -j --app #{app}`
config = JSON.parse(json_str)
vars = config.to_a
EnvVars.new(vars)
end
def set_eb_env(env_name, profile = nil)
vars = @vars.map { |v| "\"#{v}\"" }
cmd = "eb setenv #{vars.join(" ")} -e #{env_name}"
cmd += " --profile #{profile}" if profile
cmd
end
def set_eb_env!(env_name, profile = nil)
cmd = set_eb_env(env_name, profile)
puts cmd
`#{cmd}`
end
end
class EnvVar
def initialize(name, value)
@name = name
@value = value
end
def to_s
"#{@name}=#{@value}"
end
end