ruby-cdk 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +253 -0
  3. data/README.md +28 -5
  4. data/lib/ruby_cdk/assets/hasher.rb +4 -0
  5. data/lib/ruby_cdk/assets.rb +4 -8
  6. data/lib/ruby_cdk/cli/aws.rb +23 -5
  7. data/lib/ruby_cdk/cli/drift.rb +94 -0
  8. data/lib/ruby_cdk/cli/import.rb +306 -0
  9. data/lib/ruby_cdk/cli/lookup.rb +214 -0
  10. data/lib/ruby_cdk/cli/session.rb +114 -3
  11. data/lib/ruby_cdk/cli/watch.rb +297 -0
  12. data/lib/ruby_cdk/cli.rb +76 -1
  13. data/lib/ruby_cdk/constructs/function.rb +24 -3
  14. data/lib/ruby_cdk/constructs/hosted_zone.rb +342 -0
  15. data/lib/ruby_cdk/constructs/record_set.rb +330 -0
  16. data/lib/ruby_cdk/constructs/ssm_parameter.rb +174 -0
  17. data/lib/ruby_cdk/constructs/vpc.rb +822 -0
  18. data/lib/ruby_cdk/constructs/vpc_network.rb +159 -0
  19. data/lib/ruby_cdk/constructs.rb +5 -1
  20. data/lib/ruby_cdk/core/app.rb +28 -2
  21. data/lib/ruby_cdk/core/construct.rb +2 -0
  22. data/lib/ruby_cdk/core/context.rb +138 -0
  23. data/lib/ruby_cdk/core/stack.rb +4 -0
  24. data/lib/ruby_cdk/core.rb +1 -0
  25. data/lib/ruby_cdk/deploy/deployer.rb +283 -8
  26. data/lib/ruby_cdk/deploy/drift.rb +389 -0
  27. data/lib/ruby_cdk/deploy/ec2_adapter.rb +214 -0
  28. data/lib/ruby_cdk/deploy/errors.rb +8 -0
  29. data/lib/ruby_cdk/deploy/fakes.rb +230 -22
  30. data/lib/ruby_cdk/deploy/output/base.rb +8 -0
  31. data/lib/ruby_cdk/deploy/output/json.rb +7 -0
  32. data/lib/ruby_cdk/deploy/poller.rb +10 -0
  33. data/lib/ruby_cdk/deploy/ports.rb +124 -8
  34. data/lib/ruby_cdk/deploy/sdk_adapters.rb +141 -6
  35. data/lib/ruby_cdk/deploy/ssm_adapter.rb +111 -0
  36. data/lib/ruby_cdk/deploy.rb +1 -0
  37. data/lib/ruby_cdk/diff/compare.rb +1 -1
  38. data/lib/ruby_cdk/diff/identity_center.rb +64 -0
  39. data/lib/ruby_cdk/diff/render.rb +147 -8
  40. data/lib/ruby_cdk/diff/security.rb +195 -10
  41. data/lib/ruby_cdk/diff/security_group.rb +94 -0
  42. data/lib/ruby_cdk/nag/rules/security_group_ingress.rb +2 -0
  43. data/lib/ruby_cdk/schema/sources/provider_type.rb +3 -0
  44. data/lib/ruby_cdk/test/private/cyclic.rb +4 -0
  45. data/lib/ruby_cdk/test/private/js.rb +1 -3
  46. data/lib/ruby_cdk/version.rb +1 -1
  47. metadata +43 -1
@@ -0,0 +1,306 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "failure"
5
+ require_relative "selection"
6
+
7
+ module RubyCdk
8
+ module Cli
9
+ # `import`: existing resources brought under the stack, the CDK's command
10
+ # (cdk-toolkit.ts:916-1061 in aws-cdk-cli at
11
+ # f7c9dca95f440a076c2abd61b66b984624b8548e, and its ResourceImporter,
12
+ # packages/@aws-cdk/toolkit-lib/lib/api/resource-import/importer.ts). One
13
+ # stack; the resources of its template that the deployed stack does not
14
+ # hold are the candidates; each candidate is asked for the properties
15
+ # that identify it, in the terminal or from a mapping file; the import
16
+ # itself is the engine's, one change set of type IMPORT.
17
+ module Import
18
+ # names are the STACK words: one stack, as the CDK refuses more than
19
+ # one. Answers the exit code (architecture section 14).
20
+ def self.run(session, names)
21
+ # The options are read, and so checked, before any client is built:
22
+ # a bad notification ARN is a usage error and never a request.
23
+ options = session.import_options
24
+ mapping = mapping_of(session)
25
+ manifest = session.manifest
26
+ session.say_synthesis_time
27
+ selected = Selection.choose(session.stacks, names:, all: false, command: "import")
28
+ ambiguous(selected) if selected.length > 1
29
+
30
+ unless mapping || session.io.interactive?
31
+ raise Usage.new("--resource-mapping or --resource-mapping-inline is required when input is not a terminal",
32
+ next_step: "Run `ruby-cdk import` again with --resource-mapping PATH, or in a terminal to answer the questions.")
33
+ end
34
+
35
+ stack = selected.first
36
+ entry = manifest.entries.find { |candidate| candidate.name == stack.stack_name }
37
+ region = session.region_of(stack)
38
+ clients = session.clients(region:)
39
+ session.io.debug("#{stack.stack_name}: region #{region}#{session.region_source(stack)}")
40
+ identity = session.identity(clients)
41
+ deployer = session.deployer(clients)
42
+
43
+ template_text = session.template_of(entry)
44
+ diff = RubyCdk::Diff.for_stack(clients.cfn, stack.stack_name, template: template_text)
45
+ addition_ids = diff.changes.select(&:addition?).map(&:logical_id)
46
+ has_non_additions = diff.changes.any? { |change| !change.addition? }
47
+
48
+ # The pending updates are said, and asked about, as the CDK says and
49
+ # asks (cdk-toolkit.ts:949-960, importer.ts:261-264): an import takes
50
+ # them onto the stack as it is, and a deploy reconciles them after.
51
+ # --force imports without the question.
52
+ if has_non_additions
53
+ if session.options.force
54
+ session.io.say("Ignoring updated/deleted resources (--force): " \
55
+ "#{diff.changes.reject(&:addition?).map(&:logical_id).join(", ")}")
56
+ else
57
+ session.io.say("The following resources have pending updates that will be reconciled with a `ruby-cdk deploy` after import:")
58
+ session.io.say(RubyCdk::Diff.render(diff).chomp)
59
+ unless options.yes == true || session.output.ask("Perform import?")
60
+ raise RubyCdk::Deploy::ApprovalRequired, "Import cancelled: the template holds updates or deletes besides the additions, " \
61
+ "and the question was not answered yes. Nothing was imported.\n" \
62
+ "Run `ruby-cdk import #{stack.stack_name}` again with --force to import anyway."
63
+ end
64
+ end
65
+ end
66
+
67
+ if addition_ids.empty?
68
+ session.io.say("#{stack.stack_name}: no new resources compared to the currently deployed stack, skipping import.")
69
+ return Cli::SUCCESS
70
+ end
71
+
72
+ definitions = definitions_of(template_text)
73
+ if mapping
74
+ selected, map = from_mapping(addition_ids, mapping, session)
75
+ else
76
+ selected, map = from_questions(session, clients.cfn, template_text, addition_ids, definitions, options)
77
+ end
78
+
79
+ if selected.empty?
80
+ session.io.say("No resources selected for import.")
81
+ return Cli::SUCCESS
82
+ end
83
+
84
+ # The CDK's --record-resource-mapping (cdk-toolkit.ts:986-995): what
85
+ # was collected is written, and no import runs.
86
+ if session.options.record_resource_mapping
87
+ File.write(session.options.record_resource_mapping, "#{JSON.pretty_generate(map)}\n")
88
+ session.io.say("#{session.options.record_resource_mapping}: mapping file written.")
89
+ return Cli::SUCCESS
90
+ end
91
+
92
+ # The stack's assets are in their bucket before any change set is
93
+ # asked for, as on a deploy: an added resource can carry one.
94
+ published = Assets.publish(stack, store: clients.store, owner: identity.account)
95
+ session.io.debug("#{stack.stack_name}: assets #{published[:uploaded]} uploaded, #{published[:skipped]} already in the bucket")
96
+
97
+ result = deployer.import(stack:, template: template_text, resources: selected, identity:, options:,
98
+ change_set_name: session.options.change_set_name)
99
+ record(session, result)
100
+ return result.exit_code unless result.exit_code.zero?
101
+
102
+ code = next_steps(session, stack.stack_name, addition_ids.length, selected.length, has_non_additions, options)
103
+ code.zero? ? Cli::SUCCESS : code
104
+ end
105
+
106
+ # The CDK's refusal of a selection that names more than one stack
107
+ # (cdk-toolkit.ts:926-931): an import is one stack's operation.
108
+ def self.ambiguous(selected)
109
+ names = selected.map(&:stack_name).join(", ")
110
+ raise Usage.new("Stack selection is ambiguous, please choose a specific stack for import [#{names}]",
111
+ next_step: "Run `ruby-cdk import STACK` for one of them.")
112
+ end
113
+
114
+ # The mapping the flags carry, the CDK's resourceMappingInline and
115
+ # resourceMappingFile (cdk-toolkit.ts:972-975): the inline JSON wins
116
+ # over the file, as it reads first there. A mapping is
117
+ # { logical id => { property => value } }.
118
+ def self.mapping_of(session)
119
+ inline = session.options.resource_mapping_inline
120
+ path = session.options.resource_mapping
121
+ return parse_mapping(inline) if inline
122
+ return parse_mapping(read_mapping(path)) if path
123
+
124
+ nil
125
+ end
126
+
127
+ def self.read_mapping(path)
128
+ File.read(path)
129
+ rescue SystemCallError => e
130
+ raise Usage.new("The resource mapping file could not be read: #{path} (#{e.message})",
131
+ next_step: "Run `ruby-cdk import` again with --resource-mapping naming a file that exists.")
132
+ end
133
+
134
+ def self.parse_mapping(text)
135
+ parsed = JSON.parse(text)
136
+ return parsed if parsed.is_a?(Hash)
137
+
138
+ raise Usage.new("Could not parse resource mapping as JSON: #{text}",
139
+ next_step: "Run `ruby-cdk import` again with a mapping of { logical id => { property => value } }.")
140
+ rescue JSON::ParserError, TypeError
141
+ raise Usage.new("Could not parse resource mapping as JSON: #{text}",
142
+ next_step: "Run `ruby-cdk import` again with a mapping of { logical id => { property => value } }.")
143
+ end
144
+
145
+ # The mapping form, the CDK's loadResourceIdentifiers (importer.ts
146
+ # 152-188): the candidates the mapping names are imported, the others
147
+ # are announced as skipped, and a mapping key that is no candidate of
148
+ # this template is warned about. The types are not questioned here, as
149
+ # the CDK does not question them: a mapping is explicit.
150
+ def self.from_mapping(candidates, mapping, session)
151
+ selected = []
152
+ map = {}
153
+ candidates.each do |logical_id|
154
+ identifier = mapping[logical_id]
155
+ if identifier
156
+ session.io.say("#{logical_id}: importing using #{fmtdict(identifier)}")
157
+ selected << { logical_resource_id: logical_id, resource_identifier: identifier }
158
+ map[logical_id] = identifier
159
+ else
160
+ session.io.say("#{logical_id}: skipping")
161
+ end
162
+ end
163
+ unknown = mapping.keys - candidates
164
+ session.io.say("Unrecognized resource identifiers in mapping file: #{unknown.join(", ")}") unless unknown.empty?
165
+ [ selected, map ]
166
+ end
167
+
168
+ # The interactive form, the CDK's askForResourceIdentifiers
169
+ # (importer.ts:124-139): per candidate, the identifier its questions
170
+ # collect, and a skip line for the candidate they do not.
171
+ def self.from_questions(session, client, template_text, candidates, definitions, options)
172
+ by_type = client.resource_identifier_summaries(template_text).to_h do |summary|
173
+ [ summary.type, summary.identifier_sets ]
174
+ end
175
+ selected = []
176
+ map = {}
177
+ candidates.each do |logical_id|
178
+ type = definitions.dig(logical_id, "Type")
179
+ sets = by_type[type]
180
+ unless sets
181
+ session.io.say("#{logical_id}: unsupported resource type #{type}, skipping import.")
182
+ next
183
+ end
184
+
185
+ given = ask_identifier(session, options, definitions[logical_id], sets, "#{logical_id} (#{type})")
186
+ if given.nil?
187
+ session.io.say("Skipping import of #{logical_id}")
188
+ next
189
+ end
190
+
191
+ selected << { logical_resource_id: logical_id, resource_identifier: given }
192
+ map[logical_id] = given
193
+ end
194
+ [ selected, map ]
195
+ end
196
+
197
+ # One candidate's identifier, the CDK's askForResourceIdentifier
198
+ # (importer.ts:352-443). A set the template's literal properties
199
+ # already satisfy is offered as a yes-or-no question, and refusing
200
+ # every satisfied set skips the resource without a typing question.
201
+ # Otherwise each set's properties are asked for, one line each, an
202
+ # empty answer skipping to the next set. A type with no summary is
203
+ # announced as unsupported and skipped by the caller, as the CDK skips
204
+ # it. --yes answers the yes-or-no questions; it cannot type, so a
205
+ # candidate that needs typing is skipped. nil is a skip.
206
+ def self.ask_identifier(session, options, definition, sets, prefix)
207
+ literals = literal_properties(definition)
208
+ satisfied = sets.select { |set| set.all? { |prop| literals[prop] } }
209
+ satisfied.each do |set|
210
+ candidate = set.to_h { |prop| [ prop, literals[prop] ] }
211
+ next unless options.yes == true || session.output.ask("#{prefix}: import with #{fmtdict(candidate)}")
212
+
213
+ return candidate
214
+ end
215
+ return nil if satisfied.any?
216
+
217
+ if sets.length > 1
218
+ session.io.say("#{prefix}: enter one of #{sets.map { |set| set.join("+") }.join(", ")} to import (leave all empty to skip)")
219
+ end
220
+ sets.each do |set|
221
+ input = ask_set(session.output, options, set, prefix)
222
+ return input unless input.nil?
223
+ end
224
+ nil
225
+ end
226
+
227
+ # One set's properties, typed one line each. nil when the set was not
228
+ # completed.
229
+ def self.ask_set(output, options, set, prefix)
230
+ input = {}
231
+ set.each do |prop|
232
+ answer = options.yes == true ? nil : output.request("#{prefix}: enter #{prop}")
233
+ return nil if answer.nil? || answer.empty?
234
+
235
+ input[prop] = answer
236
+ end
237
+ input
238
+ end
239
+
240
+ # The literal string properties of a resource definition, the only
241
+ # ones that can satisfy an identifier set (importer.ts:367-369).
242
+ def self.literal_properties(definition)
243
+ properties = definition.is_a?(Hash) ? definition["Properties"] : nil
244
+ return {} unless properties.is_a?(Hash)
245
+
246
+ properties.select { |_, value| value.is_a?(String) }
247
+ end
248
+
249
+ def self.definitions_of(template_text)
250
+ body = JSON.parse(template_text)
251
+ resources = body["Resources"]
252
+ resources.is_a?(Hash) ? resources : {}
253
+ end
254
+
255
+ def self.fmtdict(hash)
256
+ hash.map { |key, value| "#{key}=#{value}" }.join(", ")
257
+ end
258
+
259
+ # What the CDK says after an import (cdk-toolkit.ts:1022-1059): the
260
+ # skipped resources, the pending updates a deploy reconciles -- asked
261
+ # about, and the deploy run when it is wanted -- and the drift note.
262
+ # Answers 0, or the exit code of the deploy that followed.
263
+ def self.next_steps(session, name, found, taken, has_non_additions, options)
264
+ if taken < found
265
+ session.io.say("Some resources were skipped. Run another `ruby-cdk import` or a `ruby-cdk deploy` " \
266
+ "to bring the stack up-to-date with your CDK app definition.")
267
+ return 0
268
+ end
269
+
270
+ if has_non_additions
271
+ if options.yes != true && session.output.ask("Finish with a `ruby-cdk deploy` now?")
272
+ code = Operation.new(session, kind: :deploy).call([ name ])
273
+ return code unless code.zero?
274
+
275
+ session.io.say("Import complete. The stack now matches your CDK app.")
276
+ return 0
277
+ end
278
+ session.io.say("Import complete. Remember to run `ruby-cdk deploy` to update the stack to match your CDK app.")
279
+ return 0
280
+ end
281
+
282
+ session.io.say("Import operation complete. We recommend you run a drift detection operation to confirm your CDK app " \
283
+ "resource definitions are up-to-date. Read more here: " \
284
+ "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/detect-drift-stack.html")
285
+ 0
286
+ end
287
+
288
+ # For --json, one object on standard out (architecture section 11): the
289
+ # shape a deploy's record carries, the import's changes among it.
290
+ # Nothing else is written there.
291
+ def self.record(session, result)
292
+ return unless session.options.json
293
+
294
+ object = {
295
+ "name" => result.stack_name,
296
+ "stack_id" => result.stack_id,
297
+ "outcome" => result.outcome&.to_s,
298
+ "exit_code" => result.exit_code,
299
+ "changes" => result.changes.map(&:to_h),
300
+ "outputs" => result.outputs || {}
301
+ }
302
+ session.io.result("#{JSON.generate(object)}\n")
303
+ end
304
+ end
305
+ end
306
+ end
@@ -0,0 +1,214 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "failure"
5
+
6
+ module RubyCdk
7
+ module Cli
8
+ # `lookup`: the command of decision D-022. The app is synthesized once
9
+ # with the cache as it is; every query the cache does not answer stops
10
+ # the synthesis with a Context::Miss, and this command answers it
11
+ # against AWS through the EC2 adapter, writes the answer into
12
+ # cdk.context.json beside the app file, and synthesizes again, until the
13
+ # app synthesizes whole. `synth` itself never calls AWS: it refuses with
14
+ # the command to run, which is this one.
15
+ #
16
+ # Each answer is written as soon as it is read, so a query that fails
17
+ # later leaves the earlier ones cached. The account and region of a
18
+ # query are the stack's env, and the credentials must be the query's
19
+ # account, as a deploy into an env must (architecture section 13): the
20
+ # cache entry names the environment it is valid for, and synthesis never
21
+ # reads one for another.
22
+ module Lookup
23
+ # Answers every pending query of the app. Takes no stack names: the
24
+ # app file builds every stack, so every query of every stack is
25
+ # pending. Answers the exit code.
26
+ def self.run(session, names)
27
+ unless names.empty?
28
+ raise Usage.new("`ruby-cdk lookup` takes no stack names, got #{names.join(", ")}: the app file builds " \
29
+ "every stack, so the command answers every query of every stack.",
30
+ next_step: "Run `ruby-cdk lookup` without arguments.")
31
+ end
32
+
33
+ io = session.io
34
+ cache = cache_path(session)
35
+ io.debug("lookup: the context cache is #{cache}")
36
+
37
+ answered = {}
38
+ manifest = synthesize(session, answered, cache)
39
+ report(session, cache, answered, manifest)
40
+ Cli::SUCCESS
41
+ end
42
+
43
+ # Synthesizes until the app holds no query the cache fails to answer,
44
+ # answering each miss as it is met and writing it into the cache at
45
+ # once. Returns the manifest of the synthesis that came whole.
46
+ def self.synthesize(session, answered, cache)
47
+ loop do
48
+ begin
49
+ return session.manifest
50
+ rescue RubyCdk::Context::Miss => miss
51
+ raise AnsweredTwice.new(miss, answered[miss.key]) if answered.key?(miss.key)
52
+
53
+ answered[miss.key] = { query: miss.query, where: miss.where, answer: answer_one(session, miss, cache) }
54
+ session.io.debug("lookup: answered #{miss.key}, synthesizing again")
55
+ end
56
+ end
57
+ end
58
+
59
+ # cdk.context.json beside the app file, the file synthesis reads.
60
+ def self.cache_path(session)
61
+ app_file = File.expand_path(session.options.app.to_s)
62
+ unless File.file?(app_file)
63
+ raise Usage.new("There is no app file at #{app_file}",
64
+ next_step: "Run `ruby-cdk lookup` from the app's directory, or with --app PATH (the default is cdk.rb).")
65
+ end
66
+
67
+ File.expand_path(RubyCdk::Context::FILE_NAME, File.dirname(app_file))
68
+ end
69
+
70
+ # One query, answered: the environment is checked against the
71
+ # credentials and the command line before anything is asked, the
72
+ # query's adapter reads the answer, and it is written into the cache at
73
+ # once.
74
+ def self.answer_one(session, miss, cache)
75
+ query = miss.query
76
+ refuse_region(session, query)
77
+ io = session.io
78
+ io.say("Looking up #{query.describe.empty? ? "every VPC" : query.describe} " \
79
+ "for account #{query.account} in #{query.region} (#{miss.where})...") unless silent?(session)
80
+
81
+ client = client_for(session, query)
82
+ account = client.account
83
+ if account != query.account
84
+ raise PreconditionError, "The credentials are for account #{account}, but the query is for " \
85
+ "#{query.account}, the stack's env: the answer would not be valid where the stack deploys. " \
86
+ "Nothing was cached. Check the profile (--profile NAME), then run `ruby-cdk lookup` again."
87
+ end
88
+ if session.options.account && session.options.account != account
89
+ raise PreconditionError, "--account #{session.options.account} was given, but the credentials are for " \
90
+ "account #{account}. Nothing was cached. Run `ruby-cdk lookup` again with --account #{account} " \
91
+ "or without --account."
92
+ end
93
+
94
+ answer = answer_query(client, query)
95
+ entries = RubyCdk::Context.read(cache)
96
+ entries[miss.key] = answer
97
+ RubyCdk::Context.write(cache, entries)
98
+ answer
99
+ end
100
+
101
+ # The client of one query, through the command line's one client seam:
102
+ # the EC2 one answers a "vpc" query, the SSM one an "ssm" query. Each
103
+ # kind names its client and its arguments here; the environment checks,
104
+ # the cache write and the re-synthesis are one flow for every kind.
105
+ def self.client_for(session, query)
106
+ case query.provider
107
+ when "vpc" then session.aws.ec2_client(profile: session.options.profile, region: query.region)
108
+ when "ssm" then session.aws.ssm_client(profile: session.options.profile, region: query.region)
109
+ else raise PreconditionError, unknown_provider(query)
110
+ end
111
+ end
112
+
113
+ # The one call of a query, as the adapter takes the arguments: the
114
+ # "vpc-id" and the tags of a VPC query, the bare name of a parameter.
115
+ def self.answer_query(client, query)
116
+ case query.provider
117
+ when "vpc" then client.lookup_vpc(vpc_id: query.args["vpc-id"], tags: query_tags(query))
118
+ when "ssm" then client.lookup_parameter(name: query.args["name"])
119
+ else raise PreconditionError, unknown_provider(query)
120
+ end
121
+ end
122
+
123
+ # No construct makes a query of another kind; this is a bug and not a
124
+ # state a person can fix.
125
+ def self.unknown_provider(query)
126
+ "No adapter answers a #{query.provider} lookup (the key #{query.key} names it). Report it as a bug in ruby-cdk."
127
+ end
128
+
129
+ # --region names the region every client of the run is built for; a
130
+ # query of another stack env would write an answer into the wrong
131
+ # region's key.
132
+ def self.refuse_region(session, query)
133
+ wanted = session.options.region
134
+ return unless wanted && wanted != query.region
135
+
136
+ raise PreconditionError, "--region #{wanted} was given, but the query is for #{query.region}, the " \
137
+ "stack's env. Nothing was cached. Run `ruby-cdk lookup` again without --region, or with " \
138
+ "--region #{query.region} only."
139
+ end
140
+
141
+ # The tags of a query, as the adapter takes them: "tag.<Name>" back to
142
+ # a tag name.
143
+ def self.query_tags(query)
144
+ query.args.select { |name, _| name.start_with?("tag.") }
145
+ .to_h { |name, value| [ name.delete_prefix("tag."), value ] }
146
+ end
147
+
148
+ # What the command did, and the synthesis that proves the answers are
149
+ # read: one line per query for a person, one JSON object per query for
150
+ # --json, nothing but the exit code for --quiet.
151
+ def self.report(session, cache, answered, manifest)
152
+ io = session.io
153
+ if session.options.json
154
+ answered.each do |key, entry|
155
+ io.result(JSON.generate({ "key" => key, "where" => entry[:where], "answer" => entry[:answer] }))
156
+ end
157
+ return
158
+ end
159
+ return if session.options.quiet
160
+
161
+ if answered.empty?
162
+ io.say("Nothing to look up: every query the app makes has an answer in #{cache} already.")
163
+ else
164
+ answered.each do |key, entry|
165
+ io.say("Answered #{key}")
166
+ io.say(" #{entry[:where]}: #{describe_answer(entry)}")
167
+ end
168
+ io.say("Wrote #{answered.length} #{answered.length == 1 ? "answer" : "answers"} into #{cache}. " \
169
+ "The file is part of the app: commit it, so two machines synthesize the same template.")
170
+ end
171
+ io.say("Successfully synthesized to #{File.expand_path(manifest.out_dir)}.")
172
+ end
173
+
174
+ # One line about what an answer holds. The value of a parameter is
175
+ # deliberately not on the terminal: a String parameter may carry a
176
+ # secret, and the cache file already holds the value for whoever may
177
+ # read it.
178
+ def self.describe_answer(entry)
179
+ case entry[:query].provider
180
+ when "vpc" then describe_vpc(entry[:answer])
181
+ when "ssm" then describe_parameter(entry[:answer])
182
+ end
183
+ end
184
+
185
+ def self.describe_vpc(answer)
186
+ zones = answer["availability_zones"].length
187
+ counts = answer["subnet_groups"].map do |group|
188
+ "#{group["subnets"].length} #{group["type"]}"
189
+ end.join(", ")
190
+ details = [ "#{zones} #{zones == 1 ? "zone" : "zones"}", counts ].reject(&:empty?).join(", ")
191
+ "#{answer["vpc_id"]} (#{answer["cidr"]}) in #{answer["region"]}: #{details}"
192
+ end
193
+
194
+ def self.describe_parameter(answer)
195
+ "#{answer["name"]} (#{answer["type"]}) in #{answer["region"]}; its value is only in the cache file"
196
+ end
197
+
198
+ def self.silent?(session)
199
+ session.options.quiet || session.options.json
200
+ end
201
+
202
+ # Exit 1. A query that was answered and still misses: the cache write
203
+ # and the read disagree, which is a bug and not a state a person can
204
+ # fix by running again.
205
+ class AnsweredTwice < RubyCdk::PreconditionError
206
+ def initialize(miss, written)
207
+ super("The query #{miss.key} was answered into the cache and the app still misses it: " \
208
+ "#{miss.where} asked again, #{written ? "and the answer written differs from the one read" : "and no answer was read"}. " \
209
+ "Nothing more was cached. Report it as a bug in ruby-cdk.")
210
+ end
211
+ end
212
+ end
213
+ end
214
+ end
@@ -19,8 +19,11 @@ module RubyCdk
19
19
  # command does not take, or that was not given, is nil; a boolean that
20
20
  # was given is true.
21
21
  Options = Data.define(:app, :out, :profile, :region, :account, :yes, :force, :quiet, :verbose, :json, :color,
22
- :long, :all, :exclusively, :execute, :on_failure, :parameters, :tags, :outputs_file, :previous_parameters,
23
- :no_validate, :strict_types, :deployer, :fail, :fail_on, :security_only, :hotswap, :hotswap_fallback)
22
+ :long, :all, :exclusively, :execute, :on_failure, :parameters, :tags, :notification_arns,
23
+ :rollback_trigger_alarm_arns, :monitoring_time_minutes, :import_existing_resources, :outputs_file,
24
+ :previous_parameters, :no_validate, :strict_types, :deployer, :fail, :fail_on, :security_only, :hotswap,
25
+ :hotswap_fallback, :interval, :change_set_name, :resource_mapping, :resource_mapping_inline,
26
+ :record_resource_mapping)
24
27
 
25
28
  # Thor's options as Options.
26
29
  def self.options_from(given)
@@ -190,6 +193,9 @@ module RubyCdk
190
193
  @deploy_options ||= Deploy::DeployOptions.new(
191
194
  parameters: Pairs.parse(options.parameters, option: "--parameters", command:),
192
195
  tags: Pairs.parse(options.tags, option: "--tags", command:),
196
+ notification_arns: split_arn_list(options.notification_arns),
197
+ rollback_configuration: rollback_configuration,
198
+ import_existing_resources: !!options.import_existing_resources,
193
199
  yes: !!options.yes,
194
200
  no_execute: options.execute == false,
195
201
  on_failure: on_failure,
@@ -216,6 +222,57 @@ module RubyCdk
216
222
  )
217
223
  end
218
224
 
225
+ # What the engine is given for each deploy of the watch loop. The mode is
226
+ # the CDK's determineHotswapMode with watch: true (cli.ts:999-1021 in
227
+ # aws-cdk-cli at f7c9dca95f440a076c2abd61b66b984624b8548e): neither flag
228
+ # is HOTSWAP_ONLY -- the hotswap by default the watch is for; --no-hotswap
229
+ # is FULL_DEPLOYMENT; --hotswap-fallback is FALL_BACK; the pair is
230
+ # refused, as for deploy. The deploy never asks: the CDK's watch deploy is
231
+ # built with RequireApproval.NEVER (cdk-toolkit.ts:1535), and a loop that
232
+ # stops to ask is not a watch.
233
+ def watch_deploy_options
234
+ check_hotswap_flags
235
+ hotswap, fallback = watch_hotswap_flags
236
+ Deploy::DeployOptions.new(
237
+ parameters: Pairs.parse(options.parameters, option: "--parameters", command:),
238
+ tags: Pairs.parse(options.tags, option: "--tags", command:),
239
+ yes: true,
240
+ force: !!options.force,
241
+ account: options.account,
242
+ profile: options.profile,
243
+ hotswap: hotswap,
244
+ hotswap_fallback: fallback,
245
+ use_previous_parameters: options.previous_parameters != false
246
+ )
247
+ end
248
+
249
+ # The next synthesis of the watch loop: the app file is loaded again and
250
+ # the manifest answered fresh, the way the CDK's watch re-produces the
251
+ # assembly on every iteration but the first (toolkit.ts:1199-1207). The
252
+ # memoized app and manifest are replaced, so stacks, templates and the
253
+ # synthesis-time line read what this iteration built. An app file broken
254
+ # mid-edit is reported at its line, like a first load's is.
255
+ def reiterate
256
+ App.reset!
257
+ @app = nil
258
+ @manifest = nil
259
+ manifest
260
+ end
261
+
262
+ # What the engine is given for an import. No parameters and no tags of
263
+ # the command line: the CDK's import declares neither (its command
264
+ # options, cli-config.ts:306-338). --no-execute leaves the change set
265
+ # for the console; the notification ARNs are checked like a deploy's.
266
+ def import_options
267
+ @import_options ||= Deploy::DeployOptions.new(
268
+ yes: !!options.yes,
269
+ no_execute: options.execute == false,
270
+ notification_arns: split_arn_list(options.notification_arns),
271
+ account: options.account,
272
+ profile: options.profile
273
+ )
274
+ end
275
+
219
276
  # The engine's output object, on the session's streams.
220
277
  def output
221
278
  @output ||=
@@ -241,10 +298,54 @@ module RubyCdk
241
298
  next_step: "Run `ruby-cdk #{command}` again with only one of the two flags.")
242
299
  end
243
300
 
301
+ # The hotswap pair of the watch, as determineHotswapMode sorts it with
302
+ # watch: true (cli.ts:999-1021 in aws-cdk-cli at
303
+ # f7c9dca95f440a076c2abd61b66b984624b8548e): neither flag is HOTSWAP_ONLY,
304
+ # a false among them is FULL_DEPLOYMENT, and of the truths the fallback
305
+ # wins. The pair both true was refused above.
306
+ def watch_hotswap_flags
307
+ given = [ options.hotswap, options.hotswap_fallback ]
308
+ return [ true, false ] if given.all?(&:nil?)
309
+ return [ false, false ] if given.none?
310
+
311
+ options.hotswap ? [ true, false ] : [ true, true ]
312
+ end
313
+
244
314
  def clock
245
315
  Process.clock_gettime(Process::CLOCK_MONOTONIC)
246
316
  end
247
317
 
318
+ # The ARN lists of the command line: each word split on commas, the way
319
+ # the CDK's parser splits the words of its array flags
320
+ # (--notification-arns ARN[,ARN]). nil stays nil: the flag not given is
321
+ # not the empty list, which for the notification ARNs would be a deploy
322
+ # that manages them.
323
+ def split_arn_list(words)
324
+ return nil if words.nil?
325
+
326
+ words.flat_map { |word| word.split(",") }
327
+ end
328
+
329
+ # The rollback configuration of the deploy, built as the CDK builds it
330
+ # at its command line (cli.ts:463-479 at f7c9dca95f440a076c2abd61b66b984624b8548e):
331
+ # --monitoring-time-minutes requires the alarm ARNs, and a single
332
+ # literal 'none' asks for the triggers the stack has to be cleared.
333
+ # The ARNs are the configuration's triggers as they were given; every
334
+ # one is treated as a metric alarm, the CDK's default type. The flags
335
+ # not given manage nothing: nil, and the triggers the stack has are
336
+ # left alone.
337
+ def rollback_configuration
338
+ arns = split_arn_list(options.rollback_trigger_alarm_arns)
339
+ if options.monitoring_time_minutes && arns.nil?
340
+ raise Usage.new("--monitoring-time-minutes requires --rollback-trigger-alarm-arns",
341
+ next_step: "Run `ruby-cdk #{command}` again with --rollback-trigger-alarm-arns, or without --monitoring-time-minutes.")
342
+ end
343
+ return nil if arns.nil?
344
+
345
+ triggers = arns.length == 1 && arns.first.downcase == "none" ? [] : arns
346
+ Deploy::RollbackConfiguration.new(triggers: triggers, monitoring_time_in_minutes: options.monitoring_time_minutes)
347
+ end
348
+
248
349
  # True when the pipeline's synth takes the validate keyword.
249
350
  def pipeline_takes_validate?
250
351
  app.method(:synth).parameters.any? { |_kind, name| name == :validate }
@@ -253,6 +354,12 @@ module RubyCdk
253
354
  # The app file, or the error placed where it happened.
254
355
  def load_app(path)
255
356
  App.build!(app_file: path, out_dir: options.out)
357
+ rescue RubyCdk::Context::Miss
358
+ # A context lookup the cache does not answer (D-022): the tool's own
359
+ # refusal, written for a user and carrying the query the lookup
360
+ # command answers, so it passes through unwrapped. Any other command
361
+ # reports it as it is, message and command to run.
362
+ raise
256
363
  rescue RubyCdk::Error => e
257
364
  # One of this gem's errors raised by the app file: it is already written
258
365
  # for a user, and it is still placed at the file's line.
@@ -274,8 +381,12 @@ module RubyCdk
274
381
  end
275
382
 
276
383
  # --on-failure, checked against the engine's own table before any request,
277
- # so that a typo is a usage error and not a failed deploy.
384
+ # so that a typo is a usage error and not a failed deploy. Commands that do
385
+ # not declare --on-failure (such as `import`, which may invoke a follow-up
386
+ # deploy) leave it nil and take the engine's default DELETE.
278
387
  def on_failure
388
+ return "DELETE" if options.on_failure.nil?
389
+
279
390
  wanted = options.on_failure.to_s
280
391
  unless Deploy::Deployer::ON_FAILURE.key?(wanted.downcase)
281
392
  raise Usage.new("--on-failure must be one of DELETE, ROLLBACK or DO_NOTHING, not #{wanted.inspect}",