ruby-cdk 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +253 -0
  3. data/README.md +28 -5
  4. data/lib/ruby_cdk/assets/hasher.rb +4 -0
  5. data/lib/ruby_cdk/assets.rb +4 -8
  6. data/lib/ruby_cdk/cli/aws.rb +23 -5
  7. data/lib/ruby_cdk/cli/drift.rb +94 -0
  8. data/lib/ruby_cdk/cli/import.rb +306 -0
  9. data/lib/ruby_cdk/cli/lookup.rb +214 -0
  10. data/lib/ruby_cdk/cli/session.rb +114 -3
  11. data/lib/ruby_cdk/cli/watch.rb +297 -0
  12. data/lib/ruby_cdk/cli.rb +76 -1
  13. data/lib/ruby_cdk/constructs/function.rb +24 -3
  14. data/lib/ruby_cdk/constructs/hosted_zone.rb +342 -0
  15. data/lib/ruby_cdk/constructs/record_set.rb +330 -0
  16. data/lib/ruby_cdk/constructs/ssm_parameter.rb +174 -0
  17. data/lib/ruby_cdk/constructs/vpc.rb +822 -0
  18. data/lib/ruby_cdk/constructs/vpc_network.rb +159 -0
  19. data/lib/ruby_cdk/constructs.rb +5 -1
  20. data/lib/ruby_cdk/core/app.rb +28 -2
  21. data/lib/ruby_cdk/core/construct.rb +2 -0
  22. data/lib/ruby_cdk/core/context.rb +138 -0
  23. data/lib/ruby_cdk/core/stack.rb +4 -0
  24. data/lib/ruby_cdk/core.rb +1 -0
  25. data/lib/ruby_cdk/deploy/deployer.rb +283 -8
  26. data/lib/ruby_cdk/deploy/drift.rb +389 -0
  27. data/lib/ruby_cdk/deploy/ec2_adapter.rb +214 -0
  28. data/lib/ruby_cdk/deploy/errors.rb +8 -0
  29. data/lib/ruby_cdk/deploy/fakes.rb +230 -22
  30. data/lib/ruby_cdk/deploy/output/base.rb +8 -0
  31. data/lib/ruby_cdk/deploy/output/json.rb +7 -0
  32. data/lib/ruby_cdk/deploy/poller.rb +10 -0
  33. data/lib/ruby_cdk/deploy/ports.rb +124 -8
  34. data/lib/ruby_cdk/deploy/sdk_adapters.rb +141 -6
  35. data/lib/ruby_cdk/deploy/ssm_adapter.rb +111 -0
  36. data/lib/ruby_cdk/deploy.rb +1 -0
  37. data/lib/ruby_cdk/diff/compare.rb +1 -1
  38. data/lib/ruby_cdk/diff/identity_center.rb +64 -0
  39. data/lib/ruby_cdk/diff/render.rb +147 -8
  40. data/lib/ruby_cdk/diff/security.rb +195 -10
  41. data/lib/ruby_cdk/diff/security_group.rb +94 -0
  42. data/lib/ruby_cdk/nag/rules/security_group_ingress.rb +2 -0
  43. data/lib/ruby_cdk/schema/sources/provider_type.rb +3 -0
  44. data/lib/ruby_cdk/test/private/cyclic.rb +4 -0
  45. data/lib/ruby_cdk/test/private/js.rb +1 -3
  46. data/lib/ruby_cdk/version.rb +1 -1
  47. metadata +43 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 7d26933a27bf404e149152155ddb8744aa5dd055b94c06929da5d00ccc5b1b2c
4
- data.tar.gz: 50afe89a297afef34c024cdf99ad86da6837c5042d1ecb9e96639a513993915e
3
+ metadata.gz: 057d4fcdec17442f3d7e3cabfdea45097e93350305f4990a5085fe6abea9a525
4
+ data.tar.gz: 4c0e9b9594ac7a9519ff2068f4f91541e4cbaeecd1e29adbb3a25cb87d68896e
5
5
  SHA512:
6
- metadata.gz: 020c8868d980608e6eb6e0cfad8cd8235990a1d7800b372128b1762551d22d1986be3bc6f87f3a4fbf56de5493a73ea47877586cffc8ed3136aa381047e4c033
7
- data.tar.gz: 8ba70f3cc099063866ce21faffb0eedae4ec2ed1fa7a030db945d54d154f8c0ca864a6fc3471b8c6ed53aa5fc05c3474c9cc10850176f1a89eb0108d944172be
6
+ metadata.gz: 7ed99b25ba385cc8596c38036a3c025d8bc0f5cf98f62a93a662dd023c025d71b59233d0e0f8d15983e34e13daed9ab80495bf1f1f9bdad830a7a1ab40b2864a
7
+ data.tar.gz: ea777d24961d8bcb78b1e10d7a94370ba6b64f59bdeb8eaf52c6c892f32838654badffce4360f6c19b8c4d0e27919a9f04098777b511b67b28c21918d403c8f5
data/CHANGELOG.md CHANGED
@@ -7,6 +7,259 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.3.0] - 2026-12-01
11
+
12
+ ### Added
13
+
14
+ - **The Route 53 hosted zone and its record sets.** `Route53::HostedZone`
15
+ writes the `AWS::Route53::HostedZone` as the CDK's HostedZone does
16
+ (aws-route53/lib/hosted-zone.ts, read at
17
+ c070afb54b9e4dbddd52a85a21077fe970354985): the zone name validated by
18
+ Route 53's rules and given the trailing dot when it lacks one,
19
+ `comment:` in `HostedZoneConfig`, `query_logs_log_group_arn:` in
20
+ `QueryLoggingConfig`, and, with `vpcs:`, the `VPCs` pairs that make the
21
+ zone private — each entry a created or looked-up `EC2::Vpc`, a
22
+ `{ vpc_id:, region: }` Hash or a bare id, with the region the VPC's own
23
+ stack names or the stack's `AWS::Region` reference
24
+ (hosted-zone.ts:287-290). The record sets are the CDK's standalone
25
+ classes, `Route53::RecordSet` and the A, AAAA, CNAME, TXT, SRV, CAA,
26
+ Amazon CAA, MX and NS records, each built with the zone as its scope and
27
+ writing its `AWS::Route53::RecordSet` under the zone's namespace, the
28
+ record name qualified against the zone name (util.ts:42-55) and the CDK's
29
+ default ttl of 1800 seconds. `HostedZone.from_hosted_zone_attributes(
30
+ zone_id:, zone_name:)` is the import that answers the id, the name and
31
+ the ARN, synthesizes nothing, and is the shape the hosted-zone lookup
32
+ will one day fill on the D-022 machinery. Not carried: the delegation
33
+ grant and the cross-account delegation pieces (the Grant here carries no
34
+ conditions and this tool has no custom resources), DNSSEC and the key
35
+ signing key, the alias-record target classes, the record routing
36
+ policies, and the PublicHostedZone and PrivateHostedZone classes beside
37
+ the base one. 24 of the origins' 97 cases are ported
38
+ (test/cdk/constructs/hosted_zone_test.rb: hosted-zone.test.ts,
39
+ record-set.test.ts).
40
+ - **`ruby-cdk drift [STACK...]` — stack drift detection against
41
+ CloudFormation.** Starts drift detection (`DetectStackDrift`), polls status
42
+ to completion (`DescribeStackDriftDetectionStatus`, 2 s interval, 5 min
43
+ limit), and reads every page of resource drifts
44
+ (`DescribeStackResourceDrifts`, never truncating across `NextToken`), matching
45
+ the CDK's drift action (`packages/@aws-cdk/toolkit-lib/lib/api/drift/drift.ts`,
46
+ `drift-formatter.ts`, `toolkit.ts:465-535`, and `packages/aws-cdk/lib/cli/cdk-toolkit.ts:654-661`,
47
+ read at `f7c9dca95f440a076c2abd61b66b984624b8548e`). Reports modified
48
+ resources with property-level diffs, deleted resources, and — under
49
+ `--verbose` — in-sync and unchecked resources (resources in the synthesized
50
+ template with no drift record or `UNKNOWN` status), ignoring
51
+ `AWS::CDK::Metadata`. Exits 0 unless `--fail` is passed and at least one
52
+ resource drifted (`MODIFIED` or `DELETED`). Uses deploy/diff stack selection
53
+ (`--all`, `-e/--exclusively`), prints human text on standard error, and under
54
+ `--json` emits one structured JSON object per stack on standard output. The
55
+ CDK's three drift test suites are ported (`test/cdk/cli/drift_test.rb`: 35
56
+ cases in the origins, 33 ported).
57
+ - **`ruby-cdk watch`, the CDK's development loop** (read at
58
+ f7c9dca95f440a076c2abd61b66b984624b8548e, cdk-toolkit.ts:828-903 and
59
+ toolkit-lib toolkit.ts:1283-1467). One synthesis and deploy up front —
60
+ reusing the startup synthesis, as the CDK reuses its startup assembly —
61
+ then the watched files are polled, and every change synthesizes and deploys
62
+ again, hotswapping by default (the CDK's `determineHotswapMode` with watch:
63
+ true: neither flag is HOTSWAP_ONLY, `--no-hotswap` is FULL_DEPLOYMENT,
64
+ `--hotswap-fallback` is FALL_BACK, the pair is refused). The inner deploy
65
+ goes through the same engine, clients and options as `deploy`, and never
66
+ asks: `yes: true`, the CDK's `RequireApproval.NEVER`
67
+ (cdk-toolkit.ts:1533). What is watched is the app file and every asset
68
+ source directory the manifest records, the synthesis out directory and
69
+ hidden files left out — the two exclusions the CDK always adds itself
70
+ (toolkit.ts:1335, 1338) — re-derived after every synthesis, so an asset an
71
+ edit adds joins the watched set. A failing deploy and an app file broken
72
+ mid-edit are reported and watched through (the CDK's `invokeSafe`,
73
+ toolkit.ts:1384-1396, and `invokeDeployFromWatch`'s catch,
74
+ cdk-toolkit.ts:1546-1549); only the startup synthesis and the option checks
75
+ are fatal. A change the fast path refuses is reported and ignored, and the
76
+ loop goes on. The lines are the CDK's own, with this tool's command named:
77
+ the observed files (cdk-toolkit.ts:891), the first deploy ("Triggering
78
+ initial 'cdk deploy'", 883), a detected change with its type — add, change,
79
+ unlink (893) — and the queued deploy for changes that arrived during one
80
+ ("Detected file changes during deployment. Invoking 'cdk deploy' again",
81
+ 856). Two things are this tool's own, recorded here: the loop polls mtimes
82
+ in process, starting no watcher and no process (architecture section 8),
83
+ where the CDK's watcher is chokidar, event driven — so `--interval
84
+ SECONDS` (default 1) is a flag of ours, one the CDK does not take; and the
85
+ CDK's include/exclude globs from cdk.json have nothing to live in here, so
86
+ the file set is the derivation above. 21 tests, in process, with the sleep
87
+ faked and the changes scripted into temporary directories
88
+ (test/unit/cli/watch_test.rb).
89
+ - **`ruby-cdk import STACK` — existing resources under a stack, the CDK's
90
+ command.** The resources of the synthesized template the deployed stack
91
+ does not hold are the import candidates (the CDK's
92
+ `discoverImportableResources`, importer.ts:247-282, read at
93
+ f7c9dca95f440a076c2abd61b66b984624b8548e); each candidate is asked for the
94
+ properties that identify it — a set the template's literals already
95
+ satisfy as a yes-or-no question, otherwise one line per property, compound
96
+ sets named `HostedZoneId+Name` — or read from `--resource-mapping PATH` /
97
+ `--resource-mapping-inline JSON` (the CDK's mapping forms;
98
+ `--record-resource-mapping PATH` writes what was collected and imports
99
+ nothing). Without a terminal and without a mapping the command refuses, in
100
+ the CDK's words. Updates and deletes found beside the additions are said
101
+ and asked about ("Perform import?"), `--force` importing without the
102
+ question. The engine's `Deployer#import` runs it as one change set of type
103
+ IMPORT carrying `ResourcesToImport` — logical id, type from the template,
104
+ the identifier properties; never a bare physical id, which is what AWS's
105
+ `ResourceToImport` is (importer.ts:448-454) — its template the deployed
106
+ one with the additions in it, `DeletionPolicy: Retain` added where none is
107
+ (importer.ts:306-324, 522-531), the stack's parameters going back as
108
+ `UsePreviousValue`, executed and followed like a deploy's, with §14's exit
109
+ codes and the outputs afterwards; the post-import lines are the CDK's, the
110
+ "Finish with a `ruby-cdk deploy` now?" question included. The port gained
111
+ two things for it: `create_change_set` takes `resources_to_import` (the
112
+ adapter sends the request's field; the fake records it, an execution puts
113
+ the resources on the fake stack, and `describe_change_set` answers
114
+ `Import` actions with their logical ids), and
115
+ `resource_identifier_summaries(template)` asks `GetTemplateSummary` for
116
+ the property sets an existing resource of each type is identified by; the
117
+ Output port gained `request(question)`, the free-form question the typed
118
+ identifiers go through. The other flags are the CDK's that fit:
119
+ `--change-set-name`, `--no-execute`, `--notification-arns`. The origin's
120
+ import cases are ported (test/cdk/cli/import_test.rb: 20 in the three
121
+ origins, 18 ported; the migrate path and the stack-level notification-ARN
122
+ merge have no counterpart here).
123
+ - **The three change-set options the architecture listed as not in this
124
+ version, and the template URL.** `deploy --notification-arns ARN[,ARN]`
125
+ sends the SNS topics as `NotificationARNs` on the change set and the direct
126
+ update alike, validated per ARN as the CDK validates them
127
+ (`validateSnsTopicArn`, util/cloudformation.ts:11-20, read at
128
+ f7c9dca95f440a076c2abd61b66b984624b8548e) before any client is built;
129
+ `deploy --rollback-trigger-alarm-arns ARN[,ARN]` and
130
+ `--monitoring-time-minutes N` — the CDK's rollback triggers, which the
131
+ pinned CLI does carry (parse-command-line-arguments.ts:521-532), with its
132
+ `none` clearing, its five-alarms and 0-to-180-minutes bounds, and
133
+ `RollbackConfiguration` on the same two requests;
134
+ `deploy --import-existing-resources` sends `ImportExistingResources` on
135
+ every change set, as the CDK names the field there and nowhere else
136
+ (deploy-stack.ts:640). When the notification ARNs or the rollback
137
+ configuration are the deployed ones and nothing else differs, the deploy is
138
+ skipped, as the CDK's skip rule decides (deploy-stack.ts:992-994,
139
+ 1079-1089). The origin's eight cases are ported
140
+ (test/cdk/cli/deploy_stack_test.rb: 120 in the origin, 49 ported).
141
+ - **A template too large for a request goes to the bucket by the URL the
142
+ object-store port answers.** The port gains `object_url`, and the adapter
143
+ derives the answer from the S3 client's own region and endpoint
144
+ configuration — the CDK's shape (the endpoint origin, then bucket and key,
145
+ template-body-parameter.ts `restUrlFromManifest`), so another partition
146
+ shows in the host and an overridden endpoint (AWS_ENDPOINT_URL_S3,
147
+ AWS_ENDPOINT_URL — the emulator scenario) names itself. Until now the URL
148
+ was written by hand in the commercial partition's virtual-hosted shape,
149
+ an assumption recorded in architecture section 8; it is gone.
150
+
151
+ ### Fixed
152
+
153
+ - **`diff --fail-on=broadening` now counts security-group rule additions and
154
+ the IAM Identity Center additions the CDK counts.** The security view read
155
+ only the policy documents and the managed policy attachments, so a rule
156
+ added to a group's lists, a new `AWS::EC2::SecurityGroupIngress` or
157
+ `AWS::EC2::SecurityGroupEgress` resource, and a new `AWS::SSO::PermissionSet`,
158
+ `AWS::SSO::Assignment` or
159
+ `AWS::SSO::InstanceAccessControlAttributeConfiguration`, made none of it:
160
+ no exit 1, no stack counted under `--security-only`, no row in the view.
161
+ They now carry the same weight as in the CDK's `permissionsBroadened`
162
+ (diff/types.ts:125-127, iam-changes.ts:75-82, security-group-changes.ts:95-98,
163
+ read at f7c9dca95f440a076c2abd61b66b984624b8548e), with its "Security Group
164
+ Changes" and "IAM Identity Center Changes" tables beside the IAM ones, and
165
+ the additions and removals in `--json`. A rule taken away is a security
166
+ change that is not a broadening, as there. The CDK's broadening and
167
+ security-group cases are ported (test/cdk/diff/diff_template_test.rb, three
168
+ origins now: 41 cases, 36 ported).
169
+ - **The function construct validates the name and the description as the CDK
170
+ does** (`function.ts:1009-1022`): a literal name over 64 characters or with
171
+ characters outside letters, numbers, hyphens and underscores is refused at
172
+ construction, as is a description over 256. Until now only the String type
173
+ was checked.
174
+
175
+ ### Added
176
+
177
+ - **`EC2::Vpc.from_lookup` and `ruby-cdk lookup` — the context providers of
178
+ decision D-022.** A lookup is a command, never a side effect of synth:
179
+ `EC2::Vpc.from_lookup(stack, "Net", vpc_id: "vpc-…")` (optionally `tags:`,
180
+ String or Symbol names and values) reads its answer from
181
+ `cdk.context.json` beside the app file, and on a cache miss refuses with
182
+ the command that answers it — synthesis calls no AWS and reads nothing
183
+ else. `ruby-cdk lookup` synthesizes the app once with the cache as it is,
184
+ answers every query the cache does not hold — the VPC named by the id, or
185
+ a tags-only query that must match exactly one VPC, through the EC2 API
186
+ (`describe_vpcs`, `describe_subnets`, `describe_route_tables`) for the
187
+ stack's account and region, the credentials checked against the query's
188
+ environment as a deploy into an `env` is — writes each answer into the
189
+ cache as soon as it is read, and synthesizes again until the app comes
190
+ whole. The looked-up VPC is the CDK's `LookedUpVpc`
191
+ (vpc.ts:2745-2820 at the pinned commit): it synthesizes no resources, and
192
+ what it answers — the vpc id and CIDR, the zone names, the subnet ids
193
+ grouped by reachability type public/private/isolated — are literals, so
194
+ what consumes the VPC writes the ids directly, with no `Fn::GetAtt` and
195
+ no `Fn::ImportValue`. The query needs the stack's concrete `env`, as the
196
+ CDK needs a concrete account and region for a context lookup
197
+ (context-provider.ts:167-172). The cache file is one JSON object whose
198
+ keys carry the provider, the account and the region the answer is valid
199
+ for and the query's arguments (sorted, colons quoted as the CDK's keys
200
+ are), so the same query always hits, a wrong-environment read is
201
+ impossible, and two machines with the same answers hold the same bytes;
202
+ it carries no timestamp, and it is committed. `aws-sdk-ec2` joins the
203
+ runtime gems — the fifth (D-012, owner-delegated), loaded only by the
204
+ lookup command, so `synth` never loads the AWS SDK and a deploy never
205
+ loads the EC2 gem.
206
+ - **`SSM::Parameter.from_lookup` — the second context provider, on the
207
+ machinery of D-022.** `SSM::Parameter.from_lookup(stack, "Pwd",
208
+ name: "/app/db-password")` reads an existing parameter's answer from
209
+ `cdk.context.json` beside the app file and answers literals — the value,
210
+ the type as AWS reads it (`String`, `StringList`), and the parameter's
211
+ name — synthesizing no resource, because the parameter exists: a consumer
212
+ writes the value literally, the way a consumer of a looked-up VPC writes
213
+ its ids. On a cache miss, synthesis refuses with the command to run. The
214
+ CDK's origin is `StringParameter.valueFromLookup` (parameter.ts:637-661 at
215
+ the pinned commit), whose provider makes one call — `ssm get_parameter`
216
+ with the Name and no WithDecryption (toolkit-lib ssm-parameters.ts) — and
217
+ that is the one call the lookup command makes, through the new SSM adapter
218
+ beside the EC2 one. A parameter that is not there is a refusal naming what
219
+ is checkable (the name, the profile, the region); a SecureString is
220
+ refused — read without decryption, as the CDK's provider reads it, the
221
+ answer is a per-call KMS ciphertext, which the committed cache must not
222
+ carry, and the dynamic reference `{{resolve:ssm-secure:…}}` reads the
223
+ value at deploy time. The CDK's `defaultValue` (its
224
+ `dummy-value-for-…` dummy) and `additionalCacheKey` are not carried: a
225
+ parameter that is not there stops the synthesis, and the cache key carries
226
+ the whole query already. `aws-sdk-ssm` joins the runtime gems — the sixth
227
+ (D-012, owner-delegated), dragging nothing new (aws-sdk-core and aws-sigv4
228
+ only), loaded only by the lookup command like the EC2 gem.
229
+ - **`EC2::Vpc`, the defaults slice.** The CDK's Vpc (aws-ec2/lib/vpc.ts,
230
+ read at the pinned commit) for its default behaviour: an
231
+ `AWS::EC2::VPC` with `CidrBlock` 10.0.0.0/16, DNS support and DNS
232
+ hostnames on; an `AWS::EC2::InternetGateway` and its
233
+ `AWS::EC2::VPCGatewayAttachment` when any subnet can reach the internet;
234
+ one public and one private subnet per availability zone (one public and
235
+ one isolated when `nat_gateways: 0`), each with its `AWS::EC2::RouteTable`
236
+ and `AWS::EC2::SubnetRouteTableAssociation`; a public subnet's
237
+ `0.0.0.0/0` route to the gateway, dependent on the attachment; and an
238
+ `AWS::EC2::NatGateway` with its `AWS::EC2::EIP` in every public subnet —
239
+ one per zone unless `nat_gateways:` lowers the count — with every private
240
+ subnet routed to the gateway of its own zone, falling back round-robin.
241
+ Options: `cidr:`, `max_azs:`, `availability_zones:`, `dns_support:`,
242
+ `dns_hostnames:`, `default_instance_tenancy:`, `subnet_configuration:`
243
+ (the CDK's SubnetConfiguration: `name`, `subnet_type`, `cidr_mask`,
244
+ `reserved`, `map_public_ip_on_launch`), `nat_gateways:` and
245
+ `nat_gateway_subnets:`. The zone names, when none are given, are the
246
+ three the CDK's synthesis writes when its context cache is empty
247
+ (`dummy1a`, `dummy1b`, `dummy1c`); the created path reads no context, so
248
+ `availability_zones:` is the way to write real ones, and `from_lookup`
249
+ (below) is the way to take an existing VPC's. The CIDR carving is
250
+ the CDK's network-util port: configurations with a `cidr_mask` carve in
251
+ order, the rest share what is left (a /19 each for the default). Accessors:
252
+ `vpc_id`, `vpc_arn`, `vpc_cidr_block`, `vpc_default_network_acl`,
253
+ `vpc_default_security_group`, `internet_gateway_id`,
254
+ `public_subnet_ids`, `private_subnet_ids`, `isolated_subnet_ids`,
255
+ `azs`, `dns_support_enabled`, `dns_hostnames_enabled`.
256
+ `restrict_default_security_group: true` is refused — the CDK writes a
257
+ Lambda-backed custom resource for it, and this tool has no custom
258
+ resources; `false` is accepted and is the behaviour here. The CDK's own
259
+ defaults-and-subnetting cases are ported
260
+ (`test/cdk/constructs/vpc_test.rb`: 199 cases at the pinned commit,
261
+ 45 ported).
262
+
10
263
  ## [0.2.0] - 2026-11-30
11
264
 
12
265
  ### Added
data/README.md CHANGED
@@ -8,7 +8,7 @@ Infrastructure as code in **pure Ruby**, in the style of the AWS CDK: define sta
8
8
 
9
9
  The AWS CDK's programming model, reimplemented in Ruby. Your app file creates one `RubyCdk::App`; stacks are classes with a `build` method that declares resources, parameters and outputs; synthesis turns the object tree into CloudFormation templates whose every byte is specified, and the `ruby-cdk` CLI deploys them through change sets. Properties are written with CloudFormation's names, or in `snake_case` — the keys are normalized against AWS's own resource schemas before anything is written.
10
10
 
11
- "Measured against the CDK" is a number, not a claim. The CDK's own test suites are ported and run in the default gate (`rake parity`): 2,084 cases, 666 of them ported, every ported case passing, and each of the others listed in a ported file's header with the reason it is not ported — every header's origin count held to the counted fact in `test/cdk/origins.json`, so the numbers are recountable, not remembered. The whole suite — 2,228 runs, 25,320 assertions — passes with no AWS credential reachable; the same gate keeps line coverage above 98% over a floor of 85%, and proves that every example synthesizes byte-identical output across two runs with different Ruby hash seeds.
11
+ "Measured against the CDK" is a number, not a claim. The CDK's own test suites are ported and run in the default gate (`rake parity`): 2,445 cases, 803 of them ported, every ported case passing, and each of the others listed in a ported file's header with the reason it is not ported — every header's origin count held to the counted fact in `test/cdk/origins.json`, so the numbers are recountable, not remembered. The whole suite — 2,598 runs, 26,918 assertions — passes with no AWS credential reachable; the same gate keeps line coverage above 98% over a floor of 85%, and proves that every example synthesizes byte-identical output across two runs with different Ruby hash seeds.
12
12
 
13
13
  ## Install
14
14
 
@@ -152,6 +152,9 @@ Yes executes the change set and follows the operation, printing each event as it
152
152
  - `--outputs-file PATH` — the outputs of each stack as JSON.
153
153
  - `--no-execute` — create the change set and leave it for the console.
154
154
  - `--on-failure DELETE|ROLLBACK|DO_NOTHING` — what CloudFormation does when a first deploy fails (default `DELETE`, so a failed creation cleans up after itself).
155
+ - `--notification-arns ARN[,ARN]` — SNS topics CloudFormation notifies with the stack's events (the CDK's flag). Not given, whatever the stack carries is left alone; an ARN that is not an SNS topic's is refused before anything is asked of AWS.
156
+ - `--rollback-trigger-alarm-arns ARN[,ARN]` and `--monitoring-time-minutes N` — the CloudWatch alarms CloudFormation monitors during the deployment, rolling it back when one goes ALARM (the CDK's rollback triggers: at most five alarms, zero to 180 whole monitoring minutes, and the minutes need the alarms). `--rollback-trigger-alarm-arns none` clears what the stack has; not given, nothing is managed and whatever the stack carries stays.
157
+ - `--import-existing-resources` — the change set imports resources that already exist instead of failing on them.
155
158
  - `--force` — deploy even when the deployed template, parameters and tags are unchanged (unchanged means the deploy is skipped).
156
159
  - `--all`, `-e/--exclusively` — every stack of the app in dependency order, or only the ones named.
157
160
  - `--hotswap` / `--hotswap-fallback` — the development-loop fast path; see below.
@@ -163,6 +166,14 @@ Yes executes the change set and follows the operation, printing each event as it
163
166
 
164
167
  A hotswap puts the stack outside what CloudFormation last deployed (drift); the next ordinary deploy brings it back in line. Do not use either flag on a production stack.
165
168
 
169
+ **The development loop.** `bundle exec ruby-cdk watch` is the CDK's `cdk watch`: it synthesizes and deploys once up front, then polls the app's files and, on a change, synthesizes and deploys again — hotswapping by default — until you interrupt it. It takes the stack selection `deploy` takes (`--all`, `-e/--exclusively`), the deploy flags the inner deploy uses (`--parameters`, `--tags`, `--force`, and the global `--profile`, `--region`, `--account`), and `--hotswap` / `--no-hotswap` / `--hotswap-fallback` (`--hotswap` is on by default; `--no-hotswap` deploys every change through a change set). What is watched is the app file and every asset source directory the manifest records — the synthesis output directory and hidden files are left out, as the CDK's watch leaves its own out — and a deploy that fails, like an app file broken mid-edit, is printed and watched through: the next change tries again. The inner deploy never asks (`--yes` is the watch's): the CDK's watch deploy is built with `RequireApproval.NEVER`, and a loop that stops to ask is not a watch. A change the fast path refuses is reported and ignored, and the watch goes on. The poll runs every `--interval SECONDS` (one second by default) — this flag is this tool's own: the CDK's watcher is a native file watcher, and ours polls in process, starting no watcher of its own. The loop prints the CDK's own lines:
170
+
171
+ 'watch' is observing the file '/path/to/cdk.rb' for changes
172
+ Triggering initial 'ruby-cdk deploy'
173
+ Detected change to '/path/to/cdk.rb' (type: change). Triggering 'ruby-cdk deploy'
174
+
175
+
176
+
166
177
  **Preview a deploy.** `bundle exec ruby-cdk diff` compares each stack's synthesized template with the one CloudFormation holds: per resource and per changed property path, the properties whose change replaces the resource marked as such, and the security view — the IAM statements a deployment adds or takes away. It reads the deployed template and writes nothing. The command exits 0 whether or not there are differences; these options decide otherwise, as the CDK's do:
167
178
 
168
179
  - `--fail` — exit 1 when a stack differs.
@@ -170,8 +181,19 @@ A hotswap puts the stack outside what CloudFormation last deployed (drift); the
170
181
  - `--security-only` — the security view alone.
171
182
  - `--json` — one object per stack on standard output: the changes with their replacement facts, the security view, and the destructive changes.
172
183
 
184
+ **Detect live drift.** `bundle exec ruby-cdk drift [STACK...]` runs CloudFormation drift detection on each selected stack (`DetectStackDrift`, polling `DescribeStackDriftDetectionStatus` until complete, then reading every page of `DescribeStackResourceDrifts`). It prints modified resources with their property differences, deleted resources, and the per-stack and overall drift counts on standard error; `--verbose` also shows in-sync resources, unchecked resources (template resources with no drift record or `UNKNOWN` status), and detection progress; `--quiet` omits clean stacks; `--json` writes one structured object per stack to standard output. As in the CDK, the command exits 0 even when drift is found unless `--fail` is passed, in which case any `MODIFIED` or `DELETED` resource exits 1 (`UNKNOWN` and unchecked resources do not fail it). Stack selection matches `deploy` and `diff` (`--all`, `-e/--exclusively`).
185
+
173
186
  `bundle exec ruby-cdk destroy` prints what the stack retains, then asks you to type the stack's name — a yes/no is not enough for an irreversible act — and deletes it. `--yes` skips the question; a termination-protected stack is refused.
174
187
 
188
+ **Bring existing resources in.** `bundle exec ruby-cdk import STACK` adopts resources that already exist in AWS into the stack, the CDK's `cdk import`. The command synthesizes the app, compares the template against the one CloudFormation holds, and the resources the stack does not have yet are the candidates. Each one is asked for the properties that identify it — a queue's `QueueName`, a table's `TableName`, a Route53 key-signing key's `HostedZoneId` and `Name` together — as a yes/no when the template already spells the value out, otherwise one line to type. When the template also holds updates or deletes, the command shows them and asks before importing; `--force` imports anyway. For scripts, the questions have a file form:
189
+
190
+ ```sh
191
+ bundle exec ruby-cdk import my-app --resource-mapping mapping.json
192
+ # mapping.json: { "MyQueue": { "QueueName": "my-existing-queue" } }
193
+ ```
194
+
195
+ `--resource-mapping-inline '{"MyQueue":{"QueueName":"my-existing-queue"}}'` is the same on the command line, and `--record-resource-mapping PATH` writes what was collected instead of importing. The import itself is one CloudFormation change set of type IMPORT: its template is the deployed one with the additions in it, every imported resource kept (`DeletionPolicy: Retain`) so a failed operation loses nothing, executed after the same approval question a deploy asks (`--yes` answers it) and followed to the end like a deploy. Without a terminal, a mapping is required. After an import that left pending updates behind, the command offers to finish with a `ruby-cdk deploy` — the import puts the resources under the stack as they are today, and the deploy brings the rest of the template in line.
196
+
175
197
  `examples/hello` is this same app kept by hand, with more commentary on what each line does, and the generated project's README carries the three commands with the notes a first deploy needs: where a stack without an `env` deploys, what deploy asks, and that an asset (`asset.zip`) needs a pinned env, because the bucket its zip lands in is named after the account and the region and synthesis never calls AWS to discover them.
176
198
 
177
199
  ## Validation before deploy
@@ -283,22 +305,23 @@ That test runs:
283
305
 
284
306
  - Ruby 4.0 or newer. The gemspec refuses older (`required_ruby_version ">= 4.0.0"`).
285
307
  - AWS credentials reachable through the SDK's standard chain — environment, shared files, SSO — narrowed by `--profile`. Nothing is stored, nothing is logged, and synthesis never calls AWS.
286
- - The four runtime gems (`aws-sdk-cloudformation`, `aws-sdk-s3`, `thor`, `rubyzip`) install with the gem. No Node, no build tools, no native extensions.
308
+ - The six runtime gems (`aws-sdk-cloudformation`, `aws-sdk-s3`, `aws-sdk-ec2`, `aws-sdk-ssm`, `thor`, `rubyzip`) install with the gem; the EC2 and SSM ones are loaded only by `ruby-cdk lookup`. No Node, no build tools, no native extensions.
287
309
 
288
310
  ## Status
289
311
 
290
312
  Works today:
291
313
 
292
- - `ruby-cdk synth`, `validate`, `ls`, `diff`, `deploy`, `destroy`, `new`, `bootstrap` (`ruby-cdk help COMMAND` for each). `new PROJECT` scaffolds an app: `cdk.rb`, one stack with one private bucket, a Gemfile, `.gitattributes` and `.gitignore`.
314
+ - `ruby-cdk synth`, `validate`, `ls`, `diff`, `drift`, `deploy`, `destroy`, `import`, `watch`, `new`, `bootstrap`, `lookup` (`ruby-cdk help COMMAND` for each). `new PROJECT` scaffolds an app: `cdk.rb`, one stack with one private bucket, a Gemfile, `.gitattributes` and `.gitignore`.
293
315
  - Schema-backed synthesis with the normalizer and rules V1–V23.
294
316
  - File assets with content hashing, zipping at deploy, and the bootstrap bucket; templates above 51,200 bytes deploy by URL.
295
317
  - The nag rule pack — seventeen security rules over every example's synthesized template, run with `rake nag`, suppressed per resource or in `.ruby-cdk/nag.yml`.
296
318
  - The test kit, `RubyCdk::Test`, with the CDK's assertions ported.
297
319
  - Two scenarios run end to end in CI against the AWS Emulator, which answers as CloudFormation does (`rake integration`), and the same two against the real sandbox before a release: a stack created, updated through a change set, deployed again with nothing changed and destroyed; and a Lambda function whose code is a zipped asset, bootstrapped, created, updated through `--hotswap`, left untouched by `--hotswap` when a change is refused, updated through `--hotswap-fallback`, and destroyed.
298
- - Curated constructs — `S3::Bucket`, `IAM::Role`, `Lambda::Function`, `DynamoDB::Table`, `SQS::Queue`, `SNS::Topic`, `Logs::LogGroup`, `SSM::Parameter`, a `SecretsManager::Secret` reference, `Events::Rule`, `ApiGateway::RestApi`, `KMS::Key` — with explicit grants, and `ruby-cdk diff` against the deployed template. `KMS::Key` brings customer-managed encryption to the bucket (`encryption: :kms`, `encryption_key:`), the queue (`encryption:`, `encryption_master_key:`), the topic (`master_key:`) and the table (`encryption:`, `encryption_key:`), with the grants on the key the CDK's own grants add.
320
+ - Curated constructs — `S3::Bucket`, `IAM::Role`, `Lambda::Function`, `DynamoDB::Table`, `SQS::Queue`, `SNS::Topic`, `Logs::LogGroup`, `SSM::Parameter`, a `SecretsManager::Secret` reference, `Events::Rule`, `ApiGateway::RestApi`, `KMS::Key`, `EC2::Vpc` — with explicit grants, and `ruby-cdk diff` against the deployed template. `KMS::Key` brings customer-managed encryption to the bucket (`encryption: :kms`, `encryption_key:`), the queue (`encryption:`, `encryption_master_key:`), the topic (`master_key:`) and the table (`encryption:`, `encryption_key:`), with the grants on the key the CDK's own grants add. `EC2::Vpc` is the CDK's defaults: the VPC, the Internet Gateway and its attachment, the public and private subnets per availability zone with their route tables and routes, and a NAT Gateway and EIP per zone — `max_azs:`, `availability_zones:`, `subnet_configuration:` (name, `subnet_type`, `cidr_mask`, `reserved`), `nat_gateways:`, `nat_gateway_subnets:`, `cidr:`, `dns_support:`, `dns_hostnames:` — with the subnet ids and the zone names on the construct. `Route53::HostedZone` is the CDK's hosted zone: the zone name validated and given the trailing dot (`add_trailing_dot:` keeps it off), `comment:`, `query_logs_log_group_arn:`, and `vpcs:` for a private zone — each entry a `Vpc`, a `{ vpc_id:, region: }` Hash or a bare id — with the zone id, ARN and name on the construct, and the CDK's record sets beside it: `RecordSet` and the A, AAAA, CNAME, TXT, SRV, CAA, Amazon CAA, MX and NS records, built with the zone as their scope, the record name qualified against the zone name and the CDK's 1800-second default ttl. `Route53::HostedZone.from_hosted_zone_attributes(zone_id:, zone_name:)` imports a zone by attributes — no resources, the shape the hosted-zone lookup will one day fill.
321
+ - Lookups of existing resources on one machinery, the CDK's context providers as decision D-022 shapes them: `EC2::Vpc.from_lookup(stack, "Net", vpc_id: "vpc-…")` (optionally `tags:`) reads its answer from `cdk.context.json` beside the app file — the VPC's id and CIDR, the zone names, and the subnet ids grouped by reachability type, as literals: a looked-up VPC synthesizes no resources, and what consumes it writes the ids directly. The second provider reads an SSM parameter: `SSM::Parameter.from_lookup(stack, "Pwd", name: "/app/db-…")` answers the value, the type as AWS reads it (`String`, `StringList`), and the parameter's name, as literals — a looked-up parameter synthesizes no resource, and what consumes it writes the value directly; a SecureString is refused (read without decryption, as the CDK's provider reads it, the answer is a per-call KMS ciphertext), and the dynamic reference `{{resolve:ssm-secure:…}}` reads one at deploy time. On a cache miss, synthesis refuses with the command to run; `ruby-cdk lookup` performs the queries through the EC2 API (one VPC, or a tags-only query that must match exactly one VPC) and the SSM API (`get_parameter`) for the stack's account and region, writes the answers into `cdk.context.json`, and synthesizes again. The file is part of the app: commit it, so two machines read the same answers and synthesize the same template. An entry is keyed by its environment, and a lookup never reads one written for another account or region.
299
322
  - Two examples that put the constructs in one stack: `examples/app` — a function, a table, a bucket and one least-privilege role for them all — and `examples/api` — a function behind a REST API and a scheduled rule, with the queue, topic and parameter grants and the two Lambda permissions a service principal needs to call a function itself. Both are under the determinism and nag gates.
300
323
 
301
- Next: context providers (lookups of existing resources). `deploy --hotswap` is there (see "The hotswap fast path" above).
324
+ Next: the hosted-zone lookup on the same lookup machinery, and the context commands of the CDK's `cdk context`. `deploy --hotswap` is there (see "The hotswap fast path" above).
302
325
 
303
326
  And the honest part: this is 0.1.0. The APIs — `Stack`, `App`, `Test`, the constructs, the CLI options — may still change between versions. Pin the version you build against.
304
327
 
@@ -129,7 +129,9 @@ module RubyCdk
129
129
  def readable_stat(path, relative)
130
130
  File.lstat(path)
131
131
  rescue SystemCallError => error
132
+ # :nocov: race condition where an entry disappears between Dir.children and File.lstat
132
133
  raise SourceNotFoundError, "Asset entry #{relative} cannot be read (#{error.message})"
134
+ # :nocov:
133
135
  end
134
136
 
135
137
  def readable_digest(path, relative)
@@ -161,7 +163,9 @@ module RubyCdk
161
163
  end
162
164
  return if relative.valid_encoding?
163
165
 
166
+ # :nocov: macOS APFS/HFS+ rejects non-UTF-8 filenames at the kernel level (EILSEQ)
164
167
  raise UnsupportedEntryError, "A file name that is not valid UTF-8 cannot be in an asset: #{relative.inspect}"
168
+ # :nocov:
165
169
  end
166
170
 
167
171
  # The way git stores a mode: 0755 when the owner may execute the file,
@@ -63,13 +63,9 @@ module RubyCdk
63
63
  # of the template. The key is templates/<stack name>/<sha256>.json, the
64
64
  # SHA-256 of the body, so the same template lands on the same key and the
65
65
  # uploader leaves a key that is already there alone — the second deploy of
66
- # the same template puts nothing. Answers the address of the object,
67
- # https://<bucket>.s3.<region>.amazonaws.com/<key>, the one the change set
68
- # carries as TemplateURL. That address is the commercial partition's shape,
69
- # written from the bucket's name and region, not read from the SDK: under
70
- # another partition, or with the endpoint overridden (the emulator
71
- # scenario), CloudFormation would not resolve it — the assumption is
72
- # recorded in architecture section 8.
66
+ # the same template puts nothing. Answers the address the store would
67
+ # serve the object back from, the port's object_url, which the change set
68
+ # carries as TemplateURL.
73
69
  #
74
70
  # The bucket is the stack's own, named for its env as an asset bucket is,
75
71
  # and owner must be the stack's env account, as publish requires. The
@@ -94,7 +90,7 @@ module RubyCdk
94
90
  bucket = bucket_name(account, env.region)
95
91
  key = "templates/#{stack.stack_name}/#{Digest::SHA256.hexdigest(template)}.json"
96
92
  Uploader.new(store:, owner: account).upload_body(key, body: template, bucket: bucket)
97
- "https://#{bucket}.s3.#{env.region}.amazonaws.com/#{key}"
93
+ store.object_url(bucket, key)
98
94
  end
99
95
  end
100
96
 
@@ -17,11 +17,29 @@ module RubyCdk
17
17
  RubyCdk::Deploy::Sdk.resolve_region(profile: profile, region: region)
18
18
  end
19
19
 
20
- # The CloudFormation client and the object store of a region.
21
- def self.clients(profile:, region:)
22
- adapters
23
- RubyCdk::Deploy::Sdk.clients(profile: profile, region: region)
24
- end
20
+ # The CloudFormation client and the object store of a region.
21
+ def self.clients(profile:, region:)
22
+ adapters
23
+ RubyCdk::Deploy::Sdk.clients(profile: profile, region: region)
24
+ end
25
+
26
+ # The EC2 client the lookup command reads its answers through (D-022).
27
+ # Loaded here, and only when the lookup command asks, so that `synth`
28
+ # never loads the AWS SDK and a deploy never loads the EC2 gem
29
+ # (architecture principle 10).
30
+ def self.ec2_client(profile:, region:)
31
+ require_relative "../deploy/ec2_adapter"
32
+ RubyCdk::Deploy::Sdk.ec2_client(region: region, profile: profile)
33
+ end
34
+
35
+ # The SSM client the lookup command answers a parameter query through
36
+ # (D-022). Loaded here, and only when the lookup command asks, so that
37
+ # `synth` never loads the AWS SDK and a deploy never loads the SSM gem
38
+ # (architecture principle 10).
39
+ def self.ssm_client(profile:, region:)
40
+ require_relative "../deploy/ssm_adapter"
41
+ RubyCdk::Deploy::Sdk.ssm_client(region: region, profile: profile)
42
+ end
25
43
 
26
44
  # The adapters are loaded here, and only when a command needs a client,
27
45
  # so that `version` and `synth` never load the AWS SDK (architecture
@@ -0,0 +1,94 @@
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
+ # `drift`: what CloudFormation holds against what each stack's resources
10
+ # should hold. The CDK's drift command, read at
11
+ # f7c9dca95f440a076c2abd61b66b984624b8548e:
12
+ #
13
+ # - CLI wiring: parse-command-line-arguments.ts:1036-1042 (`drift [STACKS..]`,
14
+ # `--fail`), cli.ts:397-402, cdk-toolkit.ts:654-661.
15
+ # - Action: toolkit-lib toolkit.ts:465-535, api/drift/drift.ts:16-112,
16
+ # api/drift/drift-formatter.ts:72-280.
17
+ #
18
+ # The stacks are chosen the way deploy and diff choose them (module
19
+ # Selection): the app's single stack when nothing is named, a usage error
20
+ # otherwise, --all for every stack in dependency order, and a named stack
21
+ # bringing its dependencies unless --exclusively.
22
+ #
23
+ # Output is text for a person on standard error -- where the CDK routes
24
+ # non-result messages -- and, with --json, one machine object per stack on
25
+ # standard output and nothing else there (architecture section 11).
26
+ #
27
+ # The exit code is the CDK's (cdk-toolkit.ts:659-660): 0 unless --fail is
28
+ # given and at least one resource drifted (MODIFIED or DELETED). Unchecked
29
+ # and UNKNOWN resources do not fail the command.
30
+ module Drift
31
+ # Routes engine progress lines to standard error only under --verbose,
32
+ # matching the CDK's trace level for drift progress (api/drift/drift.ts).
33
+ class Trace
34
+ def initialize(io)
35
+ @io = io
36
+ end
37
+
38
+ def announce(text)
39
+ @io.debug(text)
40
+ end
41
+ end
42
+
43
+ def self.run(session, names, poller: Deploy::Poller.drift)
44
+ manifest = session.manifest
45
+ session.say_synthesis_time
46
+ selected = Selection.choose(session.stacks, names:, all: session.options.all, command: "drift")
47
+ entries = Selection.ordered(manifest.entries, selected: selected.map(&:stack_name), direction: :up,
48
+ exclusively: session.options.exclusively)
49
+ announce_dependencies(session, selected, entries)
50
+ session.io.debug("drift: #{entries.map(&:name).join(", ")}")
51
+
52
+ trace = session.options.json ? nil : Trace.new(session.io)
53
+ results = entries.map { |entry| one(session, entry, poller: poller, output: trace) }
54
+
55
+ if session.options.json
56
+ results.each do |result|
57
+ session.io.result("#{JSON.generate(result.to_h)}\n")
58
+ end
59
+ else
60
+ results.each do |result|
61
+ text = Deploy::Drift.render(result, verbose: !!session.options.verbose, quiet: !!session.options.quiet)
62
+ session.io.say(text) unless text.empty?
63
+ end
64
+ session.io.say(Deploy::Drift.summary(results))
65
+ warning = Deploy::Drift.unavailable_warning(results)
66
+ session.io.say(warning) if warning
67
+ end
68
+
69
+ total_drifts = results.select(&:available?).sum(&:num_resources_with_drift)
70
+ total_drifts > 0 && session.options.fail ? 1 : Cli::SUCCESS
71
+ end
72
+
73
+ # One stack, from synthesis's template to its drift result.
74
+ def self.one(session, entry, poller:, output:)
75
+ stack = session.stack(entry.name)
76
+ region = session.region_of(stack)
77
+ clients = session.clients(region:)
78
+ session.io.debug("#{entry.name}: region #{region}#{session.region_source(stack)}")
79
+ Deploy::Drift.check(clients.cfn, entry.name, template: session.template_of(entry), poller: poller, output: output)
80
+ end
81
+
82
+ # The CDK brings a named stack's dependencies on deploy and diff and says
83
+ # so; drift follows the same stack selection.
84
+ def self.announce_dependencies(session, selected, entries)
85
+ return if session.options.all || session.options.exclusively || session.options.json || session.options.quiet
86
+
87
+ extra = entries.map(&:name) - selected.map(&:stack_name)
88
+ return if extra.empty?
89
+
90
+ session.io.say("Including dependency stacks: #{extra.join(", ")}")
91
+ end
92
+ end
93
+ end
94
+ end