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,389 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "errors"
5
+ require_relative "poller"
6
+ require_relative "ports"
7
+
8
+ module RubyCdk
9
+ module Deploy
10
+ # What CloudFormation holds against what a stack should hold. The CDK's
11
+ # drift action, read at f7c9dca95f440a076c2abd61b66b984624b8548e: detection
12
+ # is started (DetectStackDrift, api/drift/drift.ts:22), followed to its end
13
+ # (DescribeStackDriftDetectionStatus, drift.ts:76-112), and the per-resource
14
+ # results are read whole (DescribeStackResourceDrifts, drift.ts:42-54).
15
+ # The words are the CDK's: IN_SYNC reads "Resources In Sync"; UNKNOWN and
16
+ # the resources CloudFormation says nothing about read "Unchecked
17
+ # Resources", because they were not checked (drift-formatter.ts:101-107);
18
+ # MODIFIED reads "Modified Resources" with its property differences;
19
+ # DELETED reads "Deleted Resources". Only MODIFIED and DELETED count as
20
+ # drift (drift-formatter.ts:116-118), and AWS::CDK::Metadata never does,
21
+ # wherever it turns up (drift-formatter.ts:88-90, 191, 214).
22
+ #
23
+ # This is a read, not an operation: it changes nothing in AWS, so it sits
24
+ # beside the deployer rather than inside it. It is in the deploy component
25
+ # because it speaks to CloudFormation through the deploy ports and follows
26
+ # a CloudFormation-side operation with the engine's poller.
27
+ #
28
+ # The CDK's drift does not compare the deployed template with the
29
+ # synthesized one: its action makes no get_template request
30
+ # (toolkit.ts:465-535), and that comparison is `cdk diff` there and `diff`
31
+ # here. The synthesized template is read for one thing only: which
32
+ # resources the stack should hold, so that the ones CloudFormation says
33
+ # nothing about are reported as unchecked (drift-formatter.ts:84-93).
34
+ module Drift
35
+ # The drift words CloudFormation answers a resource with.
36
+ IN_SYNC = "IN_SYNC"
37
+ MODIFIED = "MODIFIED"
38
+ DELETED = "DELETED"
39
+ UNKNOWN = "UNKNOWN"
40
+ NOT_CHECKED = "NOT_CHECKED"
41
+
42
+ # The detection words, and the ones a property difference carries.
43
+ DETECTION_COMPLETE = "DETECTION_COMPLETE"
44
+ DETECTION_FAILED = "DETECTION_FAILED"
45
+ ADD = "ADD"
46
+ REMOVE = "REMOVE"
47
+ NOT_EQUAL = "NOT_EQUAL"
48
+
49
+ # The markers of the sections, as the CDK renders them plain
50
+ # (drift-formatter.ts:277-280): in sync and unchecked carry no mark of
51
+ # their own, modified is [~], deleted is [-], and a property difference
52
+ # is [+] added, [-] removed or [~] changed.
53
+ CONTEXT = "[ ]"
54
+ UPDATE = "[~]"
55
+ REMOVAL = "[-]"
56
+ ADDITION = "[+]"
57
+
58
+ # The CDK's metadata resource: never counted, never rendered as drift.
59
+ METADATA = "AWS::CDK::Metadata"
60
+
61
+ # One resource from the synthesized template that CloudFormation did not
62
+ # check: either absent from DescribeStackResourceDrifts (status nil) or
63
+ # returned with status UNKNOWN (drift-formatter.ts:101-107).
64
+ UncheckedResource = Struct.new(:logical_id, :resource_type, :status, :status_reason, keyword_init: true) do
65
+ def to_h
66
+ hash = { "logical_id" => logical_id, "resource_type" => resource_type, "status" => status }
67
+ hash["status_reason"] = status_reason if status_reason
68
+ hash
69
+ end
70
+ end
71
+
72
+ # The drift of one stack, carrying both the structured resource lists
73
+ # (for --json) and the CDK's formatted sections (actions/drift/index.ts:47-67).
74
+ # available is false when CloudFormation holds no drift results for the
75
+ # stack (toolkit.ts:481-486).
76
+ Result = Struct.new(:stack_name, :detection_id, :stack_drift_status, :available, :num_resources_with_drift,
77
+ :num_resources_unchecked, :in_sync, :unchecked_resources, :modified_resources, :deleted_resources,
78
+ :not_checked_resources, :unchanged, :unchecked, :modified, :deleted, :summary, keyword_init: true) do
79
+ def available?
80
+ available != false
81
+ end
82
+
83
+ def drifted?
84
+ num_resources_with_drift > 0
85
+ end
86
+
87
+ def to_h
88
+ {
89
+ "name" => stack_name,
90
+ "detection_id" => detection_id,
91
+ "stack_drift_status" => stack_drift_status,
92
+ "available" => available?,
93
+ "drifted" => drifted?,
94
+ "num_resources_with_drift" => num_resources_with_drift,
95
+ "num_resources_unchecked" => num_resources_unchecked,
96
+ "modified" => (modified_resources || []).map { |drift| Drift.resource_hash(drift) },
97
+ "deleted" => (deleted_resources || []).map { |drift| Drift.resource_hash(drift) },
98
+ "in_sync" => (in_sync || []).map { |drift| Drift.resource_hash(drift) },
99
+ "unchecked" => (unchecked_resources || []).map(&:to_h),
100
+ "not_checked" => (not_checked_resources || []).map { |drift| Drift.resource_hash(drift) }
101
+ }
102
+ end
103
+ end
104
+
105
+ module_function
106
+
107
+ # The drift of one stack: detection started, followed, read, classified.
108
+ # template is the stack's synthesized template, as bytes or as a Hash.
109
+ # output is the engine's output port (or any object responding to
110
+ # #announce); the progress lines go through it and nothing else does.
111
+ # When CloudFormation holds no drift results (describe_stack_resource_drifts
112
+ # answers nil), returns a Result with available: false.
113
+ def check(client, name, template:, poller: Poller.drift, output: nil)
114
+ detection_id = client.detect_stack_drift(name)
115
+ announce(output, "Detecting drift with ID #{detection_id} for stack #{name}...")
116
+
117
+ status = follow(client, detection_id, poller, output)
118
+ if status.stack_drift_status == UNKNOWN
119
+ announce(output, "Stack drift status is UNKNOWN. This may occur when CloudFormation is unable to detect drift " \
120
+ "for at least one resource and all other resources are IN_SYNC.\nReason: #{reason(status.status_reason)}")
121
+ end
122
+
123
+ drifts = client.describe_stack_resource_drifts(name)
124
+ if drifts.nil?
125
+ return Result.new(
126
+ stack_name: name,
127
+ detection_id: detection_id,
128
+ stack_drift_status: status.stack_drift_status,
129
+ available: false,
130
+ num_resources_with_drift: 0,
131
+ num_resources_unchecked: 0,
132
+ in_sync: [],
133
+ unchecked_resources: [],
134
+ modified_resources: [],
135
+ deleted_resources: [],
136
+ not_checked_resources: [],
137
+ summary: "#{name}: No drift results available"
138
+ )
139
+ end
140
+
141
+ announce_unknown(output, drifts)
142
+ classify(name, template, drifts, detection_id: detection_id, stack_drift_status: status.stack_drift_status)
143
+ end
144
+
145
+ # Polls the detection until it completes. DETECTION_FAILED ends it here,
146
+ # with the CDK's words (drift.ts:96-98); so does the limit, with the
147
+ # CDK's timeout message (drift.ts:100-101).
148
+ def follow(client, detection_id, poller, output)
149
+ poller.run do
150
+ status = client.describe_stack_drift_detection_status(detection_id)
151
+ case status.detection_status
152
+ when DETECTION_COMPLETE
153
+ status
154
+ when DETECTION_FAILED
155
+ Kernel.raise DriftDetectionFailed, "Drift detection failed: #{reason(status.status_reason)}"
156
+ else
157
+ announce(output, "Waiting for drift detection to complete...")
158
+ nil
159
+ end
160
+ end
161
+ rescue WaitTimedOut
162
+ Kernel.raise DriftDetectionFailed, "Drift detection failed: Timed out after #{poller.limit} seconds."
163
+ end
164
+
165
+ # The drift of a stack, sorted into the CDK's sections. expected is the
166
+ # map of the resources the template says the stack holds; a resource
167
+ # with no drift record, or one that reads UNKNOWN, was not checked.
168
+ def classify(name, template, drifts, detection_id: nil, stack_drift_status: nil)
169
+ expected = expected_resources(template)
170
+ in_sync = drifts.select { |drift| drift.status == IN_SYNC }
171
+ modified_list = drifts.select { |drift| drift.status == MODIFIED && drift.resource_type != METADATA }
172
+ deleted_list = drifts.select { |drift| drift.status == DELETED && drift.resource_type != METADATA }
173
+ not_checked_list = drifts.select { |drift| drift.status == NOT_CHECKED && drift.resource_type != METADATA }
174
+ counted = modified_list.length + deleted_list.length
175
+
176
+ unchecked_list = expected.filter_map do |logical_id, resource_type|
177
+ record = drifts.find { |drift| drift.logical_id == logical_id }
178
+ next unless record.nil? || record.status == UNKNOWN
179
+
180
+ UncheckedResource.new(
181
+ logical_id: logical_id,
182
+ resource_type: resource_type,
183
+ status: record&.status,
184
+ status_reason: record&.status_reason
185
+ )
186
+ end
187
+
188
+ # Match CDK's DriftFormatter (drift-formatter.ts:123-156): when no
189
+ # drift records were returned, no detail sections are built (though
190
+ # num_resources_unchecked still counts every template resource); when
191
+ # no drift is detected, unchanged is omitted from the formatted output.
192
+ if drifts.empty?
193
+ unchanged_text = nil
194
+ unchecked_text = nil
195
+ modified_text = nil
196
+ deleted_text = nil
197
+ else
198
+ unchecked_text = section("Unchecked Resources", unchecked_list.map do |resource|
199
+ "#{CONTEXT} #{resource.resource_type} #{resource.logical_id}"
200
+ end)
201
+ modified_text = section("Modified Resources", modified_rows(modified_list))
202
+ deleted_text = section("Deleted Resources", deleted_list.filter_map do |drift|
203
+ marked_line(REMOVAL, drift) if drift.logical_id && drift.resource_type
204
+ end)
205
+ unchanged_text = if counted > 0
206
+ section("Resources In Sync", in_sync.filter_map do |drift|
207
+ marked_line(CONTEXT, drift) if drift.logical_id && drift.resource_type
208
+ end)
209
+ end
210
+ end
211
+
212
+ Result.new(
213
+ stack_name: name,
214
+ detection_id: detection_id,
215
+ stack_drift_status: stack_drift_status,
216
+ available: true,
217
+ num_resources_with_drift: counted,
218
+ num_resources_unchecked: unchecked_list.length,
219
+ in_sync: in_sync,
220
+ unchecked_resources: unchecked_list,
221
+ modified_resources: modified_list,
222
+ deleted_resources: deleted_list,
223
+ not_checked_resources: not_checked_list,
224
+ unchanged: unchanged_text,
225
+ unchecked: unchecked_text,
226
+ modified: modified_text,
227
+ deleted: deleted_text,
228
+ summary: summary_of(counted)
229
+ )
230
+ end
231
+
232
+ # One stack's drift as plain text, in the CDK's layout (toolkit.ts:503-523):
233
+ # header, then under --verbose the in-sync and unchecked sections, then
234
+ # modified and deleted, then the per-stack summary line. Under --quiet, a
235
+ # clean stack prints nothing (like `diff --quiet`).
236
+ def render(result, verbose: false, quiet: false)
237
+ return result.summary unless result.available?
238
+ return "" if quiet && !result.drifted?
239
+
240
+ parts = [ "Stack #{result.stack_name}\n" ]
241
+ if verbose
242
+ parts << result.unchanged if result.unchanged
243
+ parts << result.unchecked if result.unchecked
244
+ end
245
+ parts << result.modified if result.modified
246
+ parts << result.deleted if result.deleted
247
+ parts << result.summary
248
+ parts.join("\n").chomp
249
+ end
250
+
251
+ # The overall closing line across stacks (toolkit.ts:527-529).
252
+ def summary(results)
253
+ available = results.select(&:available?)
254
+ total_drifts = available.sum(&:num_resources_with_drift)
255
+ total_unchecked = available.sum(&:num_resources_unchecked)
256
+ suffix = total_unchecked > 0 ? " (#{total_unchecked} unchecked)" : ""
257
+ "✨ Number of resources with drift: #{total_drifts}#{suffix}"
258
+ end
259
+
260
+ # The closing warning when CloudFormation returned no drift results for
261
+ # one or more stacks (toolkit.ts:530-532), or nil when every stack answered.
262
+ def unavailable_warning(results)
263
+ count = results.count { |result| !result.available? }
264
+ return nil if count.zero?
265
+
266
+ "⚠️ Failed to check drift for #{count} stack(s). Check log for more details."
267
+ end
268
+
269
+ # The JSON representation of one ResourceDrift.
270
+ def resource_hash(drift)
271
+ hash = {
272
+ "logical_id" => drift.logical_id,
273
+ "physical_id" => drift.physical_id,
274
+ "resource_type" => drift.resource_type,
275
+ "status" => drift.status
276
+ }
277
+ differences = drift.property_differences || []
278
+ unless differences.empty?
279
+ hash["property_differences"] = differences.map do |difference|
280
+ {
281
+ "property_path" => difference.property_path,
282
+ "expected_value" => difference.expected_value,
283
+ "actual_value" => difference.actual_value,
284
+ "difference_type" => difference.difference_type
285
+ }
286
+ end
287
+ end
288
+ hash["status_reason"] = drift.status_reason if drift.status_reason
289
+ hash
290
+ end
291
+
292
+ # The resources the stack should hold, as logical ID => type, from the
293
+ # synthesized template (drift-formatter.ts:84-93).
294
+ def expected_resources(template)
295
+ return {} if template.nil?
296
+
297
+ body = template.is_a?(Hash) ? template : JSON.parse(template.to_s)
298
+ (body["Resources"] || {}).filter_map do |logical_id, resource|
299
+ next if resource.is_a?(Hash) && resource["Type"] == METADATA
300
+
301
+ [ logical_id, resource.is_a?(Hash) ? resource["Type"] : nil ]
302
+ end.to_h
303
+ end
304
+
305
+ # The modified section's rows: one per resource, then its property
306
+ # differences under it (drift-formatter.ts:189-209).
307
+ def modified_rows(drifts)
308
+ drifts.flat_map do |drift|
309
+ next [] unless drift.logical_id && drift.resource_type
310
+
311
+ differences = (drift.property_differences || []).select(&:property_path)
312
+ [ "#{UPDATE} #{drift.resource_type} #{drift.logical_id}" ] + differences.each_with_index.flat_map do |difference, index|
313
+ difference_lines(difference, index == differences.length - 1)
314
+ end
315
+ end
316
+ end
317
+
318
+ # The lines of one property difference: the path with the mark of what
319
+ # happened to it, and, for a changed value, the values on both sides
320
+ # (drift-formatter.ts:262-274).
321
+ def difference_lines(difference, last)
322
+ kind = difference_kind(difference)
323
+ marker = case kind
324
+ when ADD then ADDITION
325
+ when REMOVE then REMOVAL
326
+ else UPDATE
327
+ end
328
+ lines = [ " #{last ? "└" : "├"}─ #{marker} #{difference.property_path}" ]
329
+ return lines unless kind == NOT_EQUAL
330
+
331
+ lines + [ " ├─ #{REMOVAL} #{difference.expected_value}", " └─ #{ADDITION} #{difference.actual_value}" ]
332
+ end
333
+
334
+ def difference_kind(difference)
335
+ return difference.difference_type if difference.difference_type
336
+ return ADD if difference.expected_value.nil? && !difference.actual_value.nil?
337
+ return REMOVE if !difference.expected_value.nil? && difference.actual_value.nil?
338
+
339
+ NOT_EQUAL
340
+ end
341
+
342
+ # A section's text: its title, one line per row, and the CDK's blank
343
+ # line after it (printSectionHeader and printSectionFooter,
344
+ # drift-formatter.ts:254-260).
345
+ def section(title, rows)
346
+ return nil if rows.empty?
347
+
348
+ ([ title ] + rows + [ "" ]).join("\n")
349
+ end
350
+
351
+ # One resource line: the section's mark, the type, the logical ID. The
352
+ # CDK prints the construct path where it has one; this tool's manifest
353
+ # carries none, so the logical ID stands alone, which is the CDK's own
354
+ # reading where the map has no entry (drift-formatter.ts:227-229).
355
+ def marked_line(marker, drift)
356
+ "#{marker} #{drift.resource_type} #{drift.logical_id}"
357
+ end
358
+
359
+ # The closing line: "No drift detected", or the CDK's count
360
+ # (drift-formatter.ts:124, 134).
361
+ def summary_of(count)
362
+ return "No drift detected" if count.zero?
363
+
364
+ "#{count} resource#{count == 1 ? "" : "s"} #{count == 1 ? "has" : "have"} drifted from their expected configuration"
365
+ end
366
+
367
+ # The resources CloudFormation could not check, named with the CDK's
368
+ # words and its per-resource reason (drift.ts:56-68).
369
+ def announce_unknown(output, drifts)
370
+ unknown = drifts.select { |drift| drift.status == UNKNOWN }
371
+ return if unknown.empty?
372
+
373
+ lines = unknown.map { |drift| " - #{drift.logical_id}: #{reason(drift.status_reason)}" }
374
+ announce(output, "Some resources have UNKNOWN drift status. This may be due to insufficient permissions " \
375
+ "or throttling:\n#{lines.join("\n")}")
376
+ end
377
+
378
+ # The CDK's formatReason (util/string-manipulation.ts:50-52): a reason
379
+ # left out reads "No reason provided".
380
+ def reason(text)
381
+ text.to_s.strip.empty? ? "No reason provided" : text.to_s.strip
382
+ end
383
+
384
+ def announce(output, text)
385
+ output&.announce(text)
386
+ end
387
+ end
388
+ end
389
+ end
@@ -0,0 +1,214 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "aws-sdk-ec2"
4
+ require_relative "../errors"
5
+ require_relative "sdk_adapters"
6
+
7
+ module RubyCdk
8
+ module Deploy
9
+ # The EC2 client behind the lookups of D-022, beside the CloudFormation
10
+ # and object-store clients of the engine in the adapters component. Only
11
+ # the lookup command loads this file (through the command line's client
12
+ # seam), so `synth` never loads the AWS SDK and a deploy never loads the
13
+ # EC2 gem.
14
+ module Sdk
15
+ # The lookup client of one region, built like every client: the region
16
+ # is passed explicitly, the profile selects credentials.
17
+ def self.ec2_client(region:, profile: nil, credentials: nil, stub_responses: false)
18
+ Ec2Client.new(region: region, profile: profile, credentials: credentials, stub_responses: stub_responses)
19
+ end
20
+
21
+ # The VPC lookups. What a query reads is shaped here, so that the
22
+ # construct that reads the cache and this client agree on one answer
23
+ # (the shape is written out in EC2::Vpc.from_lookup, and the file is
24
+ # the contract):
25
+ #
26
+ # "vpc_id" the VPC's id
27
+ # "cidr" its primary IPv4 CIDR
28
+ # "owner_account_id" the account that owns it
29
+ # "region" where it lives
30
+ # "availability_zones" the zones of its subnets, without duplicates,
31
+ # sorted
32
+ # "subnet_groups" one per non-empty reachability type, in the
33
+ # order public, private, isolated: the group's
34
+ # name (the CDK's default subnet name), its
35
+ # type, and its subnets sorted by zone and id,
36
+ # each with its subnet_id, route_table_id, cidr
37
+ # and availability_zone
38
+ #
39
+ # Every list is sorted here, so that the same VPC answers the same
40
+ # bytes on two machines and the committed cache does not churn.
41
+ class Ec2Client
42
+ # The group names a looked-up VPC answers with, the CDK's default
43
+ # subnet names in its type order (vpc.ts:1351-1376). Named here and
44
+ # not read from the construct: the adapters do not depend on the
45
+ # curated constructs, and the two lists are two halves of one file
46
+ # contract (the cache), not one shared table.
47
+ LOOKUP_TYPES = {
48
+ "public" => "Public",
49
+ "private" => "Private",
50
+ "isolated" => "Isolated"
51
+ }.freeze
52
+
53
+ # The classification of a subnet by the destination of its default
54
+ # route, as the CDK's lookup provider classifies it (aws-cdk-cli,
55
+ # the VPC context provider): a route whose gateway is an internet
56
+ # gateway is public, one whose gateway is a NAT gateway is private,
57
+ # anything else is isolated.
58
+ PUBLIC_TARGET = /\Aigw-/
59
+ PRIVATE_TARGET = /\Anat-/
60
+
61
+ attr_reader :raw
62
+
63
+ def initialize(region:, profile: nil, credentials: nil, stub_responses: false)
64
+ @profile = profile
65
+ @credentials = credentials
66
+ @stub_responses = stub_responses
67
+ @raw = Aws::EC2::Client.new(**Sdk.options_for(region: region, profile: profile,
68
+ credentials: credentials, stub_responses: stub_responses))
69
+ end
70
+
71
+ # The account the credentials are for, asked of STS with the same
72
+ # region and profile as the client, as the CloudFormation client asks
73
+ # it. The lookup command refuses a query whose env names another.
74
+ def account
75
+ Sdk.request { sts.get_caller_identity }.account
76
+ end
77
+
78
+ # The STS client, built on first use with the options the main
79
+ # client was built with, so that a test stubs it the same way.
80
+ def sts
81
+ @sts ||= Aws::STS::Client.new(**Sdk.options_for(region: region, profile: @profile,
82
+ credentials: @credentials, stub_responses: @stub_responses))
83
+ end
84
+
85
+ # The answer for one VPC query: the VPC named by vpc_id (when given),
86
+ # which must carry every tag. With neither the query matches every
87
+ # VPC of the region. One match answers; none or several refuse, in
88
+ # words that name what would disambiguate.
89
+ def lookup_vpc(vpc_id: nil, tags: {})
90
+ filters = filters_of(vpc_id, tags)
91
+ params = filters.empty? ? {} : { filters: filters }
92
+ vpcs = each_page(:describe_vpcs, params).flat_map(&:vpcs)
93
+ if vpcs.empty?
94
+ raise PreconditionError, "No VPC matches this query in #{region}: #{describe_query(vpc_id, tags)}. " \
95
+ "Nothing was cached. Check the query, and the profile and region it runs against " \
96
+ "(--profile NAME, --region NAME), then run `ruby-cdk lookup` again."
97
+ end
98
+ if vpcs.length > 1
99
+ raise PreconditionError, "The query matches #{vpcs.length} VPCs in #{region} " \
100
+ "(#{vpcs.map(&:vpc_id).sort.join(", ")}), so no single answer can be cached: " \
101
+ "#{describe_query(vpc_id, tags)}. Nothing was cached. Name the VPC with vpc_id:, or carry the " \
102
+ "query further with tags:, then run `ruby-cdk lookup` again."
103
+ end
104
+
105
+ answer(vpcs.first)
106
+ end
107
+
108
+ private
109
+
110
+ def region
111
+ @raw.config.region
112
+ end
113
+
114
+ # The EC2 filters of one query: the id, then one tag: filter per tag,
115
+ # which AWS combines with AND.
116
+ def filters_of(vpc_id, tags)
117
+ filters = []
118
+ filters << { name: "vpc-id", values: [ vpc_id ] } if vpc_id
119
+ tags.sort.each do |name, value|
120
+ filters << { name: "tag:#{name}", values: [ value ] }
121
+ end
122
+ filters
123
+ end
124
+
125
+ def describe_query(vpc_id, tags)
126
+ parts = []
127
+ parts << "vpc-id #{vpc_id}" if vpc_id
128
+ tags.sort.each { |name, value| parts << "tag #{name}=#{value}" }
129
+ parts.empty? ? "no filter at all" : parts.join(", ")
130
+ end
131
+
132
+ # Every page of one call, yielded one response at a time. The pages
133
+ # are collected first and handed to the caller's block explicitly: a
134
+ # bare yield inside a loop's or each's block yields to that block,
135
+ # not to the caller of each_page.
136
+ def each_page(operation, params, &block)
137
+ response = Sdk.request { @raw.send(operation, **params) }
138
+ pages = [ response ]
139
+ while response.next_token
140
+ response = Sdk.request { @raw.send(operation, **params, next_token: response.next_token) }
141
+ pages << response
142
+ end
143
+ pages.each(&block)
144
+ end
145
+
146
+ # The answer of one VPC: the VPC itself, every subnet of it, and
147
+ # every route table of it, the subnets classified by their routes.
148
+ def answer(vpc)
149
+ id = vpc.vpc_id
150
+ subnets = each_page(:describe_subnets, filters: [ { name: "vpc-id", values: [ id ] } ])
151
+ .flat_map(&:subnets)
152
+ .sort_by { |subnet| [ subnet.availability_zone, subnet.subnet_id ] }
153
+ tables = each_page(:describe_route_tables, filters: [ { name: "vpc-id", values: [ id ] } ])
154
+ .flat_map(&:route_tables)
155
+ routes_of = tables_of(tables)
156
+
157
+ {
158
+ "vpc_id" => id,
159
+ "cidr" => vpc.cidr_block,
160
+ "owner_account_id" => vpc.owner_id,
161
+ "region" => region,
162
+ "availability_zones" => subnets.map(&:availability_zone).uniq.sort,
163
+ "subnet_groups" => LOOKUP_TYPES.filter_map do |type, name|
164
+ group = subnets.select { |subnet| group_type(subnet, routes_of) == type }
165
+ next if group.empty?
166
+
167
+ {
168
+ "name" => name,
169
+ "type" => type,
170
+ "subnets" => group.map do |subnet|
171
+ # A subnet without an explicit association routes through
172
+ # the main table, and that is the table its answer names.
173
+ table = routes_of[subnet.subnet_id] || routes_of[:main]
174
+ {
175
+ "availability_zone" => subnet.availability_zone,
176
+ "subnet_id" => subnet.subnet_id,
177
+ "route_table_id" => table&.fetch(:table_id),
178
+ "cidr" => subnet.cidr_block
179
+ }
180
+ end
181
+ }
182
+ end
183
+ }
184
+ end
185
+
186
+ # Which route table answers for each subnet: its own association,
187
+ # else the VPC's main one, as EC2 routes a subnet without an
188
+ # explicit association through the main table.
189
+ def tables_of(route_tables)
190
+ tables = {}
191
+ route_tables.each do |table|
192
+ entry = { table_id: table.route_table_id, routes: table.routes }
193
+ table.associations.each do |association|
194
+ tables[association.subnet_id] = entry if association.subnet_id
195
+ end
196
+ tables[:main] = entry if table.associations.any?(&:main)
197
+ end
198
+ tables
199
+ end
200
+
201
+ # public, private or isolated, by the default routes of the subnet's
202
+ # table (its own, else the main one).
203
+ def group_type(subnet, tables)
204
+ routes = (tables[subnet.subnet_id] || tables[:main] || {})[:routes] || []
205
+ targets = routes.filter_map(&:gateway_id)
206
+ return "public" if targets.any? { |target| target.match?(PUBLIC_TARGET) }
207
+ return "private" if targets.any? { |target| target.match?(PRIVATE_TARGET) }
208
+
209
+ "isolated"
210
+ end
211
+ end
212
+ end
213
+ end
214
+ end
@@ -45,11 +45,19 @@ module RubyCdk
45
45
  # Exit 1. A wait reached its overall limit.
46
46
  class WaitTimedOut < RubyCdk::PreconditionError; end
47
47
 
48
+ # Exit 1. CloudFormation could not finish detecting a stack's drift, or the
49
+ # detection did not finish within the limit.
50
+ class DriftDetectionFailed < RubyCdk::PreconditionError; end
51
+
48
52
  # Exit 1. --no-rollback was given for an update whose change set replaces a
49
53
  # resource: a replaced resource cannot be recovered when there is no
50
54
  # rollback to restore it from.
51
55
  class ReplacementNeedsRollback < RubyCdk::PreconditionError; end
52
56
 
57
+ # Exit 1. A resource named for an import is not in the template, so there
58
+ # is nothing in the stack's definition to import it as.
59
+ class ImportableMissing < RubyCdk::PreconditionError; end
60
+
53
61
  # Exit 3. CloudFormation rejected the change set, or did not create it.
54
62
  class ChangeSetFailed < RubyCdk::ChangeSetRejected; end
55
63