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,608 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "aws-sdk-cloudformation"
4
+ require "aws-sdk-s3"
5
+ require_relative "../errors"
6
+ require_relative "ports"
7
+
8
+ module RubyCdk
9
+ module Deploy
10
+ # The AWS SDK behind the two ports. This is the only file in the gem that
11
+ # knows an Aws:: client exists: a command loads it on its own, and `synth`
12
+ # never does.
13
+ #
14
+ # It knows the ports and the error classes, and nothing of the engine. What
15
+ # it raises is what a component that did not raise it can recognise: the
16
+ # classes in errors.rb. The engine rescues those.
17
+ module Sdk
18
+ # The two clients a command needs: cfn answers CfnClient, store answers ObjectStore.
19
+ Clients = Data.define(:cfn, :store)
20
+
21
+ # Exit 1. AWS refused a request, or could not be reached. code is the
22
+ # error code AWS answered with, or nil when there was no answer.
23
+ class RequestFailed < RubyCdk::PreconditionError
24
+ attr_reader :code
25
+
26
+ def initialize(message, code: nil)
27
+ @code = code
28
+ super(message)
29
+ end
30
+ end
31
+
32
+ # Exit 3. CloudFormation refused the change set when it was asked for,
33
+ # before there was a change set to describe.
34
+ class ChangeSetRequestRejected < RubyCdk::ChangeSetRejected
35
+ attr_reader :code
36
+
37
+ def initialize(message, code: nil)
38
+ @code = code
39
+ super(message)
40
+ end
41
+ end
42
+
43
+ # The region, as the SDK's own search order would find it after the two
44
+ # steps taken over here. regional_endpoint.rb, in aws-sdk-core 3.271.1.
45
+ REGION_VARIABLES = %w[AWS_REGION AMAZON_REGION AWS_DEFAULT_REGION].freeze
46
+
47
+ # What the SDK raises when it cannot find or use credentials, which is
48
+ # not AWS answering.
49
+ CREDENTIAL_FAILURES = [
50
+ Aws::Errors::NoSuchProfileError,
51
+ Aws::Errors::MissingCredentialsError,
52
+ Aws::Errors::NoSourceProfileError,
53
+ Aws::Errors::NoSourceCredentialsError,
54
+ Aws::Errors::CredentialSourceConflictError,
55
+ Aws::Errors::InvalidCredentialSourceError,
56
+ Aws::Errors::SourceProfileCircularReferenceError,
57
+ Aws::Errors::InvalidSSOCredentials,
58
+ Aws::Errors::InvalidSSOToken,
59
+ Aws::Errors::InvalidLoginToken
60
+ ].freeze
61
+
62
+ module_function
63
+
64
+ # The region a command uses. It is always found here and passed to every
65
+ # client, so that the SDK's own search order never picks one (architecture
66
+ # section 13):
67
+ #
68
+ # 1. the region given: --region, else the stack's env.region;
69
+ # 2. AWS_REGION, then AMAZON_REGION, then AWS_DEFAULT_REGION, which is the
70
+ # SDK's own list in its own order;
71
+ # 3. the region the profile names in the shared config file
72
+ # (AWS_CONFIG_FILE, or ~/.aws/config).
73
+ #
74
+ # When nothing names one, the command refuses.
75
+ def resolve_region(profile:, region:)
76
+ # A region that is blank is not one.
77
+ found = region.to_s.strip.empty? ? nil : region
78
+ found = named_in_environment if found.to_s.empty?
79
+ found = profile_region(profile) if found.to_s.empty?
80
+ if found.to_s.empty?
81
+ whose = profile ? "the profile #{profile}" : "the default profile"
82
+ Kernel.raise RubyCdk::PreconditionError, "No region to deploy to: none was given, none is in #{REGION_VARIABLES.join(", ")}, " \
83
+ "and #{whose} names none in the shared config file. Nothing was changed.\n" \
84
+ "Run the command again with --region NAME."
85
+ end
86
+
87
+ check_region(found)
88
+ found
89
+ end
90
+
91
+ # The first of the SDK's environment variables that names a region.
92
+ def named_in_environment
93
+ REGION_VARIABLES.filter_map { |name| value = ENV[name]; value unless value.to_s.empty? }.first
94
+ end
95
+
96
+ # The two clients a command needs, for one profile and one region.
97
+ #
98
+ # credentials and stub_responses are for tests, and for tools that only
99
+ # need a client object: the default credential chain searches for
100
+ # credentials and, finding none, waits on the EC2 metadata endpoint
101
+ # (D-024). Nothing outside a test passes them.
102
+ def clients(profile:, region:, credentials: nil, stub_responses: false)
103
+ region = resolve_region(profile: profile, region: region)
104
+ options = { credentials: credentials, stub_responses: stub_responses }
105
+ Clients.new(
106
+ cfn: cfn_client(region: region, profile: profile, **options),
107
+ store: object_store(region: region, profile: profile, **options)
108
+ )
109
+ end
110
+
111
+ # The CloudFormation port.
112
+ def cfn_client(region:, profile: nil, credentials: nil, stub_responses: false)
113
+ CloudFormationClient.new(region: region, profile: profile, credentials: credentials, stub_responses: stub_responses)
114
+ end
115
+
116
+ # The object store port.
117
+ def object_store(region:, profile: nil, credentials: nil, stub_responses: false)
118
+ ObjectStoreClient.new(region: region, profile: profile, credentials: credentials, stub_responses: stub_responses)
119
+ end
120
+
121
+ # The options every client is built with. region is always among them.
122
+ # profile narrows the standard credential chain to that profile; without
123
+ # one, the chain is the SDK's own.
124
+ def options_for(region:, profile: nil, credentials: nil, stub_responses: false)
125
+ options = { region: region }
126
+ options[:profile] = profile if profile
127
+ options[:credentials] = credentials if credentials
128
+ options[:stub_responses] = true if stub_responses
129
+ options
130
+ end
131
+
132
+ # Runs a request. When it fails, what is raised is one of this gem's
133
+ # errors, or the error itself when it is not one the SDK documents.
134
+ # rejects decides whether the refusal of a change set is told apart.
135
+ def request(rejects: false)
136
+ yield
137
+ rescue StandardError => e
138
+ translated = failure_of(e, rejects: rejects)
139
+ Kernel.raise translated if translated
140
+
141
+ Kernel.raise
142
+ end
143
+
144
+ # The error of this gem that stands for one of the SDK's, or nil.
145
+ def failure_of(error, rejects: false)
146
+ case error
147
+ when Aws::Errors::ServiceError
148
+ code = error.code || error.class.name.to_s.split("::").last
149
+ message = "#{code}: #{error.message}"
150
+ return ChangeSetRequestRejected.new(message, code: code) if rejects && CloudFormationClient::REJECTED_CODES.include?(code)
151
+
152
+ RequestFailed.new(message, code: code)
153
+ when Seahorse::Client::NetworkingError
154
+ RequestFailed.new("AWS could not be reached (#{error.message}).")
155
+ when *CREDENTIAL_FAILURES
156
+ kind = error.class.name.to_s.split("::").last
157
+ RequestFailed.new("The credentials could not be found or used (#{kind}: #{error.message}).")
158
+ end
159
+ end
160
+
161
+ # The region the profile names in the shared config file.
162
+ #
163
+ # Two things about SharedConfig are easy to get wrong, and both were:
164
+ #
165
+ # - The profile is an option of `region`, not of `new`. The constructor
166
+ # takes `profile_name`, and ignores `profile:`: SharedConfig.new(profile: "x")
167
+ # is the default profile.
168
+ # - The config file is read only with `config_enabled: true`. Without it,
169
+ # `region` answers nil for every profile.
170
+ #
171
+ # Together they make the wrong call answer the default profile's region
172
+ # for a named profile: the wrong region, in silence. This is the call the
173
+ # SDK makes itself (plugins/regional_endpoint.rb).
174
+ #
175
+ # AWS_SDK_CONFIG_OPT_OUT is honoured as the SDK honours it (aws-sdk-core.rb):
176
+ # a file the user told the SDK to ignore is not read for a region either.
177
+ def profile_region(profile)
178
+ return nil if ENV["AWS_SDK_CONFIG_OPT_OUT"]
179
+
180
+ Aws::SharedConfig.new(config_enabled: true).region(profile: profile)
181
+ rescue StandardError => e
182
+ Kernel.raise RubyCdk::PreconditionError, "The shared config file could not be read for a region (#{e.message}).\n" \
183
+ "Run the command again with --region NAME."
184
+ end
185
+
186
+ # A region is checked against the partitions the SDK ships, so that a
187
+ # typo is refused here and not by a request to an endpoint that does not
188
+ # exist. The cost: a region newer than the pinned aws-partitions is
189
+ # refused until the gem is updated, which is the safe side of the trade.
190
+ def check_region(region)
191
+ known = Aws::Partitions.partitions.any? { |partition| partition.region?(region) }
192
+ return if known
193
+
194
+ Kernel.raise RubyCdk::PreconditionError, "#{region.inspect} is not a region the AWS SDK knows, so nothing was changed.\n" \
195
+ "Run the command again with --region NAME, for example eu-west-1."
196
+ end
197
+
198
+ # The CloudFormation port.
199
+ class CloudFormationClient
200
+ include CfnClient
201
+
202
+ # The events of an operation are read from this many seconds before the
203
+ # engine asks: this machine's clock and the one at AWS are never the same.
204
+ EVENT_SKEW = 5
205
+
206
+ # The error codes CloudFormation answers with when it refuses a change
207
+ # set, as opposed to when something else went wrong.
208
+ REJECTED_CODES = %w[
209
+ ValidationError
210
+ InsufficientCapabilitiesException
211
+ AlreadyExistsException
212
+ CreatedButModifiedException
213
+ InvalidChangeSetStatusException
214
+ ].freeze
215
+
216
+ # How CloudFormation says that there is no such stack.
217
+ MISSING_STACK = /does not exist/i
218
+
219
+ attr_reader :raw
220
+
221
+ def initialize(region:, profile: nil, credentials: nil, stub_responses: false)
222
+ @profile = profile
223
+ @credentials = credentials
224
+ @stub_responses = stub_responses
225
+ @raw = Aws::CloudFormation::Client.new(**client_options(region))
226
+ rescue ArgumentError
227
+ raise RequestFailed, "The AWS SDK does not accept the region #{region.inspect}. Run the command again with --region NAME."
228
+ end
229
+
230
+ # The STS client, built on first use with the options the main client
231
+ # was built with, so that a test stubs it the same way.
232
+ def sts
233
+ @sts ||= Aws::STS::Client.new(**client_options(@raw.config.region))
234
+ end
235
+
236
+ # Who the credentials are for, asked of STS with the same region and
237
+ # the same profile as the client. The account is an identifier; it is
238
+ # returned whole, and nothing here prints anything.
239
+ #
240
+ # The STS client is built on the first call, with the options the main
241
+ # client was built with, so a test stubs it the same way.
242
+ def resolve_identity
243
+ response = Sdk.request { sts.get_caller_identity }
244
+ Identity.new(account: response.account, region: @raw.config.region, arn: response.arn)
245
+ rescue RequestFailed => e
246
+ raise RubyCdk::PreconditionError, "No account could be resolved from the credentials, so there is no target to deploy to. " \
247
+ "#{e.message}\nNothing was changed. Check the profile and the region (--profile NAME, --region NAME), then run the command again."
248
+ end
249
+
250
+ def stack_state(name)
251
+ stack = stack_of(name)
252
+ state = StackStatus.state(stack&.stack_status)
253
+ if state.nil?
254
+ raise RubyCdk::PreconditionError, "CloudFormation answers the stack status #{stack.stack_status.inspect}, " \
255
+ "which this tool does not know how to place. Nothing was changed. Report it as a bug in ruby-cdk."
256
+ end
257
+
258
+ state
259
+ end
260
+
261
+ def stack_info(name)
262
+ stack = stack_of(name)
263
+ return nil unless stack
264
+
265
+ StackInfo.new(
266
+ name: stack.stack_name,
267
+ id: stack.stack_id,
268
+ status: stack.stack_status,
269
+ outputs: (stack.outputs || []).to_h { |output| [ output.output_key, output.output_value ] },
270
+ termination_protection: !!stack.enable_termination_protection
271
+ )
272
+ end
273
+
274
+ def stack_parameters(name)
275
+ (stack_of(name)&.parameters || []).to_h { |parameter| [ parameter.parameter_key, parameter.parameter_value ] }
276
+ end
277
+
278
+ def stack_tags(name)
279
+ (stack_of(name)&.tags || []).map { |tag| { key: tag.key, value: tag.value } }
280
+ end
281
+
282
+ # Every page, and every stack that is not deleted.
283
+ def list_stacks
284
+ stacks = []
285
+ response = Sdk.request { @raw.list_stacks }
286
+ loop do
287
+ response.stack_summaries.each do |summary|
288
+ next if summary.stack_status == StackStatus::DELETED
289
+
290
+ stacks << ListedStack.new(name: summary.stack_name, id: summary.stack_id, status: summary.stack_status)
291
+ end
292
+ break unless response.next_token
293
+
294
+ response = Sdk.request { @raw.list_stacks(next_token: response.next_token) }
295
+ end
296
+ stacks
297
+ end
298
+
299
+ # Answers the change set's ID. A template above the inline limit goes to
300
+ # the bucket, and the request carries its URL instead of its body: the
301
+ # two never go together, as the port promises.
302
+ def create_change_set(name, change_set_name, template:, change_set_type:, parameters:, tags:, capabilities:,
303
+ on_stack_failure: nil, template_url: nil)
304
+ params = {
305
+ stack_name: name,
306
+ change_set_name: change_set_name,
307
+ change_set_type: change_set_type.to_s.upcase,
308
+ parameters: parameter_pairs(parameters),
309
+ tags: pairs(tags, :key, :value),
310
+ capabilities: capabilities
311
+ }
312
+ params[:template_body] = template if template
313
+ params[:template_url] = template_url if template_url
314
+ params[:on_stack_failure] = on_stack_failure.to_s.upcase if on_stack_failure
315
+ response = Sdk.request(rejects: true) { @raw.create_change_set(params) }
316
+ ChangeSet.new(id: response.id || change_set_name)
317
+ end
318
+
319
+ # Every page of the changes, so that the list is never truncated.
320
+ def describe_change_set(name, change_set_id)
321
+ head = Sdk.request { @raw.describe_change_set(stack_name: name, change_set_name: change_set_id) }
322
+ response = head
323
+ changes = head.changes || []
324
+ while response.next_token
325
+ response = Sdk.request do
326
+ @raw.describe_change_set(stack_name: name, change_set_name: change_set_id, next_token: response.next_token)
327
+ end
328
+ changes.concat(response.changes || [])
329
+ end
330
+
331
+ ChangeSet.new(
332
+ id: head.change_set_id || change_set_id,
333
+ status: head.status,
334
+ status_reason: head.status_reason,
335
+ execution_status: head.execution_status,
336
+ changes: changes.map do |entry|
337
+ resource = entry.resource_change
338
+ Change.new(
339
+ action: resource.action,
340
+ logical_id: resource.logical_resource_id,
341
+ resource_type: resource.resource_type,
342
+ replacement: resource.replacement,
343
+ detail: plain(resource.details)
344
+ )
345
+ end
346
+ )
347
+ end
348
+
349
+ # DisableRollback is sent only when it is true: a creation carries
350
+ # OnStackFailure instead, and CloudFormation takes the two together for
351
+ # an error. So is RetainExceptOnCreate, which is what the engine always asks.
352
+ def execute_change_set(name, change_set_id, disable_rollback: false, retain_except_on_create: true)
353
+ params = { stack_name: name, change_set_name: change_set_id }
354
+ params[:disable_rollback] = true if disable_rollback
355
+ params[:retain_except_on_create] = true if retain_except_on_create
356
+ Sdk.request(rejects: true) { @raw.execute_change_set(params) }
357
+ nil
358
+ end
359
+
360
+ def delete_change_set(name, change_set_id)
361
+ Sdk.request { @raw.delete_change_set(stack_name: name, change_set_name: change_set_id) }
362
+ nil
363
+ end
364
+
365
+ def delete_stack(name)
366
+ Sdk.request { @raw.delete_stack(stack_name: name) }
367
+ nil
368
+ end
369
+
370
+ def list_resources(name_or_id)
371
+ resources = []
372
+ response = Sdk.request { @raw.list_stack_resources(stack_name: name_or_id) }
373
+ loop do
374
+ resources.concat(response.stack_resource_summaries || [])
375
+ break unless response.next_token
376
+
377
+ response = Sdk.request { @raw.list_stack_resources(stack_name: name_or_id, next_token: response.next_token) }
378
+ end
379
+ resources.map do |summary|
380
+ StackResource.new(logical_id: summary.logical_resource_id, status: summary.resource_status, physical_id: summary.physical_resource_id)
381
+ end
382
+ end
383
+
384
+ # The events after a moment, oldest first. DescribeStackEvents answers
385
+ # newest first, so paging stops at the first page that reaches back to
386
+ # the moment: a long-lived stack does not have its whole history read.
387
+ def events(name_or_id, after:)
388
+ after ||= Time.now - EVENT_SKEW
389
+ found = []
390
+ response = Sdk.request { @raw.describe_stack_events(stack_name: name_or_id) }
391
+ loop do
392
+ page = response.stack_events || []
393
+ found.concat(page)
394
+ break unless response.next_token && page.any? && page.all? { |event| event.timestamp && event.timestamp > after }
395
+
396
+ response = Sdk.request { @raw.describe_stack_events(stack_name: name_or_id, next_token: response.next_token) }
397
+ end
398
+ found.select { |event| event.timestamp && event.timestamp > after }
399
+ .sort_by(&:timestamp)
400
+ .map do |event|
401
+ Event.new(
402
+ resource_status: event.resource_status,
403
+ logical_id: event.logical_resource_id,
404
+ resource_type: event.resource_type,
405
+ status_reason: event.resource_status_reason,
406
+ timestamp: event.timestamp
407
+ )
408
+ end
409
+ rescue RequestFailed => e
410
+ raise unless missing?(e)
411
+
412
+ []
413
+ end
414
+
415
+ def get_template(name)
416
+ Sdk.request { @raw.get_template(stack_name: name) }.template_body
417
+ rescue RequestFailed => e
418
+ raise unless missing?(e)
419
+
420
+ nil
421
+ end
422
+
423
+ def update_termination_protection(name, enabled:)
424
+ Sdk.request { @raw.update_termination_protection(stack_name: name, enable_termination_protection: enabled) }
425
+ nil
426
+ end
427
+
428
+ # The events of a change set that failed its validation (DescribeEvents,
429
+ # newer than DescribeStackEvents). Only the failed ones are asked for.
430
+ def operation_events(name, change_set_id)
431
+ response = Sdk.request do
432
+ @raw.describe_events(stack_name: name, change_set_name: change_set_id, filters: { failed_events: true })
433
+ end
434
+ (response.operation_events || []).sort_by { |event| event.timestamp || event.start_time }.map do |event|
435
+ reason = [ event.validation_name, event.validation_status_reason ].compact.join(": ")
436
+ Event.new(
437
+ resource_status: event.resource_status,
438
+ logical_id: event.logical_resource_id,
439
+ resource_type: event.resource_type,
440
+ status_reason: reason.empty? ? event.resource_status_reason : reason,
441
+ timestamp: event.timestamp || event.start_time
442
+ )
443
+ end
444
+ end
445
+
446
+ private
447
+
448
+ # The options of a client for this region and profile. STS gets the same
449
+ # ones as CloudFormation: the identity is asked of the same credentials.
450
+ def client_options(region)
451
+ Sdk.options_for(region: region, profile: @profile, credentials: @credentials, stub_responses: @stub_responses)
452
+ end
453
+
454
+ # The stack as CloudFormation describes it, or nil when there is none.
455
+ def stack_of(name)
456
+ Sdk.request { @raw.describe_stacks(stack_name: name) }.stacks.first
457
+ rescue RequestFailed => e
458
+ raise unless missing?(e)
459
+
460
+ nil
461
+ end
462
+
463
+ def missing?(error)
464
+ error.code == "ValidationError" && MISSING_STACK.match?(error.message)
465
+ end
466
+
467
+ # The SDK takes { key: ..., value: ... }; the engine may give either kind of key.
468
+ def pairs(list, key, value)
469
+ list.map { |pair| { key => pair[key] || pair[key.to_s], value => pair[value] || pair[value.to_s] } }
470
+ end
471
+
472
+ # A parameter either carries its value or asks for the deployed one
473
+ # (UsePreviousValue, for a NoEcho value that comes back masked and goes
474
+ # back masked).
475
+ def parameter_pairs(list)
476
+ list.map do |pair|
477
+ key = pair[:parameter_key] || pair["parameter_key"]
478
+ if pair[:use_previous_value]
479
+ { parameter_key: key, use_previous_value: true }
480
+ else
481
+ { parameter_key: key, parameter_value: pair[:parameter_value] || pair["parameter_value"] }
482
+ end
483
+ end
484
+ end
485
+
486
+ # A structure of the SDK as a plain Hash, all the way down.
487
+ def plain(value)
488
+ case value
489
+ when Array
490
+ value.map { |item| plain(item) }
491
+ when Hash
492
+ value.transform_values { |item| plain(item) }
493
+ else
494
+ value.respond_to?(:to_h) ? value.to_h.transform_values { |item| plain(item) } : value
495
+ end
496
+ end
497
+ end
498
+
499
+ # The object store port. Every call names the bucket's expected owner
500
+ # (architecture section 8): a bucket name is a function of public facts,
501
+ # and somebody else may hold the one that was computed.
502
+ class ObjectStoreClient
503
+ include ObjectStore
504
+
505
+ attr_reader :raw
506
+
507
+ def initialize(region:, profile: nil, credentials: nil, stub_responses: false)
508
+ @raw = Aws::S3::Client.new(**Sdk.options_for(region: region, profile: profile, credentials: credentials,
509
+ stub_responses: stub_responses))
510
+ end
511
+
512
+ # A HEAD request answers with no body, so its error code is generic
513
+ # (NotFound, Forbidden); the status is what tells the two apart.
514
+ #
515
+ # :mine the owner check passed
516
+ # :foreign the bucket exists and is not ours: S3 answers 403
517
+ # :absent there is no such bucket: S3 answers 404
518
+ def bucket_state(name, expected_owner:)
519
+ @raw.head_bucket(bucket: name, expected_bucket_owner: expected_owner)
520
+ :mine
521
+ rescue StandardError => e
522
+ case status_of(e)
523
+ when 404
524
+ :absent
525
+ when 403
526
+ :foreign
527
+ else
528
+ raise Sdk.failure_of(e) || e
529
+ end
530
+ end
531
+
532
+ # False only when the object is not there. A bucket that is not ours
533
+ # raises: a false here would read as "not uploaded yet".
534
+ def object_exists?(bucket, key, expected_owner:)
535
+ @raw.head_object(bucket: bucket, key: key, expected_bucket_owner: expected_owner)
536
+ true
537
+ rescue StandardError => e
538
+ status = status_of(e)
539
+ raise not_ours(bucket, expected_owner) if status == 403
540
+ raise Sdk.failure_of(e) || e unless status == 404
541
+
542
+ false
543
+ end
544
+
545
+ # The object goes in encrypted at rest.
546
+ #
547
+ # What is sent is what the CDK's publisher sends with an asset
548
+ # (cdk-assets-lib, lib/private/handlers/files.ts): the object encrypted
549
+ # (ServerSideEncryption), a SHA-256 checksum (ChecksumAlgorithm), and
550
+ # the content type of the file. For a zip that is application/zip; for
551
+ # anything else the CDK takes the type from the file's extension, and so
552
+ # does this, because the same port carries the templates.
553
+ #
554
+ # The checksum: the SDK computes it itself from the algorithm named
555
+ # here. Named, it is SHA-256 as in the CDK; left out, the SDK's own
556
+ # default would be CRC32.
557
+ #
558
+ # The encryption: AES256 is right while the bucket's own default
559
+ # encryption is SSE-S3. The day the bootstrap bucket is encrypted with
560
+ # a KMS key this has to follow, with "aws:kms" and the key, or S3
561
+ # answers EncryptionTypeMismatch. The CDK reads the bucket's
562
+ # configuration to choose (files.ts:120-131); this does not.
563
+ def put(bucket, key, body:, expected_owner:)
564
+ Sdk.request do
565
+ @raw.put_object(
566
+ bucket: bucket,
567
+ key: key,
568
+ body: body,
569
+ expected_bucket_owner: expected_owner,
570
+ server_side_encryption: "AES256",
571
+ checksum_algorithm: "SHA256",
572
+ content_type: content_type_of(key)
573
+ )
574
+ end
575
+ nil
576
+ rescue RequestFailed => e
577
+ raise not_ours(bucket, expected_owner) if REFUSED.include?(e.code)
578
+
579
+ raise
580
+ end
581
+
582
+ private
583
+
584
+ CONTENT_TYPES = { ".zip" => "application/zip", ".json" => "application/json" }.freeze
585
+
586
+ # What S3 answers a put when the bucket is not ours, or not ours to write.
587
+ REFUSED = %w[Forbidden AccessDenied].freeze
588
+
589
+ def content_type_of(key)
590
+ CONTENT_TYPES[File.extname(key.to_s).downcase] || "application/octet-stream"
591
+ end
592
+
593
+ # A 403 on a call that named the owner: the bucket belongs to another
594
+ # account, or these credentials may not touch it. Either way it stops.
595
+ def not_ours(bucket, expected_owner)
596
+ RequestFailed.new("Bucket #{bucket} belongs to another account than #{expected_owner}, or these credentials may not " \
597
+ "touch it (S3 answered 403 Forbidden), so the operation stops. Nothing was uploaded.", code: "Forbidden")
598
+ end
599
+
600
+ def status_of(error)
601
+ return error.context.http_response.status_code if error.is_a?(Aws::Errors::ServiceError)
602
+
603
+ 0
604
+ end
605
+ end
606
+ end
607
+ end
608
+ end
@@ -0,0 +1,62 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "errors"
4
+
5
+ module RubyCdk
6
+ module Deploy
7
+ # The six states of a stack, read from its CloudFormation status.
8
+ #
9
+ # The table itself is in the port (StackStatus), because the adapter that
10
+ # answers stack_state needs it too. This is the engine's reading of it,
11
+ # which places every status it knows and refuses the rest: a status this
12
+ # tool cannot place is never guessed at.
13
+ module States
14
+ # What has to happen before a stack in :rollback_failed can be deployed
15
+ # again. Each path is the one AWS documents for that status, read in the
16
+ # CloudFormation User Guide on 2026-11-23: "Stack failure options",
17
+ # "Continue rolling back an update" and "Delete a stack from the
18
+ # CloudFormation console".
19
+ REPAIR = {
20
+ "CREATE_FAILED" =>
21
+ "Roll the stack back to its last known stable state: Roll back in the CloudFormation console, or the RollbackStack API. " \
22
+ "A stack whose creation failed has no stable state, so the rollback deletes it, and the next deploy creates it again.",
23
+ "UPDATE_FAILED" =>
24
+ "Roll the stack back to its last known stable state: Roll back in the CloudFormation console, or the RollbackStack API.",
25
+ "UPDATE_ROLLBACK_FAILED" =>
26
+ "Continue the update rollback: in the CloudFormation console, on the Stacks page, choose the stack, " \
27
+ "then Stack actions and Continue update rollback.",
28
+ "IMPORT_ROLLBACK_FAILED" =>
29
+ "Continue the rollback: in the CloudFormation console, on the Stacks page, choose the stack, " \
30
+ "then Stack actions and Continue update rollback. An import whose update fails rolls back like an update, " \
31
+ "into IMPORT_ROLLBACK_FAILED.",
32
+ "DELETE_FAILED" =>
33
+ "The stack could not be deleted. Fix the resources that blocked the deletion, then delete the stack again: " \
34
+ "in the CloudFormation console, on the Stacks page, choose the stack, then Retry delete."
35
+ }.freeze
36
+
37
+ # The page that explains the failed states and what can be done about them.
38
+ DOCS = "https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/stack-failure-options.html"
39
+
40
+ # The state of a stack status, one of STACK_STATES. nil is a stack that
41
+ # does not exist. A status that is neither in the table nor in progress is
42
+ # an error: this tool does not know what to do with it, and says so.
43
+ def self.classify(status)
44
+ state = StackStatus.state(status)
45
+ if state.nil?
46
+ raise UnknownStackStatus, "CloudFormation reports the stack status #{status.inspect}, which this tool does not know how to place. " \
47
+ "Nothing was changed. Look at the stack in the CloudFormation console, and report the status as a bug in ruby-cdk."
48
+ end
49
+
50
+ state
51
+ end
52
+
53
+ # The way out of a status in :rollback_failed, with what to do next.
54
+ def self.repair_path(status)
55
+ repair = REPAIR[status]
56
+ return nil unless repair
57
+
58
+ "#{repair}\nWhen the stack is back in a stable state, run the command again. #{DOCS}"
59
+ end
60
+ end
61
+ end
62
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "errors"
4
+ require_relative "deploy/ports"
5
+ require_relative "deploy/errors"
6
+ require_relative "deploy/poller"
7
+ require_relative "deploy/capabilities"
8
+ require_relative "deploy/parameters"
9
+ require_relative "deploy/states"
10
+ require_relative "deploy/deployer"
11
+ require_relative "deploy/output/human"
12
+ require_relative "deploy/output/quiet"
13
+ require_relative "deploy/output/json"
14
+
15
+ module RubyCdk
16
+ # The deploy engine. Loaded by the commands that change something in AWS,
17
+ # never by `synth`.
18
+ #
19
+ # This file is the entry of the `deploy` component: it loads the engine's
20
+ # files and nothing else. The AWS SDK is reached only through
21
+ # `ruby_cdk/deploy/sdk_adapters`, which a command loads on its own. The fakes
22
+ # are `ruby_cdk/deploy/fakes`, which tests load on their own.
23
+ module Deploy
24
+ end
25
+ end