Class: CfnDSLHelper::Cli

Inherits:
Object
  • Object
show all
Defined in:
lib/cfndslhelper/cli.rb

Instance Method Summary collapse

Constructor Details

#initialize(argv, stdin = STDIN, stdout = STDOUT, stderr = STDERR, kernel = Kernel) ⇒ Cli

Returns a new instance of Cli.



10
11
12
# File 'lib/cfndslhelper/cli.rb', line 10

def initialize(argv, stdin=STDIN, stdout=STDOUT, stderr=STDERR, kernel=Kernel)
  @argv, @stdin, @stdout, @stderr, @kernel = argv, stdin, stdout, stderr, kernel
end

Instance Method Details

#createObject



181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
# File 'lib/cfndslhelper/cli.rb', line 181

def create
  puts @config['region']
  cfn = Aws::CloudFormation::Client.new(region: @config['region'])

  parameters = get_parameters_to_array
  puts parameters

  stack = {
    stack_name: @config[:stack_name],
    template_url: template_url,
    parameters: parameters,
    notification_arns: @config['notification_arns'],
    capabilities: ['CAPABILITY_IAM', 'CAPABILITY_NAMED_IAM'],
    tags: []
  }

  if @config[:set_stack_as_name_tag]
    stack[:tags] << { key: 'Name', value: @config[:stack_name]}
  end

  puts stack

  resp = cfn.create_stack(stack)

  puts resp

  stack_wait :stack_create_complete, {stack_name: @config[:stack_name] }
end

#deleteObject



210
211
212
213
214
215
216
# File 'lib/cfndslhelper/cli.rb', line 210

def delete
  cfn = Aws::CloudFormation::Client.new(region: @config['region'])
  resp = cfn.delete_stack({stack_name: @config[:stack_name]})
  puts resp

  stack_wait :stack_delete_complete, {stack_name: @config[:stack_name] }
end

#execute!Object



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
# File 'lib/cfndslhelper/cli.rb', line 14

def execute!
  instruction = @argv.first
  puts "#CfnDSLHelperVERSION:#{CfnDSLHelper::VERSION}"
  get_config unless instruction == 'parameter-update'

  if instruction == 'generate'
    generate
  end

  if instruction == 'validate'
    validate
  end

  if instruction == 'upload'
    upload
  end

  if instruction == 'create'
    create
  end

  if instruction == 'delete'
    delete
  end

  if instruction == 'update'
    update
  end

  if instruction == 'show-events'
    show_events
  end

  if instruction == 'parameter-update'
    parameter_only_update
  end
end

#generateObject



122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
# File 'lib/cfndslhelper/cli.rb', line 122

def generate
  FileUtils.rm_rf Dir.glob("#{@base_dir}/output/**/*.json")
  FileUtils.rm_rf Dir.glob("#{@base_dir}/output/**/*.yml")

  if File.directory? "#{@base_dir}/raw-imports"
    FileUtils.cp_r Dir.glob("#{@base_dir}/raw-imports/**/*.json"), "#{@base_dir}/output/"
    FileUtils.cp_r Dir.glob("#{@base_dir}/raw-imports/**/*.yml"),  "#{@base_dir}/output/"
  end

  @cfn_templates.each do |cfn_template|
    puts cfn_template
    filename = cfn_template
    template = cfn_template.gsub(/.*\//, '')
    output = template.gsub(/.rb$/,'.json')
    puts '#BEGIN MODEL GENERATE'
    model = CfnDsl.eval_file_with_extras(filename, @extras, verbose)

    File.open("#{@base_dir}/output/#{output}", "w") do | f |
      f.write(JSON.pretty_generate(model))
    end
  end
end

#get_configObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
# File 'lib/cfndslhelper/cli.rb', line 52

def get_config
  @base_dir = ENV['CFN_BASE_DIR'] || Dir.pwd

  puts @base_dir

  @config = {}

  @extras = []

  config_location = ENV['CFN_CONFIG_LOCATION'] || "#{@base_dir}/config/project_config.yml"

  notifications_location = ENV['CFN_NOTIFICATIONS_LOCATION'] || "#{@base_dir}/config/notifications.yml"

  @config = YAML.load_file(config_location)

  if File.file? notifications_location
    @config.merge!(YAML.load_file(notifications_location))
  end

  parse_args

  if ENV['CFN_VERSION']
    @config['version'] = ENV['CFN_VERSION']
    File.write("#{@base_dir}/config/version.yml", "version: \"#{ENV['CFN_VERSION']}\"")
  end

  @config['region'] = @config['region'] || 'ap-southeast-2'

  %w[version pplication_name project].each do | requirement |
    raise "No #{requirement} specified" unless @config[requirement]
  end

  @cfn_templates = Dir["#{@base_dir}/cfndsl/**/*.rb"]

  if File.directory? "#{@base_dir}/cfndsl-imports"
    @cfn_templates += Dir["#{@base_dir}/cfndsl-imports/**/*.rb"]
  end

  Dir["#{@base_dir}/config/*.yml"].each do | extra |
    @extras << [:yaml, extra]
  end

  Dir["#{@base_dir}/config/*.rb"].each do | extra |
    @extras << [:ruby, extra]
  end

  if ENV['STACK_NAME']
    @config['stack_name'] = @config['stack_name'] || ENV['STACK_NAME']
  end

  puts @config
end

#get_config_no_filesObject



105
106
107
108
109
110
111
# File 'lib/cfndslhelper/cli.rb', line 105

def get_config_no_files
  @config = {}
  parse_args
  @config['stack_name'] = @config['stack_name'] || ENV['STACK_NAME']
  @config['region'] = @config['region'] ||  ENV['AWS_DEFAULT_REGION'] || 'ap-southeast-2'
  puts @config
end

#get_parameters_to_arrayObject



171
172
173
174
175
176
177
178
# File 'lib/cfndslhelper/cli.rb', line 171

def get_parameters_to_array
  parameters = []
  if @config[:parameters_given]
    @config[:parameters].split(',').each { | p | interim = p.split('='); parameters << { parameter_key: interim[0], parameter_value: interim[1] } }
  end

  parameters
end

#get_update_parameters(stack) ⇒ Object



218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/cfndslhelper/cli.rb', line 218

def get_update_parameters(stack)
  update_parameters = []
  stack.parameters.each { |sp| update_parameters << sp.to_hash }

  override_parameters = get_parameters_to_array
  puts override_parameters

  override_parameters.each do | parameter |
    puts parameter
    if update_parameters.detect { | up | up[:parameter_key] == parameter[:parameter_key] }
      update_parameters.each { | up | up[:parameter_value] = parameter[:parameter_value] if up[:parameter_key] == parameter[:parameter_key] }
    else
      puts "#{parameter} not found in current parameters for stack"
      update_parameters << { parameter_key: parameter[:parameter_key], parameter_value: parameter[:parameter_value] }
    end
  end

  update_parameters.each { |x| p x }
end

#parameter_only_updateObject



238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
# File 'lib/cfndslhelper/cli.rb', line 238

def parameter_only_update
  get_config_no_files
  cfn = Aws::CloudFormation::Client.new(region: @config['region'])

  stack = cfn.describe_stacks({stack_name: @config[:stack_name]}).stacks[0]
  update_parameters = get_update_parameters(stack)

  puts update_parameters

  update_hash = {
    stack_name: @config[:stack_name],
    parameters:  update_parameters,
    notification_arns: @config['notification_arns'],
    use_previous_template: true,
    capabilities: ["CAPABILITY_NAMED_IAM"],
    tags: []
  }

  if @config[:set_stack_as_name_tag]
    update_hash[:tags] << { key: 'Name', value: @config[:stack_name]}
  end

  run_update update_hash
end

#parse_argsObject



113
114
115
116
117
118
119
120
# File 'lib/cfndslhelper/cli.rb', line 113

def parse_args
  options = Trollop::options do
    opt :stack_name, "whats the name of the stack??", type: String, short: "-s"
    opt :parameters, "specify some parameters for create-ing or overriding k=v,k1=v1", type: String, short: "-p"
  end

  @config = options.merge @config
end

#run_update(update_hash) ⇒ Object



287
288
289
290
291
292
293
294
295
296
297
# File 'lib/cfndslhelper/cli.rb', line 287

def run_update(update_hash)
  cfn = Aws::CloudFormation::Client.new(region: @config['region'])
  puts "debug update_hash"
  puts update_hash

  resp = cfn.update_stack(update_hash)
  puts resp

  puts 'wait until complete...'
  stack_wait :stack_update_complete, {stack_name: @config[:stack_name] }
end

#show_eventsObject



311
312
313
314
315
316
317
318
319
320
321
322
323
# File 'lib/cfndslhelper/cli.rb', line 311

def show_events
  cfn = Aws::CloudFormation::Client.new(region: @config['region'])
  resp = cfn.describe_stack_events(stack_name: @config[:stack_name])
  resp.stack_events.reverse_each do | e |
    puts e.stack_id + ";;;" + e.event_id + ";;;" + e.stack_name + ";;;" + e.logical_resource_id #=> String
    puts e.physical_resource_id #=> String
    puts e.resource_type #=> String
    puts e.timestamp #=> Time
    puts e.resource_status #=> String, one of "CREATE_IN_PROGRESS", "CREATE_FAILED", "CREATE_COMPLETE", "DELETE_IN_PROGRESS", "DELETE_FAILED", "DELETE_COMPLETE", "DELETE_SKIPPED", "UPDATE_IN_PROGRESS", "UPDATE_FAILED", "UPDATE_COMPLETE"
    puts e.resource_status_reason #=> String
    puts e.resource_properties #=> String
  end
end

#stack_wait(wait, name) ⇒ Object



325
326
327
328
329
330
331
332
# File 'lib/cfndslhelper/cli.rb', line 325

def stack_wait(wait, name)
  cfn = Aws::CloudFormation::Client.new(region: @config['region'])
  begin
    cfn.wait_until wait, name
  rescue
    raise "error doing #{wait} for #{name}"
  end
end

#template_urlObject



299
300
301
302
303
304
305
# File 'lib/cfndslhelper/cli.rb', line 299

def template_url
  "https://s3-#{@config['source_region']}.amazonaws.com/#{@config['source_bucket']}/cloudformation/#{@config['project']}/#{@config['application_name']}/#{@config['version']}/master.json"
  # FIXME: make template url an actual template itself as per below
  # @config = {:version=>"99", :cloudformation_bucket=>"my_cool_bucket", :project=>"the-project", :application=>"firefly"}
  # url = "http://%{cloudformation_bucket}/cloudformation/%{project}/%{application}/%{version}/"
  # url % @config
end

#updateObject



263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
# File 'lib/cfndslhelper/cli.rb', line 263

def update
  cfn = Aws::CloudFormation::Client.new(region: @config['region'])

  stack = cfn.describe_stacks({stack_name: @config[:stack_name]}).stacks[0]
  update_parameters = get_update_parameters(stack)

  puts update_parameters

  update_hash = {
    stack_name: @config[:stack_name],
    template_url: template_url,
    parameters:  update_parameters,
    notification_arns: @config['notification_arns'],
    capabilities: ["CAPABILITY_NAMED_IAM"],
    tags: []
  }

  if @config[:set_stack_as_name_tag]
    update_hash[:tags] << { key: 'Name', value: @config[:stack_name]}
  end

  run_update update_hash
end

#uploadObject



159
160
161
162
163
164
165
166
167
168
169
# File 'lib/cfndslhelper/cli.rb', line 159

def upload
  s3 = Aws::S3::Resource.new(region: @config['source_region'])
  Dir.glob("#{@base_dir}/output/*.json").each do | template |
    puts "will upload #{template}"
    key = template.gsub(/.*\//, '')
    key = "cloudformation/#{@config['project']}/#{@config['application_name']}/#{@config['version']}/#{key}"
    puts "will upload #{template} to #{key}"
    obj = s3.bucket(@config['source_bucket']).object(key)
    obj.upload_file(template)
  end
end

#validateObject



145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/cfndslhelper/cli.rb', line 145

def validate
  cfn = Aws::CloudFormation::Client.new(region: @config['region'])

  Dir.glob("#{@base_dir}/output/*.json").each do | template |
    puts "will validate #{template}"
    body = File.read(template)

    resp = cfn.validate_template(
      template_body: body
    )
    puts resp
  end
end

#verboseObject



307
308
309
# File 'lib/cfndslhelper/cli.rb', line 307

def verbose
  STDERR
end