ruby-cdk 0.1.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 (155) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +87 -0
  3. data/LICENSE +21 -0
  4. data/README.md +303 -0
  5. data/THIRD_PARTY_NOTICES.md +327 -0
  6. data/data/spec/META.json +33 -0
  7. data/data/spec/model.json.gz +0 -0
  8. data/exe/ruby-cdk +9 -0
  9. data/lib/ruby-cdk.rb +4 -0
  10. data/lib/ruby_cdk/assets/builder.rb +122 -0
  11. data/lib/ruby_cdk/assets/hasher.rb +175 -0
  12. data/lib/ruby_cdk/assets/record.rb +49 -0
  13. data/lib/ruby_cdk/assets/uploader.rb +139 -0
  14. data/lib/ruby_cdk/assets/zipper.rb +108 -0
  15. data/lib/ruby_cdk/assets.rb +116 -0
  16. data/lib/ruby_cdk/bootstrap.rb +289 -0
  17. data/lib/ruby_cdk/cfn/resource.rb +93 -0
  18. data/lib/ruby_cdk/cfn.rb +10 -0
  19. data/lib/ruby_cdk/cli/arguments.rb +41 -0
  20. data/lib/ruby_cdk/cli/aws.rb +35 -0
  21. data/lib/ruby_cdk/cli/bootstrap.rb +63 -0
  22. data/lib/ruby_cdk/cli/diff.rb +98 -0
  23. data/lib/ruby_cdk/cli/failure.rb +80 -0
  24. data/lib/ruby_cdk/cli/io.rb +70 -0
  25. data/lib/ruby_cdk/cli/list.rb +46 -0
  26. data/lib/ruby_cdk/cli/new.rb +313 -0
  27. data/lib/ruby_cdk/cli/operation.rb +124 -0
  28. data/lib/ruby_cdk/cli/pairs.rb +32 -0
  29. data/lib/ruby_cdk/cli/report.rb +118 -0
  30. data/lib/ruby_cdk/cli/selection.rb +134 -0
  31. data/lib/ruby_cdk/cli/session.rb +290 -0
  32. data/lib/ruby_cdk/cli/shell.rb +30 -0
  33. data/lib/ruby_cdk/cli/synth.rb +58 -0
  34. data/lib/ruby_cdk/cli/validate.rb +101 -0
  35. data/lib/ruby_cdk/cli.rb +242 -0
  36. data/lib/ruby_cdk/constructs/bucket.rb +191 -0
  37. data/lib/ruby_cdk/constructs/function.rb +163 -0
  38. data/lib/ruby_cdk/constructs/grant.rb +90 -0
  39. data/lib/ruby_cdk/constructs/log_group.rb +115 -0
  40. data/lib/ruby_cdk/constructs/policy_statement.rb +161 -0
  41. data/lib/ruby_cdk/constructs/queue.rb +118 -0
  42. data/lib/ruby_cdk/constructs/role.rb +282 -0
  43. data/lib/ruby_cdk/constructs/table.rb +160 -0
  44. data/lib/ruby_cdk/constructs/topic.rb +88 -0
  45. data/lib/ruby_cdk/constructs.rb +56 -0
  46. data/lib/ruby_cdk/core/app.rb +146 -0
  47. data/lib/ruby_cdk/core/construct.rb +105 -0
  48. data/lib/ruby_cdk/core/elements.rb +107 -0
  49. data/lib/ruby_cdk/core/ids.rb +117 -0
  50. data/lib/ruby_cdk/core/stack.rb +291 -0
  51. data/lib/ruby_cdk/core/stateful.rb +156 -0
  52. data/lib/ruby_cdk/core.rb +15 -0
  53. data/lib/ruby_cdk/deploy/capabilities.rb +44 -0
  54. data/lib/ruby_cdk/deploy/deployer.rb +805 -0
  55. data/lib/ruby_cdk/deploy/errors.rb +72 -0
  56. data/lib/ruby_cdk/deploy/fakes.rb +546 -0
  57. data/lib/ruby_cdk/deploy/output/base.rb +167 -0
  58. data/lib/ruby_cdk/deploy/output/human.rb +37 -0
  59. data/lib/ruby_cdk/deploy/output/json.rb +80 -0
  60. data/lib/ruby_cdk/deploy/output/quiet.rb +20 -0
  61. data/lib/ruby_cdk/deploy/parameters.rb +86 -0
  62. data/lib/ruby_cdk/deploy/poller.rb +72 -0
  63. data/lib/ruby_cdk/deploy/ports.rb +205 -0
  64. data/lib/ruby_cdk/deploy/sdk_adapters.rb +608 -0
  65. data/lib/ruby_cdk/deploy/states.rb +62 -0
  66. data/lib/ruby_cdk/deploy.rb +25 -0
  67. data/lib/ruby_cdk/diff/compare.rb +141 -0
  68. data/lib/ruby_cdk/diff/normalizer.rb +83 -0
  69. data/lib/ruby_cdk/diff/render.rb +242 -0
  70. data/lib/ruby_cdk/diff/security.rb +322 -0
  71. data/lib/ruby_cdk/diff/statement.rb +256 -0
  72. data/lib/ruby_cdk/diff/template.rb +524 -0
  73. data/lib/ruby_cdk/diff.rb +62 -0
  74. data/lib/ruby_cdk/env.rb +42 -0
  75. data/lib/ruby_cdk/errors.rb +38 -0
  76. data/lib/ruby_cdk/fn.rb +409 -0
  77. data/lib/ruby_cdk/lazy.rb +55 -0
  78. data/lib/ruby_cdk/nag/config.rb +303 -0
  79. data/lib/ruby_cdk/nag/engine.rb +152 -0
  80. data/lib/ruby_cdk/nag/report.rb +86 -0
  81. data/lib/ruby_cdk/nag/rule.rb +171 -0
  82. data/lib/ruby_cdk/nag/rules/api_gateway_authorization.rb +91 -0
  83. data/lib/ruby_cdk/nag/rules/dynamodb_point_in_time_recovery.rb +45 -0
  84. data/lib/ruby_cdk/nag/rules/ebs_volume_encrypted.rb +41 -0
  85. data/lib/ruby_cdk/nag/rules/ec2_ingress_http.rb +48 -0
  86. data/lib/ruby_cdk/nag/rules/ec2_ingress_other_ports.rb +46 -0
  87. data/lib/ruby_cdk/nag/rules/iam_policy_admin_access.rb +60 -0
  88. data/lib/ruby_cdk/nag/rules/iam_policy_full_access.rb +55 -0
  89. data/lib/ruby_cdk/nag/rules/iam_user_credentials.rb +61 -0
  90. data/lib/ruby_cdk/nag/rules/lambda_runtime_supported.rb +88 -0
  91. data/lib/ruby_cdk/nag/rules/lambda_secret_environment.rb +61 -0
  92. data/lib/ruby_cdk/nag/rules/log_group_retention.rb +40 -0
  93. data/lib/ruby_cdk/nag/rules/policy_statements.rb +128 -0
  94. data/lib/ruby_cdk/nag/rules/rds_storage_encrypted.rb +65 -0
  95. data/lib/ruby_cdk/nag/rules/resource_policy_wildcard_principal.rb +58 -0
  96. data/lib/ruby_cdk/nag/rules/s3_public_access_block.rb +56 -0
  97. data/lib/ruby_cdk/nag/rules/security_group_ingress.rb +136 -0
  98. data/lib/ruby_cdk/nag/rules/stateful_deletion_policy.rb +46 -0
  99. data/lib/ruby_cdk/nag/rules.rb +51 -0
  100. data/lib/ruby_cdk/nag/values.rb +305 -0
  101. data/lib/ruby_cdk/nag.rb +60 -0
  102. data/lib/ruby_cdk/schema/normalizer.rb +164 -0
  103. data/lib/ruby_cdk/schema/property_schema.rb +22 -0
  104. data/lib/ruby_cdk/schema/schema.rb +195 -0
  105. data/lib/ruby_cdk/schema/sources/compiler.rb +56 -0
  106. data/lib/ruby_cdk/schema/sources/descriptor.rb +21 -0
  107. data/lib/ruby_cdk/schema/sources/download.rb +86 -0
  108. data/lib/ruby_cdk/schema/sources/provider_schemas.rb +47 -0
  109. data/lib/ruby_cdk/schema/sources/provider_type.rb +630 -0
  110. data/lib/ruby_cdk/schema/sources/regions.rb +86 -0
  111. data/lib/ruby_cdk/schema/sources/resource_specification.rb +94 -0
  112. data/lib/ruby_cdk/schema/sources/specification_type.rb +159 -0
  113. data/lib/ruby_cdk/schema/sources/update.rb +178 -0
  114. data/lib/ruby_cdk/schema/sources.rb +20 -0
  115. data/lib/ruby_cdk/schema/type_schema.rb +109 -0
  116. data/lib/ruby_cdk/schema/validator/corpus_check.rb +81 -0
  117. data/lib/ruby_cdk/schema/validator/policies.rb +48 -0
  118. data/lib/ruby_cdk/schema/validator/refs.rb +489 -0
  119. data/lib/ruby_cdk/schema/validator/report.rb +92 -0
  120. data/lib/ruby_cdk/schema/validator/rule.rb +119 -0
  121. data/lib/ruby_cdk/schema/validator/scans.rb +146 -0
  122. data/lib/ruby_cdk/schema/validator/structure.rb +469 -0
  123. data/lib/ruby_cdk/schema/validator/template.rb +203 -0
  124. data/lib/ruby_cdk/schema/validator/template_rules.rb +70 -0
  125. data/lib/ruby_cdk/schema/validator/walk.rb +122 -0
  126. data/lib/ruby_cdk/schema/validator.rb +159 -0
  127. data/lib/ruby_cdk/schema.rb +19 -0
  128. data/lib/ruby_cdk/synth/manifest.rb +128 -0
  129. data/lib/ruby_cdk/synth/resolver.rb +326 -0
  130. data/lib/ruby_cdk/synth/rules.rb +83 -0
  131. data/lib/ruby_cdk/synth/serializer.rb +120 -0
  132. data/lib/ruby_cdk/synth/writer.rb +31 -0
  133. data/lib/ruby_cdk/synth.rb +255 -0
  134. data/lib/ruby_cdk/test/capture.rb +133 -0
  135. data/lib/ruby_cdk/test/match.rb +426 -0
  136. data/lib/ruby_cdk/test/matcher.rb +290 -0
  137. data/lib/ruby_cdk/test/private/absent.rb +34 -0
  138. data/lib/ruby_cdk/test/private/conditions.rb +39 -0
  139. data/lib/ruby_cdk/test/private/cyclic.rb +160 -0
  140. data/lib/ruby_cdk/test/private/error.rb +48 -0
  141. data/lib/ruby_cdk/test/private/js.rb +326 -0
  142. data/lib/ruby_cdk/test/private/mappings.rb +39 -0
  143. data/lib/ruby_cdk/test/private/outputs.rb +39 -0
  144. data/lib/ruby_cdk/test/private/parameters.rb +39 -0
  145. data/lib/ruby_cdk/test/private/resources.rb +116 -0
  146. data/lib/ruby_cdk/test/private/section.rb +98 -0
  147. data/lib/ruby_cdk/test/private/sorting.rb +40 -0
  148. data/lib/ruby_cdk/test/private/sparse_matrix.rb +35 -0
  149. data/lib/ruby_cdk/test/private/type.rb +23 -0
  150. data/lib/ruby_cdk/test/template.rb +364 -0
  151. data/lib/ruby_cdk/test.rb +116 -0
  152. data/lib/ruby_cdk/values.rb +8 -0
  153. data/lib/ruby_cdk/version.rb +5 -0
  154. data/lib/ruby_cdk.rb +47 -0
  155. metadata +256 -0
@@ -0,0 +1,805 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "ports"
5
+ require_relative "errors"
6
+ require_relative "poller"
7
+ require_relative "capabilities"
8
+ require_relative "parameters"
9
+ require_relative "states"
10
+
11
+ module RubyCdk
12
+ module Deploy
13
+ # What a deploy or a destroy may do.
14
+ class DeployOptions
15
+ attr_reader :parameters, :tags, :yes, :no_execute, :on_failure, :no_rollback, :outputs_file, :account, :force, :profile
16
+
17
+ # force deploys even when the template and the parameters are unchanged.
18
+ # profile is the name of the credential profile; it is shown on the target
19
+ # line and selects nothing here, because the client was built with it.
20
+ def initialize(parameters: {}, tags: {}, yes: false, no_execute: false, on_failure: :delete, no_rollback: false, outputs_file: nil, account: nil,
21
+ force: false, profile: nil)
22
+ @parameters = parameters
23
+ @tags = tags
24
+ @yes = yes
25
+ @no_execute = no_execute
26
+ @on_failure = on_failure
27
+ @no_rollback = no_rollback
28
+ @outputs_file = outputs_file
29
+ @account = account
30
+ @force = force
31
+ @profile = profile
32
+ end
33
+ end
34
+
35
+ # What came out of a deploy or a destroy. :destroyed is a destroy that
36
+ # deleted the stack; the CDK tells the two apart as well.
37
+ class DeployResult
38
+ OUTCOMES = %i[deployed no_changes not_executed rejected failed destroyed].freeze
39
+
40
+ attr_reader :stack_name, :stack_id, :outcome, :changes, :outputs, :exit_code
41
+
42
+ def initialize(stack_name:, outcome:, stack_id: nil, changes: [], outputs: {}, exit_code: 0)
43
+ raise ArgumentError, "unknown outcome #{outcome.inspect}" unless OUTCOMES.include?(outcome)
44
+
45
+ @stack_name = stack_name
46
+ @stack_id = stack_id
47
+ @outcome = outcome
48
+ @changes = changes
49
+ @outputs = outputs
50
+ @exit_code = exit_code
51
+ end
52
+ end
53
+
54
+ # A resource a destroy will not delete, because its DeletionPolicy keeps it.
55
+ RetainedResource = Struct.new(:logical_id, :resource_type, :deletion_policy, keyword_init: true)
56
+
57
+ # Deploys stacks through change sets and destroys them. Talks to AWS only
58
+ # through the two ports.
59
+ #
60
+ # The flow is architecture section 9. It raises for exit codes 1, 3 and 4
61
+ # and returns a DeployResult for everything else: a stack operation that
62
+ # failed or rolled back is a result with outcome :failed and exit code 5,
63
+ # after the resources that failed have been printed.
64
+ class Deployer
65
+ # Change set names are unique per stack, so the one a previous --no-execute
66
+ # left behind is removed before a new one takes its name.
67
+ CHANGE_SET_NAME = "ruby-cdk-deploy-change-set"
68
+
69
+ # CloudFormation takes at most this many bytes of template in a request.
70
+ INLINE_TEMPLATE_LIMIT = 51_200
71
+
72
+ # OnStackFailure, by the name of the option, in either case.
73
+ ON_FAILURE = { "delete" => "DELETE", "rollback" => "ROLLBACK", "do_nothing" => "DO_NOTHING" }.freeze
74
+
75
+ # A change set in one of these is still being created.
76
+ CREATING_STATUSES = %w[CREATE_PENDING CREATE_IN_PROGRESS].freeze
77
+
78
+ # The reasons CloudFormation gives when a change set has nothing to do,
79
+ # matched as prefixes, as the CDK matches them (changeSetHasNoChanges):
80
+ # the two the CDK reads, and the code of its early validation.
81
+ NO_CHANGE_REASONS = [
82
+ "The submitted information didn't contain changes.",
83
+ "No updates are to be performed.",
84
+ "NoChangesInUpdateSet"
85
+ ].freeze
86
+
87
+ # Right after an execution DescribeStacks can still answer the status
88
+ # from before it. The CDK gives that read three chances to catch up.
89
+ STALE_REVIEW_READS = 3
90
+
91
+ # A creation that failed and rolled back this far. The next deploy deletes the stack first.
92
+ FAILED_CREATION_STATUSES = %w[ROLLBACK_COMPLETE ROLLBACK_FAILED].freeze
93
+
94
+ # The statuses in which an operation SUCCEEDED. It is not the same
95
+ # question as whether the stack is stable: UPDATE_ROLLBACK_COMPLETE is a
96
+ # stable stack, one that can be updated again, and it is how an update
97
+ # that failed ends. This is the CDK's isDeploySuccess.
98
+ DEPLOYED_STATUSES = %w[CREATE_COMPLETE UPDATE_COMPLETE IMPORT_COMPLETE].freeze
99
+
100
+ # The stack itself, in its own events.
101
+ STACK_TYPE = "AWS::CloudFormation::Stack"
102
+
103
+ # The DeletionPolicy values under which a deleted stack leaves a resource behind.
104
+ RETAINING_POLICIES = %w[Retain RetainExceptOnCreate Snapshot].freeze
105
+
106
+ # poller waits for a change set to be created; operation_poller follows a
107
+ # stack operation. Both take a Poller, so a test never waits.
108
+ # template_publisher places a template that does not fit a request in the
109
+ # stack's asset bucket: a callable of (stack, template body) that answers
110
+ # the URL to deploy by (architecture §8). The command line wires it; nil,
111
+ # and a template above the limit is refused before any request.
112
+ def initialize(client:, store:, output:, poller: Poller.change_set, operation_poller: Poller.operation, template_publisher: nil)
113
+ @client = client
114
+ @store = store
115
+ @output = output
116
+ @poller = poller
117
+ @operation_poller = operation_poller
118
+ @template_publisher = template_publisher
119
+ @events_unavailable = false
120
+ end
121
+
122
+ # stack is the stack: anything that answers stack_name, env,
123
+ # termination_protection and tags. template is the template as JSON text.
124
+ # identity is who the credentials are for, from the client.
125
+ def deploy(stack:, template:, identity:, options:)
126
+ name = stack.stack_name
127
+ check_account(name, stack, identity, options)
128
+
129
+ body = parse_template(template)
130
+ ensure_template_placeable(template)
131
+ on_failure = on_failure_code(options.on_failure)
132
+ capabilities = Capabilities.for(body)
133
+ tags = tags_of(stack.tags, options.tags)
134
+
135
+ show_target(identity, options)
136
+
137
+ state, info = prepare_stack(name, client.stack_state(name))
138
+ # The parameters are built once the stack has been looked up, as the
139
+ # CDK builds them after its lookup: a parameter that is not given again
140
+ # keeps the value the stack has (UsePreviousValue), so a NoEcho value
141
+ # comes back masked and is sent back masked, and a deploy with nothing
142
+ # new is recognised as such. With no stack, a parameter without a value
143
+ # or a default is an error.
144
+ deployed_parameters = info ? client.stack_parameters(info.id || name) : nil
145
+ parameters = Parameters.new(body, options.parameters, deployed: deployed_parameters)
146
+
147
+ if state == :stable && unchanged?(name, info, body, parameters, tags, options, deployed_parameters)
148
+ reconcile_protection(info.id || name, info.termination_protection, stack.termination_protection)
149
+ deliver_outputs(info, options, name)
150
+ return DeployResult.new(stack_name: name, stack_id: info.id, outcome: :no_changes, outputs: outputs_of(info))
151
+ end
152
+
153
+ # A template too large for a request is placed in the bucket, and the
154
+ # change set carries its URL instead of its body. It is placed here, once
155
+ # a change set is actually coming: a deploy that has nothing to do never
156
+ # reaches this line, so the bytes are not uploaded for it.
157
+ template_url = place_template(stack, template)
158
+ creating = %i[absent review].include?(state)
159
+ output.announce("#{name}: #{creating ? "creating" : "updating"}: preparing a CloudFormation change set...")
160
+ unless state == :absent
161
+ # The name of a change set is unique per stack while it exists, so the
162
+ # one deleted here is waited for, as the CDK waits for it ("deleting
163
+ # may take a bit"): taking the name too early is an AlreadyExists error.
164
+ client.delete_change_set(name, CHANGE_SET_NAME)
165
+ wait_for_change_set_gone(name, CHANGE_SET_NAME)
166
+ end
167
+
168
+ change_set = change_set_with_rejection(name, nil, creating) do
169
+ client.create_change_set(name, CHANGE_SET_NAME, template: template_url ? nil : template,
170
+ change_set_type: creating ? :create : :update, parameters: parameters.api, tags: tags, capabilities: capabilities,
171
+ on_stack_failure: creating ? on_failure : nil, template_url: template_url)
172
+ end
173
+ change_set = wait_for_change_set(name, change_set.id)
174
+
175
+ # The stack exists from here on, with an ID of its own. Later calls use
176
+ # the ID, which still names the stack when it has been deleted.
177
+ current = info || client.stack_info(name)
178
+ target = current&.id || name
179
+ wanted_protection = !!stack.termination_protection
180
+
181
+ if no_changes?(change_set)
182
+ # An empty change set is left for the console under --no-execute and
183
+ # deleted otherwise, as the CDK leaves and deletes it
184
+ # (deploy-stack.ts, changeSetHasNoChanges).
185
+ if options.no_execute
186
+ output.announce("#{name}: CloudFormation reports that the change set would change nothing. " \
187
+ "It was left unexecuted (--no-execute), and the console can delete it.")
188
+ else
189
+ client.delete_change_set(name, change_set.id)
190
+ output.announce("#{name}: no changes to deploy. CloudFormation reports that the change set is empty." +
191
+ (options.force ? " --force was given, but the template and the parameters lead to no change." : ""))
192
+ end
193
+ reconcile_protection(target, current&.termination_protection, wanted_protection)
194
+ deliver_outputs(current, options, name)
195
+ return DeployResult.new(stack_name: name, stack_id: current&.id,
196
+ outcome: options.no_execute ? :not_executed : :no_changes, outputs: outputs_of(current))
197
+ end
198
+
199
+ changes = changes_of(change_set)
200
+
201
+ unless executable?(change_set)
202
+ detail = rejection_detail(name, change_set)
203
+ output.failure(detail)
204
+ raise ChangeSetFailed, "#{detail}#{discard(name, change_set.id, creating, false)}"
205
+ end
206
+
207
+ output.changes(changes, capabilities: capabilities)
208
+ reconcile_protection(target, current&.termination_protection, wanted_protection)
209
+
210
+ if options.no_execute
211
+ output.announce("#{name}: the change set #{change_set.id} was created and left unexecuted (--no-execute). " \
212
+ "Execute it in the CloudFormation console, or run the command again without --no-execute.")
213
+ return DeployResult.new(stack_name: name, stack_id: current&.id, outcome: :not_executed, changes: changes,
214
+ outputs: outputs_of(current))
215
+ end
216
+
217
+ refuse_replacement(name, changes, options, creating)
218
+
219
+ unless approved?(options, "Deploy these changes to stack #{name} in account #{identity.account} (#{identity.region})?")
220
+ raise ApprovalRequired, "Approval for the changes to stack #{name} was not given, so nothing was deployed. " \
221
+ "The change set was deleted#{creating ? ", with the new stack" : ""}." \
222
+ "#{discard(name, change_set.id, creating, creating && wanted_protection)}" \
223
+ "\nRun the command again in a terminal to approve it, or with --yes to deploy without asking."
224
+ end
225
+
226
+ change_set_with_rejection(name, change_set.id, creating, was_protected: creating && wanted_protection) do
227
+ # A creation carries OnStackFailure instead, and the two cannot go together.
228
+ client.execute_change_set(target, change_set.id, disable_rollback: !creating && options.no_rollback,
229
+ retain_except_on_create: true)
230
+ end
231
+
232
+ final_state, final_info, events, problem = follow_operation(target, name)
233
+ if final_state == :stable && (final_info.nil? || DEPLOYED_STATUSES.include?(final_info.status))
234
+ deliver_outputs(final_info, options, name)
235
+ return DeployResult.new(stack_name: name, stack_id: final_info&.id || target, outcome: :deployed, changes: changes,
236
+ outputs: outputs_of(final_info))
237
+ end
238
+
239
+ output.failure(operation_failure(name, final_state, final_info, events, :deploy, problem))
240
+ DeployResult.new(stack_name: name, stack_id: final_state == :absent ? nil : (final_info&.id || target),
241
+ outcome: :failed, changes: changes, exit_code: 5)
242
+ end
243
+
244
+ def destroy(stack:, identity:, options:)
245
+ name = stack.stack_name
246
+ # The account rule holds for a destroy as for a deploy: a stack with an
247
+ # env is destroyed only there (section 13).
248
+ check_account(name, stack, identity, options)
249
+ show_target(identity, options)
250
+
251
+ state = client.stack_state(name)
252
+ info = state == :absent ? nil : client.stack_info(name)
253
+ if info.nil?
254
+ output.announce("Stack #{name} does not exist: nothing to destroy.")
255
+ return DeployResult.new(stack_name: name, outcome: :no_changes)
256
+ end
257
+ raise StackBusy, busy_message(name, info.status) if state == :busy
258
+
259
+ if info.termination_protection
260
+ raise DestroyRefused, "Stack #{name} has termination protection, so destroy refuses to delete it. Nothing was deleted.\n" \
261
+ "Turn it off first (set termination_protection: false on the stack and deploy, or in the CloudFormation console: " \
262
+ "Stack actions, then Edit termination protection), then run `ruby-cdk destroy #{name}` again."
263
+ end
264
+
265
+ target = info.id || name
266
+ output.retained(retained_resources(name, client.get_template(target)))
267
+ unless options.yes == true || output.confirm(name) == true
268
+ raise ApprovalRequired, "The name of stack #{name} was not typed, so nothing was deleted.\n" \
269
+ "Run the command again and type the stack name when asked, or with --yes to destroy without asking."
270
+ end
271
+
272
+ client.delete_stack(target)
273
+ final_state, final_info, events, problem = follow_operation(target, name)
274
+ if final_state == :absent
275
+ return DeployResult.new(stack_name: name, stack_id: info.id, outcome: :destroyed)
276
+ end
277
+
278
+ output.failure(operation_failure(name, final_state, final_info || info, events, :destroy, problem))
279
+ DeployResult.new(stack_name: name, stack_id: final_info&.id || info.id, outcome: :failed, exit_code: 5)
280
+ end
281
+
282
+ private
283
+
284
+ attr_reader :client, :store, :output, :poller, :operation_poller, :template_publisher
285
+
286
+ # --- section 13: who the credentials are for, and where the stack may go
287
+
288
+ # Nothing here falls back: every mismatch is refused before any request.
289
+ def check_account(name, stack, identity, options)
290
+ check_identity(identity, options)
291
+
292
+ env = stack.env
293
+ if concrete?(env)
294
+ if identity.account.to_s != env.account.to_s
295
+ raise TargetMismatch, "The credentials are for account #{identity.account}, but stack #{name} has env " \
296
+ "#{env.account}/#{env.region}. A stack with an env deploys only there. Nothing was deployed.\n" \
297
+ "Run the command again with a profile of account #{env.account} (--profile NAME), or change the stack's env."
298
+ end
299
+ if identity.region.to_s != env.region.to_s
300
+ raise TargetMismatch, "The client is for region #{identity.region}, but stack #{name} has env " \
301
+ "#{env.account}/#{env.region}. A stack with an env deploys only there. Nothing was deployed.\n" \
302
+ "Run the command again with --region #{env.region}, or change the stack's env."
303
+ end
304
+ return
305
+ end
306
+
307
+ return unless options.yes && options.account.nil?
308
+
309
+ raise AccountRequired, "An unattended deploy (--yes) of stack #{name}, which has no env, needs --account: " \
310
+ "nobody is there to see the target. The credentials are for account #{identity.account} in #{identity.region}.\n" \
311
+ "Run the command again with --account #{identity.account} if that is the account you mean, or give the stack an env."
312
+ end
313
+
314
+ def check_identity(identity, options)
315
+ if identity.nil? || identity.account.to_s.empty?
316
+ raise AccountUnresolved, "No account could be resolved from the credentials, so there is no target to deploy to. Nothing was changed.\n" \
317
+ "Check the profile and the credentials (--profile NAME), then run the command again."
318
+ end
319
+
320
+ return if options.account.nil? || options.account.to_s == identity.account.to_s
321
+
322
+ raise AccountMismatch, "--account #{options.account} was given, but the credentials are for account #{identity.account}. Nothing was changed.\n" \
323
+ "Run the command again without --account, or with --account #{identity.account} if that is the account you mean " \
324
+ "and the credentials are the ones that are wrong (--profile NAME)."
325
+ end
326
+
327
+ # An env with both an account and a region.
328
+ def concrete?(env)
329
+ !env.nil? && env.respond_to?(:account) && env.respond_to?(:region) && !env.account.to_s.empty? && !env.region.to_s.empty?
330
+ end
331
+
332
+ def show_target(identity, options)
333
+ output.target(account: identity.account, region: identity.region, profile: options.profile)
334
+ end
335
+
336
+ # --- the template, before any request
337
+
338
+ def parse_template(template)
339
+ body = JSON.parse(template)
340
+ raise InvalidTemplate, "The template is not a JSON object, so it cannot be deployed." unless body.is_a?(Hash)
341
+
342
+ body
343
+ rescue JSON::ParserError, TypeError
344
+ raise InvalidTemplate, "The template is not valid JSON, so CloudFormation cannot take it. Synthesize the stack again."
345
+ end
346
+
347
+ # Above the inline limit the template can only deploy from the bucket, by
348
+ # its URL (architecture §8). Without the publisher that places it there,
349
+ # there is no way in, and the deploy is refused here, before any request.
350
+ def ensure_template_placeable(template)
351
+ return if template.bytesize <= INLINE_TEMPLATE_LIMIT || template_publisher
352
+
353
+ raise TemplateTooLarge, "The template is #{template.bytesize} bytes, and CloudFormation takes at most " \
354
+ "#{INLINE_TEMPLATE_LIMIT} bytes in a request, so it cannot be sent in the request itself. Nothing was deployed.\n" \
355
+ "A template of this size is placed in the stack's asset bucket first, and the change set then carries the " \
356
+ "file's address instead of the template. To do that, the deployer has to be built with a template publisher " \
357
+ "that places the template in the bucket and answers its address; the `ruby-cdk deploy` command wires one. " \
358
+ "A template that fits in the request needs no publisher."
359
+ end
360
+
361
+ # The address to deploy a template by, or nil when it goes in the request.
362
+ # The engine knows the publisher only as the callable the command line
363
+ # wired; which bucket the template lands in is its business, not this one.
364
+ def place_template(stack, template)
365
+ return nil if template.bytesize <= INLINE_TEMPLATE_LIMIT
366
+
367
+ template_publisher.call(stack, template)
368
+ end
369
+
370
+ def on_failure_code(value)
371
+ ON_FAILURE[value.to_s.downcase] ||
372
+ raise(RubyCdk::UsageError, "--on-failure must be one of DELETE, ROLLBACK or DO_NOTHING, not #{value.inspect}.")
373
+ end
374
+
375
+ # --- the stack's state
376
+
377
+ # Refuses the states nothing can be done in, removes a failed creation,
378
+ # and answers [state, stack info] with info nil when the stack is absent.
379
+ def prepare_stack(name, state)
380
+ info = state == :absent ? nil : client.stack_info(name)
381
+ return [ :absent, nil ] unless info
382
+
383
+ case state
384
+ when :busy
385
+ raise StackBusy, busy_message(name, info.status)
386
+ when :rollback_failed
387
+ raise StackNeedsRepair, "Stack #{name} is in #{info.status} and has to be repaired before it can be deployed again. " \
388
+ "Nothing was changed. #{States.repair_path(info.status)}"
389
+ when :rollback_complete
390
+ output.announce("#{name}: the stack is in #{info.status}, so its first deploy failed and rolled back. " \
391
+ "Deleting it, then creating it again.")
392
+ client.delete_stack(info.id || name)
393
+ final = wait_settled(info.id || name, "its deletion")
394
+ return [ :absent, nil ] if final == :absent
395
+
396
+ status = client.stack_info(info.id || name)&.status
397
+ raise StackNeedsRepair, "Stack #{name} could not be deleted: it is in #{status || final}. Nothing was deployed. " \
398
+ "#{States.repair_path(status)}"
399
+ end
400
+
401
+ [ state, info ]
402
+ end
403
+
404
+ def busy_message(name, status)
405
+ "Stack #{name} is #{status || "busy"}: an operation is already running on it, and two at once is not possible. " \
406
+ "Nothing was changed.\nWait for it to finish (the CloudFormation console shows it), then run the command again."
407
+ end
408
+
409
+ # Sleeps until the stack is no longer busy. Answers the state it settled in.
410
+ def wait_settled(target, what)
411
+ polling(operation_poller, "the stack did not finish #{what}") do
412
+ state = client.stack_state(target)
413
+ state unless state == :busy
414
+ end
415
+ end
416
+
417
+ # --- section 9: unchanged means skipped
418
+
419
+ # Only a template that parses as JSON, and parameters and tags that match,
420
+ # prove that nothing changed. Anything else deploys, and the change set says so.
421
+ #
422
+ # YAML is not read, on purpose. This engine always sends JSON, so a stack
423
+ # holds a YAML template only when another tool deployed it. How
424
+ # CloudFormation types a YAML value is not something to guess at, and it
425
+ # is the Wave 2 port of the cloudformation-include yaml cases that reads
426
+ # it. Until then such a stack is not skipped: its change set is created,
427
+ # CloudFormation answers that there is nothing to do, and the deploy ends
428
+ # with exit 0 one request later.
429
+ def unchanged?(name, info, body, parameters, tags, options, deployed_parameters)
430
+ return false if options.force || options.no_execute || parameters.resolved_by_cloud_formation?
431
+
432
+ deployed = JSON.parse(client.get_template(info.id || name).to_s)
433
+ return false unless deployed == body
434
+ return false if parameters.changes?(deployed_parameters)
435
+
436
+ tag_pairs(client.stack_tags(info.id || name)) == tag_pairs(tags)
437
+ rescue JSON::ParserError, TypeError
438
+ false
439
+ end
440
+
441
+ # --- change sets
442
+
443
+ # CloudFormation can refuse a change set when the request is made, or when
444
+ # it is executed. The adapter raises RubyCdk::ChangeSetRejected then; the
445
+ # engine cleans up after a creation and reports it with everything else
446
+ # it rejects. was_protected says whether the new stack was protected.
447
+ def change_set_with_rejection(name, change_set_id, creating, was_protected: false)
448
+ yield
449
+ rescue RubyCdk::ChangeSetRejected => e
450
+ raise ChangeSetFailed, "#{e.message}#{discard(name, change_set_id, creating, was_protected)}"
451
+ end
452
+
453
+ def wait_for_change_set(name, change_set_id)
454
+ polling(poller, "CloudFormation did not finish creating the change set for stack #{name}") do
455
+ described = client.describe_change_set(name, change_set_id)
456
+ described unless CREATING_STATUSES.include?(described.status)
457
+ end
458
+ end
459
+
460
+ # A change set that is gone answers as deleted or is not found at all;
461
+ # anything else keeps being asked, until the change-set poller gives up.
462
+ def wait_for_change_set_gone(name, change_set_id)
463
+ polling(poller, "CloudFormation did not finish deleting the earlier change set of stack #{name}") do
464
+ described = begin
465
+ client.describe_change_set(name, change_set_id)
466
+ rescue RubyCdk::PreconditionError => e
467
+ raise unless /not found/i.match?(e.message)
468
+
469
+ :gone
470
+ end
471
+ :gone if described == :gone || %w[DELETE_COMPLETE DELETE_FAILED].include?(described.status)
472
+ end
473
+ end
474
+
475
+ def no_changes?(change_set)
476
+ if change_set.status == "CREATE_COMPLETE"
477
+ return changes_of(change_set).empty?
478
+ end
479
+
480
+ reason = change_set.status_reason.to_s
481
+ change_set.status == "FAILED" && NO_CHANGE_REASONS.any? { |known| reason.start_with?(known) }
482
+ end
483
+
484
+ def executable?(change_set)
485
+ change_set.status == "CREATE_COMPLETE" && [ nil, "AVAILABLE" ].include?(change_set.execution_status)
486
+ end
487
+
488
+ def changes_of(change_set)
489
+ change_set.changes || []
490
+ end
491
+
492
+ def rejection_detail(name, change_set)
493
+ head = if change_set.status == "FAILED"
494
+ "CloudFormation rejected the change set for stack #{name}: #{change_set.status_reason}"
495
+ else
496
+ "The change set for stack #{name} cannot be executed (#{change_set.status}, " \
497
+ "#{change_set.execution_status || "no execution status"}): #{change_set.status_reason}"
498
+ end
499
+ lines = [ head ]
500
+ operation_events(name, change_set.id).each do |event|
501
+ lines << " #{event.logical_id} (#{event.resource_type}) #{event.resource_status}: #{event.status_reason}"
502
+ end
503
+ lines << "Correct the cause and run `ruby-cdk deploy #{name}` again."
504
+ lines.join("\n")
505
+ end
506
+
507
+ # The early validation events, when the client can read them. When it
508
+ # cannot, the answer is empty and the reason is still reported.
509
+ def operation_events(name, change_set_id)
510
+ return [] unless client.respond_to?(:operation_events)
511
+
512
+ Array(client.operation_events(name, change_set_id))
513
+ rescue NotImplementedError, StandardError
514
+ []
515
+ end
516
+
517
+ # Housekeeping. A change set that is not going to be executed is deleted,
518
+ # and so is the stack a creation made. was_protected says whether that
519
+ # stack was protected from deletion, which then has to be lifted first.
520
+ # Answers a note when the cleanup did not finish, and nil when it did.
521
+ def discard(name, change_set_id, creating, was_protected)
522
+ client.delete_change_set(name, change_set_id) if change_set_id
523
+ if creating && client.stack_state(name) == :review
524
+ client.update_termination_protection(name, enabled: false) if was_protected
525
+ client.delete_stack(name)
526
+ wait_settled(name, "its deletion")
527
+ end
528
+ nil
529
+ rescue StandardError => e
530
+ "\nThe cleanup after that did not finish (#{e.message}). Look at stack #{name} in the CloudFormation console " \
531
+ "and remove what is left of it before deploying it again."
532
+ end
533
+
534
+ # A change set that replaces a resource is not executed with rollback
535
+ # disabled, as the CDK refuses it (deploy-stack.ts,
536
+ # checkAndExecuteChangeSet): the point of --no-rollback is to keep what a
537
+ # failed operation has provisioned, and a resource that is being replaced
538
+ # is not kept. Nothing is executed, and the way in is to drop the flag.
539
+ def refuse_replacement(name, changes, options, creating)
540
+ return if creating || !options.no_rollback
541
+
542
+ replacing = changes.reject { |change| change.replacement.nil? || change.replacement == "False" }
543
+ return if replacing.empty?
544
+
545
+ names = replacing.map(&:logical_id).join(", ")
546
+ raise ReplacementNeedsRollback, "Stack #{name}: --no-rollback was given, and the change set replaces #{names}. " \
547
+ "A resource that is replaced cannot be recovered when the update fails, because with rollback disabled " \
548
+ "there is nothing to restore it from. Nothing was executed.\n" \
549
+ "Run `ruby-cdk deploy #{name}` again without --no-rollback to deploy this change with rollback, " \
550
+ "or with --no-execute to create the change set and read what replaces what first."
551
+ end
552
+
553
+ def reconcile_protection(target, current, wanted)
554
+ # A wish that is not set counts as false, so a stack that stops asking
555
+ # loses the protection on the next deploy. The CDK reconciles the same
556
+ # way (deploy-stack.ts, updateTerminationProtection:
557
+ # `terminationProtection ?? false`).
558
+ wanted = !!wanted
559
+ return if !!current == wanted
560
+
561
+ client.update_termination_protection(target, enabled: wanted)
562
+ end
563
+
564
+ # Whether a deploy may go ahead without a person: --yes, or a yes to the
565
+ # question. Both have to be exactly true: anything else an output answers
566
+ # is not an approval, and an approval given by accident is the worst thing
567
+ # this engine can do.
568
+ def approved?(options, question)
569
+ options.yes == true || output.ask(question) == true
570
+ end
571
+
572
+ # --- an operation in progress
573
+
574
+ # Follows the operation from its start to a terminal status, printing
575
+ # every event as it arrives. Answers [state, stack info, events, problem]:
576
+ # the info is nil when the stack is gone, and problem carries the error
577
+ # when the status could not be placed.
578
+ def follow_operation(target, name)
579
+ seen = {}
580
+ events = []
581
+ stale_reviews = 0
582
+ @events_unavailable = false
583
+ @newest_event = nil
584
+
585
+ settled = polling(operation_poller, "the operation on stack #{name} did not finish") do
586
+ read_events(target, seen, events, name)
587
+ current = begin
588
+ client.stack_state(target)
589
+ rescue RubyCdk::PreconditionError => e
590
+ # A status this tool cannot place ends the wait as an operation
591
+ # failure (exit 5) instead of escaping as exit 1: the operation that
592
+ # was under way is what to report. Anything else, a throttling blip
593
+ # among them, keeps being retried.
594
+ raise unless /does not know how to place/.match?(e.message)
595
+
596
+ [ :unreadable, e ]
597
+ end
598
+ case current
599
+ when Array then current
600
+ when :busy
601
+ stale_reviews = 0
602
+ nil
603
+ when :review
604
+ # Right after an execution the status from before it can still be read.
605
+ stale_reviews += 1
606
+ stale_reviews <= STALE_REVIEW_READS ? nil : [ current, nil ]
607
+ else
608
+ [ current, nil ]
609
+ end
610
+ end
611
+ state = settled.first
612
+ problem = settled.last
613
+ read_events(target, seen, events, name)
614
+
615
+ info = nil
616
+ if state != :absent && state != :unreadable
617
+ begin
618
+ info = client.stack_info(target)
619
+ rescue StandardError => e
620
+ # DescribeStacks blipped after the status had settled: the deploy
621
+ # still stands, and only its outputs are missing.
622
+ output.announce("The final state of stack #{name} could not be described (#{e.message}); " \
623
+ "its status had already settled as #{state}, and the outputs could not be read.")
624
+ end
625
+ end
626
+ [ state, info, events, problem ]
627
+ end
628
+
629
+ # Prints the events that have not been read yet. The first read leaves the
630
+ # moment to the client; the next ones ask for what is newer than the last
631
+ # event read, which is kept between the reads of one operation.
632
+ def read_events(target, seen, events, name)
633
+ return if @events_unavailable
634
+
635
+ client.events(target, after: @newest_event).sort_by { |event| event.timestamp || Time.at(0) }.each do |event|
636
+ next if seen[event]
637
+
638
+ seen[event] = true
639
+ events << event
640
+ output.event(event)
641
+ timestamp = event.timestamp
642
+ @newest_event = timestamp if timestamp && (@newest_event.nil? || timestamp > @newest_event)
643
+ end
644
+ rescue StandardError => e
645
+ @events_unavailable = true
646
+ output.announce("The events of stack #{name} could not be read (#{e.message}), so they are not shown. " \
647
+ "The stack's status is still followed.")
648
+ end
649
+
650
+ # Why an operation this engine started did not end well, with the
651
+ # resources that failed and the command to run next. purpose is :deploy
652
+ # or :destroy. problem is the error that stopped the wait, when there was
653
+ # one.
654
+ def operation_failure(name, state, info, events, purpose, problem = nil)
655
+ lines = [ failure_head(name, state, info&.status, purpose, problem) ]
656
+ failed = failed_resources(events)
657
+ if failed.any?
658
+ lines << "Resources that failed:"
659
+ failed.each { |logical_id, (resource_type, resource_status, reason)| lines << " #{logical_id} (#{resource_type}) #{resource_status}: #{reason}" }
660
+ else
661
+ lines << "No resource reported a failure in the events that were read. Read the stack's events in the CloudFormation console."
662
+ end
663
+ lines.join("\n")
664
+ end
665
+
666
+ # The first lines of a failure: what happened and what to do next.
667
+ def failure_head(name, state, status, purpose, problem = nil)
668
+ if state == :unreadable
669
+ return "The status of stack #{name} could not be placed or read while the operation was under way " \
670
+ "(#{problem&.message || "CloudFormation stopped answering"}). The operation went on in AWS.\n" \
671
+ "Look at the stack in the CloudFormation console, then run the command again."
672
+ end
673
+
674
+ if purpose == :destroy
675
+ if state == :review
676
+ return "Stack #{name} is still in REVIEW_IN_PROGRESS: the deletion did not start.\n" \
677
+ "Look at the stack in the CloudFormation console, then run the command again."
678
+ end
679
+
680
+ way_out = States.repair_path(status) ||
681
+ "Look at the stack in the CloudFormation console, fix what blocks the deletion, and run `ruby-cdk destroy #{name}` again."
682
+ return "Stack #{name} could not be deleted: it ended in #{status}.\n#{way_out}"
683
+ end
684
+
685
+ case state
686
+ when :absent
687
+ "Stack #{name} is gone: its creation failed, and CloudFormation deleted it as its change set asked.\n" \
688
+ "Fix the cause and run `ruby-cdk deploy #{name}` again."
689
+ when :review
690
+ "Stack #{name} is still in REVIEW_IN_PROGRESS: the execution of its change set did not start.\n" \
691
+ "Look at the stack in the CloudFormation console, then run the command again."
692
+ else
693
+ failed_status(name, status)
694
+ end
695
+ end
696
+
697
+ # For a deploy that ended in a status that is not a stable one.
698
+ def failed_status(name, status)
699
+ head, next_step =
700
+ if (repair = States.repair_path(status))
701
+ [ "Stack #{name} ended in #{status}, and has to be repaired before it can be deployed again.", repair ]
702
+ elsif FAILED_CREATION_STATUSES.include?(status)
703
+ [ "Stack #{name} ended in #{status}: its creation failed and was rolled back.",
704
+ "Fix the cause and run `ruby-cdk deploy #{name}` again: the failed stack is deleted and created again." ]
705
+ else
706
+ [ "Stack #{name} ended in #{status}: the operation was rolled back.", "Fix the cause and run `ruby-cdk deploy #{name}` again." ]
707
+ end
708
+ "#{head}\n#{next_step}"
709
+ end
710
+
711
+ # { logical id => [ resource type, status, reason ] }, from the last
712
+ # failure of each resource. The stack's own events are left out: they
713
+ # summarise the resources.
714
+ def failed_resources(events)
715
+ events.select { |event| event.resource_status.to_s.end_with?("_FAILED") && event.resource_type != STACK_TYPE }
716
+ .group_by(&:logical_id)
717
+ .transform_values { |list| last = list.last; [ last.resource_type, last.resource_status, last.status_reason ] }
718
+ end
719
+
720
+ def polling(waiter, description)
721
+ waiter.run { yield }
722
+ rescue WaitTimedOut
723
+ raise WaitTimedOut, "Stopped waiting: #{description} within the limit of #{waiter.limit} seconds. " \
724
+ "Nothing was changed by stopping; the operation goes on in AWS.\n" \
725
+ "Look at the stack in the CloudFormation console and run the command again once it has finished."
726
+ end
727
+
728
+ # --- outputs
729
+
730
+ def outputs_of(info)
731
+ info&.outputs || {}
732
+ end
733
+
734
+ # The file holds every stack of the command, as { stack name => outputs },
735
+ # which is how the CDK accumulates it (cdk-toolkit.ts): what was written
736
+ # for another stack stays, and a deploy with nothing to say leaves the
737
+ # file alone but for its own entry.
738
+ def deliver_outputs(info, options, name)
739
+ outputs = outputs_of(info)
740
+ output.outputs(outputs)
741
+ return unless options.outputs_file
742
+
743
+ written = begin
744
+ JSON.parse(File.read(options.outputs_file))
745
+ rescue StandardError
746
+ {}
747
+ end
748
+ File.write(options.outputs_file, "#{JSON.pretty_generate(written.merge(name => outputs))}\n")
749
+ rescue StandardError => e
750
+ # The deploy stood; a file that cannot be written must not undo it.
751
+ output.announce("The deploy succeeded, but the outputs could not be written to " \
752
+ "#{options.outputs_file} (#{e.message}). They were printed above.")
753
+ end
754
+
755
+ # --- tags
756
+
757
+ # The stack's own tags, with the command's on top of them.
758
+ def tags_of(*sources)
759
+ merged = {}
760
+ sources.each do |source|
761
+ entries_of(source).each { |key, value| merged[key.to_s] = value.to_s }
762
+ end
763
+ merged.map { |key, value| { key: key, value: value } }
764
+ end
765
+
766
+ def tag_pairs(tags)
767
+ entries_of(tags).map { |key, value| [ key.to_s, value.to_s ] }.sort
768
+ end
769
+
770
+ # [key, value] pairs from a Hash, from { key:, value: } hashes, or from pairs.
771
+ def entries_of(tags)
772
+ case tags
773
+ when Hash then tags.to_a
774
+ when Array
775
+ tags.map do |tag|
776
+ if tag.is_a?(Hash)
777
+ [ tag[:key] || tag["key"], tag[:value] || tag["value"] ]
778
+ else
779
+ Array(tag)
780
+ end
781
+ end
782
+ else []
783
+ end
784
+ end
785
+
786
+ # --- destroy
787
+
788
+ # The resources the stack's template keeps when the stack is deleted.
789
+ def retained_resources(name, template_text)
790
+ body = JSON.parse(template_text.to_s)
791
+ resources = body.is_a?(Hash) && body["Resources"].is_a?(Hash) ? body["Resources"] : {}
792
+ resources.filter_map do |logical_id, resource|
793
+ policy = resource.is_a?(Hash) ? resource["DeletionPolicy"] : nil
794
+ next unless RETAINING_POLICIES.include?(policy)
795
+
796
+ RetainedResource.new(logical_id: logical_id, resource_type: resource["Type"], deletion_policy: policy)
797
+ end.sort_by(&:logical_id)
798
+ rescue JSON::ParserError, TypeError
799
+ output.announce("The deployed template of stack #{name} is not JSON this tool can read, so the resources it retains " \
800
+ "could not be listed. Read its DeletionPolicy values in the CloudFormation console before confirming.")
801
+ []
802
+ end
803
+ end
804
+ end
805
+ end