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,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Cli
5
+ # The two exit codes the command line decides by itself. The others are
6
+ # decided by the class of the error (RubyCdk::Deploy.exit_code_for), or
7
+ # carried by a result of the engine (architecture section 14).
8
+ SUCCESS = 0
9
+ USAGE = 1
10
+
11
+ # Exit 1: the command line was asked for something it cannot do, which is a
12
+ # problem of the options or of the command, never of AWS or of the template.
13
+ #
14
+ # Architecture section 14: every failure ends with the command to run next
15
+ # when there is an obvious one. next_step is that line, whole, as
16
+ # "Run `ruby-cdk deploy --all`."; nil when nothing is obvious.
17
+ class Usage < RubyCdk::UsageError
18
+ attr_reader :next_step
19
+
20
+ def initialize(message, next_step: nil)
21
+ @next_step = next_step
22
+ super(message)
23
+ end
24
+ end
25
+
26
+ # Exit 1: the app file raised while it ran.
27
+ #
28
+ # Architecture section 11: such an error is reported at the user's file and
29
+ # line, not inside the gem. error is what was raised, and location is the
30
+ # first frame of its backtrace that is in the app file.
31
+ class AppFileError < RubyCdk::Error
32
+ attr_reader :path, :error, :location
33
+
34
+ def initialize(path, error)
35
+ @path = path
36
+ @error = error
37
+ @location = Location.in(path, error)
38
+ super("#{error.class}: #{error.message}")
39
+ end
40
+
41
+ # True when what was raised is one of this gem's errors, from the tree the
42
+ # app file was building: its message is already written for a user.
43
+ def gem_error?
44
+ error.is_a?(RubyCdk::Error)
45
+ end
46
+
47
+ # The backtrace of what was raised, gem frames included. For --verbose.
48
+ def backtrace
49
+ error.backtrace || []
50
+ end
51
+
52
+ # Where in the app file the error happened: a line, and what was running there.
53
+ Location = Data.define(:line, :label) do
54
+ # The first frame of the error's backtrace that is in the file, or nil
55
+ # when the file raised nothing of its own. A syntax error is different:
56
+ # it has no frame in the file, and its message starts with the line.
57
+ def self.in(path, error)
58
+ if error.is_a?(SyntaxError) && error.message.start_with?("#{path}:")
59
+ line, rest = error.message.delete_prefix("#{path}:").split(":", 2)
60
+ return new(line: Integer(line, exception: false), label: rest&.lines&.first&.strip)
61
+ end
62
+
63
+ frame = Array(error.backtrace).find { |entry| entry.start_with?("#{path}:") }
64
+ return nil unless frame
65
+
66
+ _path, line, rest = frame.split(":", 3)
67
+ new(line: Integer(line, exception: false), label: rest&.strip)
68
+ end
69
+
70
+ # "line 4, in `<main>'".
71
+ def to_s
72
+ return "line #{line}" if label.nil? || label.empty?
73
+ return label if line.nil?
74
+
75
+ "line #{line}, #{label}"
76
+ end
77
+ end
78
+ end
79
+ end
80
+ end
@@ -0,0 +1,70 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Cli
5
+ # The streams a command writes to, and the two settings that decide how.
6
+ #
7
+ # Standard out carries what is read by a machine: the template `synth`
8
+ # prints, the JSON of `--json`, the outputs the engine prints. Everything
9
+ # said to a person goes to standard error, so that `ruby-cdk synth >
10
+ # stack.json` and `ruby-cdk deploy --json | jq` read clean output.
11
+ class Io
12
+ RED = "\e[31m"
13
+ RESET = "\e[0m"
14
+
15
+ # Decided by each command from its options: colour only when allowed and
16
+ # wanted, --verbose on or off.
17
+ attr_accessor :color, :verbose
18
+ attr_reader :out, :err, :stdin
19
+
20
+ def initialize(out: $stdout, err: $stderr, stdin: $stdin, color: false, verbose: false)
21
+ @out = out
22
+ @err = err
23
+ @stdin = stdin
24
+ @color = color
25
+ @verbose = verbose
26
+ end
27
+
28
+ # The real streams. A command decides colour and verbosity from its options.
29
+ def self.standard
30
+ new
31
+ end
32
+
33
+ # Standard out, exactly as given. The caller ends it with a newline.
34
+ def result(text)
35
+ out.print(text)
36
+ end
37
+
38
+ # One line on standard out.
39
+ def line(text = "")
40
+ out.puts text
41
+ end
42
+
43
+ # One line to a person, on standard error.
44
+ def say(text = "")
45
+ err.puts text
46
+ end
47
+
48
+ # What the command decided, for --verbose.
49
+ def debug(text)
50
+ say("ruby-cdk: #{text}") if verbose
51
+ end
52
+
53
+ # A failure, in red when there is colour.
54
+ def failure(text)
55
+ err.puts(color ? "#{RED}#{text}#{RESET}" : text)
56
+ end
57
+
58
+ # True when there is somebody to answer a question: a terminal on both
59
+ # standard input and standard output.
60
+ def interactive?
61
+ [ stdin, out ].all? { |stream| stream.respond_to?(:tty?) && stream.tty? }
62
+ end
63
+
64
+ # True when the command may use colour on standard out.
65
+ def terminal?
66
+ out.respond_to?(:tty?) && out.tty?
67
+ end
68
+ end
69
+ end
70
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "failure"
5
+
6
+ module RubyCdk
7
+ module Cli
8
+ # `ls`: the stacks of the app, one name per line, which is the CDK's list
9
+ # (packages/aws-cdk/lib/commands/list-stacks.ts:50-51 in aws-cdk-cli at
10
+ # eca1b73d682d7763955bec30ab5dd52bbc4327b6). Its `--long` adds where each
11
+ # stack deploys. The CDK's --json only changes the long forms; here it is
12
+ # the same list as one JSON array, decided in this tool.
13
+ #
14
+ # Nothing is synthesized: the tree exists as soon as the app file ran.
15
+ module List
16
+ # names are the STACK words: only those stacks. Answers the exit code.
17
+ def self.run(session, names)
18
+ names = names.compact
19
+ stacks = session.stacks
20
+ missing = names - stacks.map(&:stack_name)
21
+ unless missing.empty?
22
+ Kernel.raise Usage.new("No stacks match the name(s) #{missing.join(", ")}",
23
+ next_step: "Run `ruby-cdk ls` without a name to see every stack of the app.")
24
+ end
25
+ stacks = stacks.select { |stack| names.include?(stack.stack_name) } if names.any?
26
+
27
+ io = session.io
28
+ if session.options.json
29
+ io.result("#{JSON.generate(stacks.map { |stack| described(stack) })}\n")
30
+ else
31
+ stacks.each { |stack| io.line(session.options.long ? "#{stack.stack_name}\t#{where(stack)}" : stack.stack_name) }
32
+ end
33
+ Cli::SUCCESS
34
+ end
35
+
36
+ def self.described(stack)
37
+ env = stack.env
38
+ { "name" => stack.stack_name, "env" => env && { "account" => env.account, "region" => env.region } }
39
+ end
40
+
41
+ def self.where(stack)
42
+ stack.env ? stack.env.name : "no env: it deploys wherever the credentials point"
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,313 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+ require_relative "../version"
5
+ require_relative "failure"
6
+
7
+ module RubyCdk
8
+ module Cli
9
+ # `new`: the scaffold. `ruby-cdk new PROJECT` creates the directory PROJECT
10
+ # with the smallest app that deploys: the app file (one App, one stack), the
11
+ # stack (one parameter, one S3 bucket that stays private), a Gemfile, and
12
+ # the two git files whose rules this tool depends on — `.gitattributes`
13
+ # pins LF line endings, because they change an asset's hash (architecture
14
+ # section 8), and `.gitignore` keeps the build output out.
15
+ #
16
+ # The CDK's init is the reference (aws/aws-cdk-cli at main,
17
+ # packages/aws-cdk/lib/commands/init/init.ts and
18
+ # packages/aws-cdk/lib/init-templates/app): one template, named `app` there
19
+ # ("Template for a CDK Application", info.json), which writes the app file,
20
+ # one stack class, an example test, .gitignore and a README of useful
21
+ # commands; prints the project template's name and then the generated
22
+ # README; refuses a directory that holds visible files
23
+ # (assertIsEmptyDirectory, init.ts:747) ignoring dot-files as it ignores
24
+ # them; and asks for a language when a template supports several
25
+ # (resolveLanguage, init.ts:205), defaulting silently when it supports one.
26
+ # This tool has one template and one language, and both answers are Ruby:
27
+ # there is no --language and no --from to ask about. What the CDK runs
28
+ # after the template (git init and the package manager's install) this
29
+ # tool never runs — `lib/` starts no process — so the generated README
30
+ # carries the two commands instead.
31
+ module New
32
+ # What PROJECT may be called: the raw material of a directory name, a
33
+ # Ruby module and a stack name. Hyphens and underscores separate words;
34
+ # letters and digits build them.
35
+ NAME_PATTERN = /\A[A-Za-z][A-Za-z0-9_-]*\z/
36
+
37
+ # The one template, as the CDK names its (init-templates/app/info.json).
38
+ TEMPLATE = "app"
39
+
40
+ # The one language, as the CDK's resolveLanguage defaults to a template's
41
+ # only language (init.ts:218-223).
42
+ LANGUAGE = "ruby"
43
+
44
+ # project is the PROJECT word. Answers the exit code.
45
+ def self.run(session, project)
46
+ parts = parts_of(project, session.io)
47
+ target = File.expand_path(parts.name, Dir.pwd)
48
+ writable!(target, !!session.options.force, session.io)
49
+
50
+ session.io.say("Applying project template #{TEMPLATE} for #{LANGUAGE} into #{parts.name}/")
51
+ files_of(parts).each do |path, content|
52
+ full = File.join(target, path)
53
+ FileUtils.mkdir_p(File.dirname(full))
54
+ File.write(full, content)
55
+ end
56
+
57
+ # The CDK prints the generated README after the template
58
+ # (initializeProject, init.ts:729-733), and what it cannot run itself
59
+ # as a "Please run" line (postInstallTypescript's no-network path).
60
+ session.io.say(File.read(File.join(target, "README.md")))
61
+ session.io.say("Please run `bundle install --local` in #{parts.name}: ruby-cdk is not on rubygems.org yet, " \
62
+ "so the Gemfile resolves from the gem installed on this machine.")
63
+ session.io.say("All done! #{parts.name}/README.md has the three commands: synth, deploy, destroy.")
64
+ Cli::SUCCESS
65
+ end
66
+
67
+ # The name's three shapes, as the CDK's placeholders are three
68
+ # (%name%, %name.PascalCased%, %name.StackName%): the directory is the
69
+ # name as typed, because that is the directory the user asked for; the
70
+ # Ruby files under it take the snake_case form, which a require_relative
71
+ # reads; and the module is PascalCase. The stack name takes the typed
72
+ # name with underscores as hyphens, because a stack name holds no
73
+ # underscore (rule V13).
74
+ Parts = Data.define(:name, :ns, :namespace, :stack_id)
75
+
76
+ # Raises Cli::Usage when the name cannot become a project.
77
+ def self.parts_of(project, io)
78
+ name = project.to_s.strip
79
+ if name.empty?
80
+ raise Usage.new("Name the project directory: `ruby-cdk new NAME` creates it with the app scaffold.",
81
+ next_step: "Run `ruby-cdk new NAME` again, for example `ruby-cdk new my-app`.")
82
+ end
83
+ unless NAME_PATTERN.match?(name)
84
+ raise Usage.new("#{name.inspect} is not a project name: a name holds letters, digits, \"_\" and \"-\", " \
85
+ "and starts with a letter.",
86
+ next_step: "Run `ruby-cdk new NAME` again, for example `ruby-cdk new my-app`.")
87
+ end
88
+
89
+ words = name.gsub(/([A-Z\d]+)([A-Z][a-z])/, '\1_\2')
90
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
91
+ .tr("-", "_")
92
+ .downcase
93
+ .split("_")
94
+ mod = words.map(&:capitalize).join
95
+ if mod == "Stack" || Object.const_defined?(mod)
96
+ raise Usage.new("#{name.inspect} would define the module #{mod}, and that name is taken or would collide " \
97
+ "with the stack class the scaffold puts inside it.",
98
+ next_step: "Run `ruby-cdk new NAME` again with a different name.")
99
+ end
100
+
101
+ parts = Parts.new(name: name, ns: words.join("_"), namespace: mod, stack_id: name.tr("_", "-"))
102
+ io.debug("project #{parts.name}: module #{parts.namespace}, stack #{parts.stack_id}")
103
+ parts
104
+ end
105
+
106
+ # The CDK refuses a directory that exists and holds visible files, and
107
+ # ignores dot-files when it counts (init.ts:752-755). It also refuses one
108
+ # that does not exist and asks to `mkdir -p` it first (init.ts:756-762);
109
+ # this command is named by the directory, so it creates it, and `--force`
110
+ # is the answer for a directory someone made already: an empty one may be
111
+ # written into, one holding visible files is never overwritten.
112
+ def self.writable!(target, force, io)
113
+ unless File.exist?(target)
114
+ io.debug("#{target} does not exist and will be created")
115
+ return
116
+ end
117
+ raise Usage.new("#{target} exists and is not a directory.",
118
+ next_step: "Run `ruby-cdk new NAME` again with a name that is free.") unless File.directory?(target)
119
+
120
+ visible = Dir.children(target).reject { |entry| entry.start_with?(".") }
121
+ if visible.empty?
122
+ return true if force
123
+
124
+ raise Usage.new("#{target} exists already. #{Dir.children(target).empty? ? "It is empty" : "It holds only dot-files"}, " \
125
+ "and writing into an existing directory is refused unless --force says it was made for this.",
126
+ next_step: "Run `ruby-cdk new NAME --force`, or choose a name that is free.")
127
+ end
128
+
129
+ raise Usage.new("`ruby-cdk new` cannot write into a non-empty directory! " \
130
+ "Found #{visible.length} visible file(s) in #{target}:\n" +
131
+ visible.map { |entry| " - #{entry}" }.join("\n"),
132
+ next_step: "Choose a name that is free: --force never overwrites files.")
133
+ end
134
+
135
+ # The generated files, each the whole of its content. Deterministic: the
136
+ # same name and the same gem version write the same bytes, which the
137
+ # tests hold to.
138
+ def self.files_of(parts)
139
+ {
140
+ "cdk.rb" => app_file(parts),
141
+ "#{parts.ns}/#{parts.ns}_stack.rb" => stack_file(parts),
142
+ ".gitattributes" => <<~GIT_ATTRIBUTES,
143
+ # One byte of one file changes an asset's hash, because the asset's
144
+ # identity is the hash of its manifest, and a checkout that rewrites
145
+ # line endings changes bytes. Every text file is stored with LF,
146
+ # wherever the checkout happens.
147
+ * text=auto eol=lf
148
+ GIT_ATTRIBUTES
149
+ ".gitignore" => <<~GIT_IGNORE,
150
+ cdk.out/
151
+ .bundle/
152
+ vendor/
153
+ GIT_IGNORE
154
+ "Gemfile" => gemfile,
155
+ "README.md" => readme(parts)
156
+ }
157
+ end
158
+
159
+ def self.app_file(parts)
160
+ <<~RUBY
161
+ # frozen_string_literal: true
162
+
163
+ # The app file. It requires the gem and creates exactly one RubyCdk::App;
164
+ # the stack is a class of its own, so that it can be built here and
165
+ # somewhere else, under another name.
166
+ #
167
+ # Run it with the command line, from this directory (see README.md):
168
+ #
169
+ # bundle exec ruby-cdk synth
170
+ # bundle exec ruby-cdk deploy
171
+ # bundle exec ruby-cdk destroy
172
+ require "ruby-cdk"
173
+ require_relative "#{parts.ns}/#{parts.ns}_stack"
174
+
175
+ # A stack without an env deploys wherever your credentials point, after
176
+ # the command prints the target. To pin this app to one account and one
177
+ # region, create the App with an env:
178
+ #
179
+ # RubyCdk::App.new(env: RubyCdk::Env.new(account: "123456789012", region: "eu-central-1")) do |app|
180
+ # #{parts.namespace}::Stack.new(app, "#{parts.stack_id}")
181
+ # end
182
+ RubyCdk::App.new do |app|
183
+ #{parts.namespace}::Stack.new(app, "#{parts.stack_id}")
184
+ end
185
+ RUBY
186
+ end
187
+
188
+ def self.stack_file(parts)
189
+ <<~RUBY
190
+ # frozen_string_literal: true
191
+
192
+ require "ruby-cdk"
193
+
194
+ module #{parts.namespace}
195
+ # One S3 bucket that stays private: public access blocked on all four
196
+ # settings, and encrypted at rest.
197
+ #
198
+ # The bucket is an L1 resource, written with CloudFormation's own
199
+ # property names. A parameter decides whether it keeps every version
200
+ # of an object.
201
+ class Stack < RubyCdk::Stack
202
+ def build
203
+ versioning = parameter("Versioning", type: "String", default: "Suspended",
204
+ allowed_values: [ "Suspended", "Enabled" ],
205
+ description: "Whether the bucket keeps every version of an object")
206
+
207
+ resource("Bucket", "AWS::S3::Bucket", properties: {
208
+ "BucketEncryption" => {
209
+ "ServerSideEncryptionConfiguration" => [
210
+ { "ServerSideEncryptionByDefault" => { "SSEAlgorithm" => "AES256" } }
211
+ ]
212
+ },
213
+ "PublicAccessBlockConfiguration" => {
214
+ "BlockPublicAcls" => true,
215
+ "BlockPublicPolicy" => true,
216
+ "IgnorePublicAcls" => true,
217
+ "RestrictPublicBuckets" => true
218
+ },
219
+ "VersioningConfiguration" => { "Status" => Fn.ref(versioning) }
220
+ })
221
+ end
222
+ end
223
+ end
224
+ RUBY
225
+ end
226
+
227
+ # The version, not a path: the README's install story is "build and
228
+ # install the gem from source", so the gem is on this machine like any
229
+ # installed gem, and a path would hard-wire a checkout that does not
230
+ # exist anywhere else. `bundle install --local` resolves it today;
231
+ # `bundle install` resolves the same line once a release is published.
232
+ def self.gemfile
233
+ <<~RUBY
234
+ # frozen_string_literal: true
235
+
236
+ source "https://rubygems.org"
237
+
238
+ # ruby-cdk is not on rubygems.org yet: install it from source (the
239
+ # ruby-cdk README's Install) and run `bundle install --local` in this
240
+ # directory to resolve the line below from the installed gem. Once a
241
+ # release is published, plain `bundle install` resolves it too.
242
+ gem "ruby-cdk", "~> #{RubyCdk::VERSION}"
243
+ RUBY
244
+ end
245
+
246
+ def self.readme(parts)
247
+ <<~MARKDOWN
248
+ # #{parts.stack_id}
249
+
250
+ A ruby-cdk app: one stack with one S3 bucket that stays private —
251
+ public access blocked on all four settings, encrypted at rest — and a
252
+ parameter that decides whether the bucket keeps every version of an
253
+ object.
254
+
255
+ ## The three commands
256
+
257
+ ```sh
258
+ bundle install --local # once, in this directory: see "The Gemfile"
259
+ bundle exec ruby-cdk synth # writes cdk.out/#{parts.stack_id}.template.json and prints the template
260
+ bundle exec ruby-cdk deploy # shows the change set, asks, then deploys it
261
+ bundle exec ruby-cdk destroy # prints what is kept, asks for the stack name, then deletes
262
+ ```
263
+
264
+ ## Deploy asks first
265
+
266
+ `deploy` creates a change set, prints every change in it and the IAM
267
+ capabilities it would add, and then asks:
268
+
269
+ ```
270
+ Deploy these changes to stack #{parts.stack_id} in account 123456789012 (eu-central-1)?
271
+ ```
272
+
273
+ Yes executes it; anything else deletes the change set, and a stack that
274
+ was not created yet is deleted with it, so a refused deploy leaves
275
+ nothing behind. In a script, `--yes` skips the question. `destroy`
276
+ prints what the stack would keep and asks for the stack's name to be
277
+ typed — a yes is not enough for an irreversible act.
278
+
279
+ ## Where this stack deploys
280
+
281
+ A stack without an `env` deploys wherever your credentials point, after
282
+ the command prints the target. To pin the app, create the App with an
283
+ env in `cdk.rb`:
284
+
285
+ ```ruby
286
+ RubyCdk::App.new(env: RubyCdk::Env.new(account: "123456789012", region: "eu-central-1")) do |app|
287
+ #{parts.namespace}::Stack.new(app, "#{parts.stack_id}")
288
+ end
289
+ ```
290
+
291
+ A stack with an `env` deploys only into that account and region. And
292
+ when the stack grows an asset — `asset.zip`, the shape a Lambda's code
293
+ takes — it needs a concrete env: the asset bucket's name is made of the
294
+ account and the region, and synthesis never calls AWS to discover them.
295
+
296
+ ## The Gemfile
297
+
298
+ ruby-cdk is not on rubygems.org yet: install it from source (the
299
+ ruby-cdk README's Install), then run `bundle install --local` here, which
300
+ resolves `gem "ruby-cdk"` from the gem installed on this machine. Once a
301
+ release is published, plain `bundle install` resolves the same line.
302
+
303
+ ## Files
304
+
305
+ - `cdk.rb` — the app file: one RubyCdk::App, one stack
306
+ - `#{parts.ns}/#{parts.ns}_stack.rb` — the stack: one parameter, one S3 bucket
307
+ - `.gitattributes` — line endings pinned to LF: they change an asset's hash
308
+ - `.gitignore` — `cdk.out/`, `.bundle/`, `vendor/`
309
+ MARKDOWN
310
+ end
311
+ end
312
+ end
313
+ end
@@ -0,0 +1,124 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require_relative "failure"
5
+ require_relative "selection"
6
+
7
+ module RubyCdk
8
+ module Cli
9
+ # `deploy` and `destroy`: the same walk over the stacks selected, each one
10
+ # through the engine, one at a time and stopping at the first that fails.
11
+ #
12
+ # The engine does the work and says what happens, through the output object
13
+ # the session chose. This class decides which stacks, in which order, with
14
+ # which region, and turns what came back into the exit code and, for
15
+ # --json, one object per stack on standard out.
16
+ class Operation
17
+ attr_reader :session, :kind
18
+
19
+ # kind is :deploy or :destroy.
20
+ def initialize(session, kind:)
21
+ @session = session
22
+ @kind = kind
23
+ end
24
+
25
+ # names are the STACK words. Answers the exit code of the command
26
+ # (architecture section 14): the first stack's that was not 0, else 0.
27
+ def call(names)
28
+ manifest = session.manifest
29
+ session.say_synthesis_time
30
+ selected = Selection.choose(session.stacks, names:, all: session.options.all, command: kind.to_s)
31
+ entries = Selection.ordered(manifest.entries, selected: selected.map(&:stack_name),
32
+ direction: kind == :deploy ? :up : :down, exclusively: session.options.exclusively)
33
+ announce_dependencies(selected, entries)
34
+ session.io.debug("#{kind}: #{entries.map(&:name).join(", ")}")
35
+
36
+ # The options are read, and so checked, before any client is built: a
37
+ # typo in one is a usage error and never a request.
38
+ kind == :deploy ? session.deploy_options : session.destroy_options
39
+
40
+ entries.each_with_index do |entry, index|
41
+ result = nil
42
+ begin
43
+ result = one(entry)
44
+ rescue RubyCdk::Error => e
45
+ record(entry.name, error: e)
46
+ entries.drop(index + 1).each do |later|
47
+ record(later.name, error: "not attempted: #{entry.name} before it ended with exit code #{Deploy.exit_code_for(e)}", code: nil)
48
+ end
49
+ raise
50
+ end
51
+
52
+ record(entry.name, result:)
53
+ return result.exit_code unless result.exit_code.zero?
54
+ end
55
+ Cli::SUCCESS
56
+ end
57
+
58
+ private
59
+
60
+ # What the command brings beside the stacks named: the CDK deploys the
61
+ # dependencies of a named stack and destroys what depends on it, unless
62
+ # --exclusively (packages/aws-cdk/lib/cli/cli.ts:800-839 in aws-cdk-cli,
63
+ # expandUp and expandDown), and says so. --all was the answer, not an
64
+ # announcement. Human output only.
65
+ def announce_dependencies(selected, entries)
66
+ return if session.options.all || session.options.exclusively
67
+
68
+ extra = entries.map(&:name) - selected.map(&:stack_name)
69
+ return if extra.empty?
70
+
71
+ session.io.say("Including #{kind == :deploy ? "dependency" : "dependent"} stacks: #{extra.join(", ")}")
72
+ end
73
+
74
+ # One stack, from synthesis's output to the engine's answer.
75
+ def one(entry)
76
+ stack = session.stack(entry.name)
77
+ region = session.region_of(stack)
78
+ clients = session.clients(region:)
79
+ session.io.debug("#{entry.name}: region #{region}#{session.region_source(stack)}")
80
+
81
+ identity = session.identity(clients)
82
+ deployer = session.deployer(clients)
83
+ if kind == :destroy
84
+ # The stack, not its name: the engine checks the stack's env against
85
+ # the identity on a destroy, exactly as it does on a deploy.
86
+ return deployer.destroy(stack:, identity:, options: session.destroy_options)
87
+ end
88
+
89
+ # The deploy step of architecture section 8: the stack's assets are in
90
+ # their bucket before any change set is asked for. A stack with no asset
91
+ # uploads nothing and checks nothing.
92
+ published = Assets.publish(stack, store: clients.store, owner: identity.account)
93
+ session.io.debug("#{entry.name}: assets #{published[:uploaded]} uploaded, #{published[:skipped]} already in the bucket")
94
+
95
+ deployer.deploy(stack:, template: session.template_of(entry), identity:, options: session.deploy_options)
96
+ end
97
+
98
+ # For --json, one object on standard out per stack (architecture section
99
+ # 11): name, stack id, outcome, exit code, changes, outputs, and the error
100
+ # when it failed. Nothing else is written there. An error carries the exit
101
+ # code its class decides; code: overrides that, nil included.
102
+ def record(name, result: nil, error: nil, code: :unset)
103
+ return unless session.options.json
104
+
105
+ exit_code =
106
+ if code == :unset
107
+ result&.exit_code || (error ? Deploy.exit_code_for(error) : nil)
108
+ else
109
+ code
110
+ end
111
+ object = {
112
+ "name" => name,
113
+ "stack_id" => result&.stack_id,
114
+ "outcome" => result&.outcome&.to_s,
115
+ "exit_code" => exit_code,
116
+ "changes" => (result&.changes || []).map(&:to_h),
117
+ "outputs" => result&.outputs || {}
118
+ }
119
+ object["error"] = error.is_a?(Exception) ? error.message : error.to_s if error
120
+ session.io.result("#{JSON.generate(object)}\n")
121
+ end
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ module RubyCdk
4
+ module Cli
5
+ # The two options that are written as KEY=VALUE pairs: --parameters and
6
+ # --tags. "k=v,k2=v2" is one string once Thor has read it.
7
+ module Pairs
8
+ # The pairs as a Hash of Strings. An option that was not given, or that
9
+ # is blank, is no pairs. Raises Cli::Usage for anything that is not
10
+ # KEY=VALUE and for a key given twice. option names the option and
11
+ # command the command, for the line that says what to run next.
12
+ def self.parse(text, option:, command:)
13
+ return {} if text.nil? || text.strip.empty?
14
+
15
+ text.split(",", -1).each_with_object({}) do |item, pairs|
16
+ key, value = item.split("=", 2)
17
+ key = key&.strip
18
+ unless value && key && !key.empty?
19
+ Kernel.raise Usage.new("#{option} takes KEY=VALUE pairs separated by commas, and #{item.strip.inspect} is not one",
20
+ next_step: "Run `ruby-cdk #{command}` again with #{option} KEY=VALUE,KEY=VALUE.")
21
+ end
22
+ if pairs.key?(key)
23
+ Kernel.raise Usage.new("#{option} names #{key.inspect} twice: #{pairs[key].inspect} and #{value.to_s.inspect}",
24
+ next_step: "Run `ruby-cdk #{command}` again with #{key}=VALUE once.")
25
+ end
26
+
27
+ pairs[key] = value.to_s
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end