belt 0.2.10 → 0.2.11
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +32 -0
- data/README.md +169 -0
- data/lib/belt/action_router.rb +32 -4
- data/lib/belt/cli/destroy_command.rb +119 -10
- data/lib/belt/cli/environment_command.rb +32 -0
- data/lib/belt/cli/plugin_command.rb +221 -0
- data/lib/belt/cli.rb +4 -0
- data/lib/belt/helpers/cors_origin.rb +19 -2
- data/lib/belt/helpers/response.rb +13 -2
- data/lib/belt/lambda_handler.rb +14 -5
- data/lib/belt/version.rb +1 -1
- data/lib/templates/environment/backend.tf.erb +1 -2
- data/lib/templates/plugin/AGENTS.md.erb +135 -0
- data/lib/templates/plugin/CHANGELOG.md.erb +5 -0
- data/lib/templates/plugin/Gemfile.erb +11 -0
- data/lib/templates/plugin/LICENSE.erb +21 -0
- data/lib/templates/plugin/README.md.erb +63 -0
- data/lib/templates/plugin/Rakefile.erb +7 -0
- data/lib/templates/plugin/gemspec.erb +26 -0
- data/lib/templates/plugin/gitignore.erb +11 -0
- data/lib/templates/plugin/lib/belt/generators/generator.rb.erb +122 -0
- data/lib/templates/plugin/lib/belt/module/configuration.rb.erb +15 -0
- data/lib/templates/plugin/lib/belt/module/version.rb.erb +7 -0
- data/lib/templates/plugin/lib/belt/module.rb.erb +27 -0
- data/lib/templates/plugin/lib/entry.rb.erb +3 -0
- data/lib/templates/plugin/rspec.erb +3 -0
- data/lib/templates/plugin/spec/configuration_spec.rb.erb +17 -0
- data/lib/templates/plugin/spec/spec_helper.rb.erb +19 -0
- metadata +18 -1
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 43ae84461595be08ca6caada3afd148ccfa0db94bfc2e2bd864a9b466d41f087
|
|
4
|
+
data.tar.gz: 1f33826b8c7a7b068458db8ca38aa9910079e16f04c3c5c727550f084ed85075
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 81532edca53a084bdd6aabf5e7027fd1653ec0fc4c592b0bdb60374283c7c59512a2217405d3a19f32a975bcbcbbebdf9f9a97d952a25b1567e05af8e2cb879d
|
|
7
|
+
data.tar.gz: d5ff609d6526f8cc59964df6da091a43150eca9d1c6f625dee27b070db0c56bd90ef58ef11c42f57e27259f169c477a4c1c548f9ca0f4c4f916c8bea540763bb
|
data/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,37 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## Unreleased
|
|
4
|
+
|
|
5
|
+
## 0.2.11
|
|
6
|
+
|
|
7
|
+
### Security hardening
|
|
8
|
+
|
|
9
|
+
- **CORS origin validation**: format validation (scheme required, no paths/queries/fragments), length limit (253 chars) to prevent ReDoS, restrict wildcard matching to valid subdomain chars `[a-z0-9-]`.
|
|
10
|
+
- **Security headers** on all responses: `X-Content-Type-Options: nosniff`, `Vary: Origin`; HTML responses also get `X-Frame-Options: DENY` and `Referrer-Policy: strict-origin-when-cross-origin`.
|
|
11
|
+
- **Path traversal protection** in `ActionRouter`: strict regex for controller names, reject `..` sequences / absolute paths / backslashes, `realpath` validation in `resolve_from_paths`.
|
|
12
|
+
- **Request body size limit** (10 MB): returns 413 for oversized bodies; proper 400 for invalid JSON.
|
|
13
|
+
|
|
14
|
+
### Safe `belt destroy environment`
|
|
15
|
+
|
|
16
|
+
Previously `belt destroy environment <name>` immediately deleted the infrastructure directory with no checks — leaving orphaned AWS resources.
|
|
17
|
+
|
|
18
|
+
Now the command:
|
|
19
|
+
1. Checks if Terraform state exists (local `.terraform` dir or remote state)
|
|
20
|
+
2. If state found, prompts user to run `terraform destroy` first
|
|
21
|
+
3. Requires explicit confirmation before deleting files
|
|
22
|
+
4. Supports `--force` (skip prompts) and `--skip-terraform` flags
|
|
23
|
+
|
|
24
|
+
### Environment generator state bucket fix
|
|
25
|
+
|
|
26
|
+
The environment generator was writing `belt-terraform-state` as the backend bucket name, missing the account-ID suffix. Now resolves via sibling `backend.tf`, STS `get-caller-identity`, or placeholder (for later `belt setup state` patch).
|
|
27
|
+
|
|
28
|
+
### Contributing & plugins
|
|
29
|
+
|
|
30
|
+
- README: **Plugins** and **Contributing** sections — how to contribute to belt, how plugins register via `GeneratorRegistry`, layout used by `belt-messaging` / `belt-pay`, generator checklist for humans and agents.
|
|
31
|
+
- **`belt plugin new <name>`** — scaffold a new plugin gem (gemspec, `Belt::<Name>` module, generator stub, RSpec, README, AGENTS.md), similar to `rails plugin new`.
|
|
32
|
+
- **`AGENTS.md`** at the belt gem root — agent-oriented map of core layout, CLI, and the plugin/GeneratorRegistry contract (complements README).
|
|
33
|
+
- Plugin scaffold includes **`AGENTS.md`** so new plugins match the agent guidance pattern already used by `belt new` apps.
|
|
34
|
+
|
|
3
35
|
## 0.2.10
|
|
4
36
|
|
|
5
37
|
### Quiet `belt new` (with optional verbose)
|
data/README.md
CHANGED
|
@@ -575,6 +575,175 @@ These are set via Terraform variables in each environment's `terraform.tfvars`.
|
|
|
575
575
|
|
|
576
576
|
The backup phase reads table names from Terraform outputs. On a brand-new environment that has never been deployed, there are no outputs yet — Belt will warn and skip the backup phase gracefully. After the first successful deploy, backups run normally on subsequent deploys.
|
|
577
577
|
|
|
578
|
+
## Plugins
|
|
579
|
+
|
|
580
|
+
Belt is designed to stay lean. Optional capabilities ship as **separate gems** that plug into the CLI and runtime the same way Rails engines and generators do.
|
|
581
|
+
|
|
582
|
+
### Official / example plugins
|
|
583
|
+
|
|
584
|
+
| Gem | Purpose | Status |
|
|
585
|
+
|-----|---------|--------|
|
|
586
|
+
| [`belt-messaging`](https://github.com/stowzilla/belt-messaging) | Two-way SMS via AWS End User Messaging (Pinpoint) | Early (not production-hardened) |
|
|
587
|
+
| [`belt-pay`](https://github.com/stowzilla/belt-pay) | Stripe payments & subscriptions | Early (not production-hardened) |
|
|
588
|
+
|
|
589
|
+
Install a plugin in a Belt app:
|
|
590
|
+
|
|
591
|
+
```ruby
|
|
592
|
+
# Gemfile
|
|
593
|
+
gem "belt-messaging"
|
|
594
|
+
# gem "belt-pay"
|
|
595
|
+
```
|
|
596
|
+
|
|
597
|
+
```bash
|
|
598
|
+
bundle install
|
|
599
|
+
belt generate messaging # or: belt g pay
|
|
600
|
+
belt generate --help # lists built-ins + gem generators
|
|
601
|
+
```
|
|
602
|
+
|
|
603
|
+
### How plugins register
|
|
604
|
+
|
|
605
|
+
No central registry file, no initializer hook. Belt discovers generators by scanning loaded gems:
|
|
606
|
+
|
|
607
|
+
1. Gem is in the app `Gemfile` and bundled
|
|
608
|
+
2. Gem ships a file at `lib/belt/generators/<name>_generator.rb`
|
|
609
|
+
3. Class lives in `Belt::Generators`, named `<Name>Generator`
|
|
610
|
+
4. Implements `.run(args)` (required), `.destroy(args)` and `.description` (optional)
|
|
611
|
+
|
|
612
|
+
That is the whole contract. After `bundle install`, `belt generate <name>` and `belt destroy <name>` just work.
|
|
613
|
+
|
|
614
|
+
See `Belt::CLI::GeneratorRegistry` and the CHANGELOG entry for **0.1.13 Generator Extension API**.
|
|
615
|
+
|
|
616
|
+
### Plugin layout (canonical)
|
|
617
|
+
|
|
618
|
+
```
|
|
619
|
+
belt-messaging/
|
|
620
|
+
├── belt-messaging.gemspec
|
|
621
|
+
├── lib/
|
|
622
|
+
│ ├── belt-messaging.rb # require entrypoint
|
|
623
|
+
│ └── belt/
|
|
624
|
+
│ ├── messaging.rb # Belt::Messaging API
|
|
625
|
+
│ ├── messaging/
|
|
626
|
+
│ │ ├── configuration.rb
|
|
627
|
+
│ │ ├── version.rb
|
|
628
|
+
│ │ ├── controllers/ # default controllers (optional)
|
|
629
|
+
│ │ └── templates/ # ERB templates for the generator
|
|
630
|
+
│ │ ├── terraform/
|
|
631
|
+
│ │ ├── lambda/
|
|
632
|
+
│ │ ├── config/
|
|
633
|
+
│ │ └── controllers/
|
|
634
|
+
│ └── generators/
|
|
635
|
+
│ └── messaging_generator.rb # ← auto-discovered
|
|
636
|
+
└── spec/
|
|
637
|
+
```
|
|
638
|
+
|
|
639
|
+
**Runtime code stays in the gem.** Generators copy only what the host app must own (Terraform modules, Lambda entrypoints, optional controller overrides). Prefer gem defaults + `belt g <plugin> --controllers` over dumping everything into the app (same idea as `rails g devise:views`).
|
|
640
|
+
|
|
641
|
+
### Creating a new plugin
|
|
642
|
+
|
|
643
|
+
Scaffold a ready-to-fill gem (Rails-style `plugin new`):
|
|
644
|
+
|
|
645
|
+
```bash
|
|
646
|
+
belt plugin new notifications
|
|
647
|
+
# → ./belt-notifications/
|
|
648
|
+
|
|
649
|
+
belt plugin new pay --path ~/Code --summary "Stripe payments for Belt"
|
|
650
|
+
# → ~/Code/belt-pay/
|
|
651
|
+
```
|
|
652
|
+
|
|
653
|
+
Then:
|
|
654
|
+
|
|
655
|
+
```bash
|
|
656
|
+
cd belt-notifications
|
|
657
|
+
bundle install
|
|
658
|
+
# implement lib/belt/notifications/* and the generator
|
|
659
|
+
```
|
|
660
|
+
|
|
661
|
+
Point a Belt app at it while developing:
|
|
662
|
+
|
|
663
|
+
```ruby
|
|
664
|
+
# In the app Gemfile
|
|
665
|
+
gem "belt-notifications", path: "../belt-notifications"
|
|
666
|
+
```
|
|
667
|
+
|
|
668
|
+
```bash
|
|
669
|
+
bundle install
|
|
670
|
+
belt generate notifications
|
|
671
|
+
```
|
|
672
|
+
|
|
673
|
+
When packaging Lambdas, `belt deploy` vendors path gems into `vendor/cache` so conveyor-belt can package them.
|
|
674
|
+
|
|
675
|
+
### Generator checklist (for humans and agents)
|
|
676
|
+
|
|
677
|
+
A solid plugin generator typically:
|
|
678
|
+
|
|
679
|
+
1. **Terraform module** → `infrastructure/modules/<name>/` (`main.tf`, `variables.tf`, `outputs.tf`)
|
|
680
|
+
2. **Lambda config** → `config/lambda/<name>.yml` (timeout, memory, env, triggers)
|
|
681
|
+
3. **Lambda entrypoint** → `lambda/<name>.rb` using `Belt::LambdaHandler`
|
|
682
|
+
4. **Routes / schema** → inject into `config/routes.tf.rb` or `infrastructure/schema.tf.rb` when needed
|
|
683
|
+
5. **Optional overrides** → `--controllers` flag for app-local subclasses
|
|
684
|
+
6. **Destroy path** → `belt destroy <name>` removes what generate created
|
|
685
|
+
7. **Help text** → `.description` + `--help` explaining what was installed and next steps
|
|
686
|
+
|
|
687
|
+
Copy from `belt-messaging` or `belt-pay` rather than inventing a new structure.
|
|
688
|
+
|
|
689
|
+
## Contributing
|
|
690
|
+
|
|
691
|
+
Bug reports and pull requests are welcome on [GitHub](https://github.com/stowzilla/belt).
|
|
692
|
+
|
|
693
|
+
### Development setup
|
|
694
|
+
|
|
695
|
+
```bash
|
|
696
|
+
git clone https://github.com/stowzilla/belt.git
|
|
697
|
+
cd belt
|
|
698
|
+
bundle install
|
|
699
|
+
bundle exec rspec
|
|
700
|
+
bundle exec rubocop
|
|
701
|
+
```
|
|
702
|
+
|
|
703
|
+
### Guidelines
|
|
704
|
+
|
|
705
|
+
1. **Branch from `master`** — open a PR against `master`
|
|
706
|
+
2. **Keep changes focused** — one concern per PR when practical
|
|
707
|
+
3. **Follow existing patterns** — look at neighboring files and `lib/belt/cli/` before inventing new ones
|
|
708
|
+
4. **Tests + lint** — run `bundle exec rspec` and `bundle exec rubocop` before opening (or updating) a PR. CI requires both (plus `bundler-audit`); failing checks block merge on `master`
|
|
709
|
+
5. **Changelog** — note user-facing changes in `CHANGELOG.md` under the next version / Unreleased
|
|
710
|
+
6. **No secrets** — never commit AWS keys, tokens, or real account IDs
|
|
711
|
+
|
|
712
|
+
### Project layout (for contributors)
|
|
713
|
+
|
|
714
|
+
| Path | What lives there |
|
|
715
|
+
|------|------------------|
|
|
716
|
+
| `lib/belt.rb` | Public require entry |
|
|
717
|
+
| `lib/belt/` | Framework core (controller, router, handler, observability) |
|
|
718
|
+
| `lib/belt/cli/` | CLI commands (`new`, `generate`, `deploy`, `plugin`, …) |
|
|
719
|
+
| `lib/belt_controller/` | `BeltController::Base` |
|
|
720
|
+
| `lib/templates/` | ERB templates for `belt new`, generators, plugin scaffold |
|
|
721
|
+
| `exe/belt` | CLI executable |
|
|
722
|
+
| `spec/` | RSpec suite |
|
|
723
|
+
| `AGENTS.md` | Agent-oriented map of this gem (layout, CLI, plugin contract) |
|
|
724
|
+
|
|
725
|
+
AI / coding agents: start with **[AGENTS.md](AGENTS.md)**. Belt apps and plugins scaffolded by the CLI get their own `AGENTS.md` as well (`belt new`, `belt plugin new`).
|
|
726
|
+
|
|
727
|
+
### Local gem development against an app
|
|
728
|
+
|
|
729
|
+
```ruby
|
|
730
|
+
# In a Belt app's Gemfile
|
|
731
|
+
gem "belt", path: "../belt"
|
|
732
|
+
```
|
|
733
|
+
|
|
734
|
+
`belt deploy` detects `path:` gems and materializes them into `vendor/cache` for Lambda packaging so you can iterate without publishing a gem for every try.
|
|
735
|
+
|
|
736
|
+
### Contributing a plugin
|
|
737
|
+
|
|
738
|
+
Plugins are separate repositories (not vendored into this repo). To add a new first-class capability:
|
|
739
|
+
|
|
740
|
+
1. `belt plugin new <name>` (or copy `belt-messaging` / `belt-pay`)
|
|
741
|
+
2. Implement the runtime API + generator contract above
|
|
742
|
+
3. Document install steps in the plugin README (`gem …` → `belt generate …`)
|
|
743
|
+
4. Open a PR on the plugin repo; optionally link it from this README's plugin table
|
|
744
|
+
|
|
745
|
+
Questions about plugin design or core changes: open a GitHub issue or discuss in the project Discord.
|
|
746
|
+
|
|
578
747
|
## License
|
|
579
748
|
|
|
580
749
|
MIT
|
data/lib/belt/action_router.rb
CHANGED
|
@@ -102,15 +102,35 @@ module Belt
|
|
|
102
102
|
end
|
|
103
103
|
|
|
104
104
|
def dispatch_to_controller(route_info, event, body)
|
|
105
|
-
|
|
105
|
+
controller_name = route_info[:controller]
|
|
106
|
+
|
|
107
|
+
# Prevent path traversal — controller names must be simple identifiers or single-level nested
|
|
108
|
+
unless valid_controller_name?(controller_name)
|
|
109
|
+
Belt::Observability::Logger.instance&.warn('Invalid controller name', controller: controller_name)
|
|
110
|
+
return error_response('Not found', 404, event)
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
controller_class = resolve_controller(controller_name)
|
|
106
114
|
controller = controller_class.new(event: event, body: body)
|
|
107
115
|
|
|
108
|
-
|
|
109
|
-
Belt::Observability::Logger.instance&.info("Processing by #{
|
|
116
|
+
class_label = controller_class.name.split('::').last.gsub('Controller', '')
|
|
117
|
+
Belt::Observability::Logger.instance&.info("Processing by #{class_label}##{route_info[:action]}")
|
|
110
118
|
|
|
111
119
|
controller.dispatch(route_info[:action].to_sym)
|
|
112
120
|
end
|
|
113
121
|
|
|
122
|
+
# Validate controller names to prevent path traversal.
|
|
123
|
+
# Allows: "posts", "admin/posts" (single nesting level, no dots or special chars)
|
|
124
|
+
def valid_controller_name?(name)
|
|
125
|
+
return false if name.nil? || name.empty?
|
|
126
|
+
return false if name.include?('..')
|
|
127
|
+
return false if name.start_with?('/') || name.end_with?('/')
|
|
128
|
+
return false if name.include?('\\')
|
|
129
|
+
|
|
130
|
+
# Allow only lowercase letters, digits, underscores, and a single forward slash for nesting
|
|
131
|
+
name.match?(%r{\A[a-z][a-z0-9_]*(/[a-z][a-z0-9_]*)?\z})
|
|
132
|
+
end
|
|
133
|
+
|
|
114
134
|
def resolve_controller(controller_name)
|
|
115
135
|
# Try namespace module first (app's own controllers)
|
|
116
136
|
begin
|
|
@@ -137,10 +157,18 @@ module Belt
|
|
|
137
157
|
def resolve_from_paths(controller_name)
|
|
138
158
|
if controller_name.include?('/')
|
|
139
159
|
end
|
|
140
|
-
file_name = "#{controller_name}_controller.rb"
|
|
160
|
+
file_name = "#{controller_name.gsub('/', '_')}_controller.rb"
|
|
141
161
|
|
|
142
162
|
Belt.all_controller_paths.each do |path|
|
|
143
163
|
full_path = File.join(path, file_name)
|
|
164
|
+
|
|
165
|
+
# Ensure resolved path stays within the allowed controller directory
|
|
166
|
+
begin
|
|
167
|
+
resolved = File.realpath(full_path)
|
|
168
|
+
rescue Errno::ENOENT, Errno::EACCES
|
|
169
|
+
next
|
|
170
|
+
end
|
|
171
|
+
next unless resolved.start_with?(File.realpath(path))
|
|
144
172
|
next unless File.exist?(full_path)
|
|
145
173
|
|
|
146
174
|
require full_path
|
|
@@ -44,10 +44,11 @@ module Belt
|
|
|
44
44
|
when 'environment'
|
|
45
45
|
name = args.shift
|
|
46
46
|
if name.nil? || name.empty?
|
|
47
|
-
puts 'Usage: belt destroy environment <name>'
|
|
47
|
+
puts 'Usage: belt destroy environment <name> [--force] [--skip-terraform]'
|
|
48
48
|
exit 1
|
|
49
49
|
end
|
|
50
|
-
|
|
50
|
+
flags = parse_environment_flags(args)
|
|
51
|
+
new(generator, name, [], **flags).destroy
|
|
51
52
|
when 'frontend'
|
|
52
53
|
new(generator, nil, []).destroy
|
|
53
54
|
when 'views'
|
|
@@ -67,6 +68,19 @@ module Belt
|
|
|
67
68
|
end
|
|
68
69
|
end
|
|
69
70
|
|
|
71
|
+
def self.parse_environment_flags(args)
|
|
72
|
+
flags = { force: false, skip_terraform: false }
|
|
73
|
+
args.each do |arg|
|
|
74
|
+
case arg
|
|
75
|
+
when '--force', '-f'
|
|
76
|
+
flags[:force] = true
|
|
77
|
+
when '--skip-terraform'
|
|
78
|
+
flags[:skip_terraform] = true
|
|
79
|
+
end
|
|
80
|
+
end
|
|
81
|
+
flags
|
|
82
|
+
end
|
|
83
|
+
|
|
70
84
|
def self.parse_field(arg)
|
|
71
85
|
name, type = arg.split(':', 2)
|
|
72
86
|
{ name: name, type: type || 'string' }
|
|
@@ -84,26 +98,37 @@ module Belt
|
|
|
84
98
|
resource Alias for scaffold
|
|
85
99
|
model Remove an ActiveItem model
|
|
86
100
|
controller Remove a controller
|
|
87
|
-
environment Remove a deployment environment
|
|
101
|
+
environment Remove a deployment environment and tear down infrastructure
|
|
88
102
|
frontend Remove the frontend/ directory
|
|
89
103
|
views Remove React pages for a resource
|
|
90
104
|
|
|
105
|
+
Environment options:
|
|
106
|
+
--force, -f Skip all prompts (CI mode)
|
|
107
|
+
--skip-terraform Delete local files without running terraform destroy
|
|
108
|
+
|
|
91
109
|
Examples:
|
|
92
110
|
belt d scaffold post title:string body:text status:string
|
|
93
111
|
belt d model user
|
|
94
112
|
belt d controller comments
|
|
95
113
|
belt d environment staging
|
|
114
|
+
belt d environment dev --skip-terraform
|
|
115
|
+
belt d environment dev --force
|
|
96
116
|
belt d frontend
|
|
97
117
|
belt d views post
|
|
98
118
|
|
|
99
119
|
⚠ This is destructive. Files will be permanently deleted.
|
|
120
|
+
|
|
121
|
+
For environments: if terraform state is detected, you'll be prompted to run
|
|
122
|
+
`terraform destroy` first to tear down cloud resources before removing files.
|
|
100
123
|
HELP
|
|
101
124
|
end
|
|
102
125
|
|
|
103
|
-
def initialize(generator, name, fields)
|
|
126
|
+
def initialize(generator, name, fields, force: false, skip_terraform: false)
|
|
104
127
|
@generator = generator
|
|
105
128
|
@name = name&.downcase&.gsub(/[^a-z0-9_]/, '_')
|
|
106
129
|
@fields = fields
|
|
130
|
+
@force = force
|
|
131
|
+
@skip_terraform = skip_terraform
|
|
107
132
|
@app_name = detect_namespace
|
|
108
133
|
@singular_name = @name ? Belt::Inflector.singularize(@name) : nil
|
|
109
134
|
@resource_name = @singular_name ? Belt::Inflector.pluralize(@singular_name) : nil
|
|
@@ -149,15 +174,99 @@ module Belt
|
|
|
149
174
|
|
|
150
175
|
def destroy_environment
|
|
151
176
|
dir = "infrastructure/#{@name}"
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
@removed << dir
|
|
155
|
-
puts " remove #{dir}/"
|
|
156
|
-
puts "\n✓ Environment '#{@name}' destroyed!"
|
|
157
|
-
else
|
|
177
|
+
|
|
178
|
+
unless Dir.exist?(dir)
|
|
158
179
|
puts "✗ Environment '#{@name}' not found at #{dir}/"
|
|
159
180
|
exit 1
|
|
160
181
|
end
|
|
182
|
+
|
|
183
|
+
# Check if terraform state exists (infra may still be live)
|
|
184
|
+
if !@skip_terraform && terraform_state_exists?(dir)
|
|
185
|
+
puts "⚠ Environment '#{@name}' appears to have active infrastructure."
|
|
186
|
+
puts " Terraform state was found — resources may still be running.\n\n"
|
|
187
|
+
|
|
188
|
+
if @force
|
|
189
|
+
puts ' --force passed, skipping terraform destroy.'
|
|
190
|
+
else
|
|
191
|
+
puts ' Options:'
|
|
192
|
+
puts ' 1) Run `terraform destroy` to tear down infrastructure first (recommended)'
|
|
193
|
+
puts ' 2) Skip terraform and just delete the local files (--skip-terraform)'
|
|
194
|
+
puts " 3) Cancel\n\n"
|
|
195
|
+
|
|
196
|
+
print " Run terraform destroy for '#{@name}'? [y/N/skip] "
|
|
197
|
+
response = $stdin.gets&.strip&.downcase
|
|
198
|
+
|
|
199
|
+
case response
|
|
200
|
+
when 'y', 'yes'
|
|
201
|
+
run_terraform_destroy(dir)
|
|
202
|
+
when 'skip', 's'
|
|
203
|
+
puts ' Skipping terraform destroy.'
|
|
204
|
+
else
|
|
205
|
+
puts 'Cancelled.'
|
|
206
|
+
exit 0
|
|
207
|
+
end
|
|
208
|
+
end
|
|
209
|
+
end
|
|
210
|
+
|
|
211
|
+
# Final confirmation before deleting files
|
|
212
|
+
unless @force
|
|
213
|
+
print "\nPermanently delete #{dir}/? [y/N] "
|
|
214
|
+
response = $stdin.gets&.strip&.downcase
|
|
215
|
+
unless response&.start_with?('y')
|
|
216
|
+
puts 'Cancelled.'
|
|
217
|
+
exit 0
|
|
218
|
+
end
|
|
219
|
+
end
|
|
220
|
+
|
|
221
|
+
FileUtils.rm_rf(dir)
|
|
222
|
+
@removed << dir
|
|
223
|
+
puts " remove #{dir}/"
|
|
224
|
+
puts "\n✓ Environment '#{@name}' destroyed!"
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
def terraform_state_exists?(dir)
|
|
228
|
+
# Check for local .terraform directory (initialized state)
|
|
229
|
+
return true if Dir.exist?(File.join(dir, '.terraform'))
|
|
230
|
+
|
|
231
|
+
# Check if backend.tf exists (remote state configured)
|
|
232
|
+
backend_file = File.join(dir, 'backend.tf')
|
|
233
|
+
return false unless File.exist?(backend_file)
|
|
234
|
+
|
|
235
|
+
# Try to query remote state — if terraform is initialized and state exists,
|
|
236
|
+
# the environment likely has live resources
|
|
237
|
+
Dir.chdir(dir) do
|
|
238
|
+
# Quick check: does `terraform show` return anything?
|
|
239
|
+
output = `terraform show -no-color 2>&1`
|
|
240
|
+
Process.last_status.success? && !output.strip.empty? && !output.include?('No state')
|
|
241
|
+
end
|
|
242
|
+
rescue StandardError
|
|
243
|
+
# If we can't determine state, assume it might exist and warn
|
|
244
|
+
true
|
|
245
|
+
end
|
|
246
|
+
|
|
247
|
+
def run_terraform_destroy(dir)
|
|
248
|
+
puts "\n━━━ terraform destroy (#{@name}) ━━━"
|
|
249
|
+
|
|
250
|
+
Dir.chdir(dir) do
|
|
251
|
+
# Initialize if needed
|
|
252
|
+
unless Dir.exist?('.terraform')
|
|
253
|
+
puts ' Initializing terraform...'
|
|
254
|
+
unless system('terraform', 'init', '-input=false')
|
|
255
|
+
puts "\n✗ terraform init failed. You may need to destroy manually:"
|
|
256
|
+
puts " cd #{dir} && terraform init && terraform destroy"
|
|
257
|
+
exit 1
|
|
258
|
+
end
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
# Run destroy with auto-approve (user already confirmed)
|
|
262
|
+
unless system('terraform', 'destroy', '-auto-approve')
|
|
263
|
+
puts "\n✗ terraform destroy failed."
|
|
264
|
+
puts ' Infrastructure may still be running. Fix and retry, or use --skip-terraform.'
|
|
265
|
+
exit 1
|
|
266
|
+
end
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
puts ' ✓ Infrastructure destroyed.'
|
|
161
270
|
end
|
|
162
271
|
|
|
163
272
|
def destroy_frontend
|
|
@@ -32,6 +32,7 @@ module Belt
|
|
|
32
32
|
@domain = domain
|
|
33
33
|
@quiet = quiet
|
|
34
34
|
@announce = announce
|
|
35
|
+
@state_bucket = resolve_state_bucket
|
|
35
36
|
end
|
|
36
37
|
|
|
37
38
|
def generate
|
|
@@ -80,6 +81,37 @@ module Belt
|
|
|
80
81
|
content = ERB.new(File.read(template_path), trim_mode: '-').result(binding)
|
|
81
82
|
File.write(dest_path, content)
|
|
82
83
|
end
|
|
84
|
+
|
|
85
|
+
# Resolve the state bucket name to use in backend.tf.
|
|
86
|
+
# Priority: existing sibling backend.tf → AWS account ID → bare placeholder.
|
|
87
|
+
def resolve_state_bucket
|
|
88
|
+
bucket_from_sibling || bucket_from_aws || 'belt-terraform-state'
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def bucket_from_sibling
|
|
92
|
+
Dir.glob('infrastructure/*/backend.tf').each do |f|
|
|
93
|
+
match = File.read(f).match(/bucket\s*=\s*"([^"]+)"/)
|
|
94
|
+
next unless match
|
|
95
|
+
# Skip the bare placeholder — it means state wasn't set up yet
|
|
96
|
+
return match[1] unless match[1] == 'belt-terraform-state'
|
|
97
|
+
end
|
|
98
|
+
nil
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def bucket_from_aws
|
|
102
|
+
require 'open3'
|
|
103
|
+
output, status = Open3.capture2e('aws', 'sts', 'get-caller-identity')
|
|
104
|
+
return nil unless status.success?
|
|
105
|
+
|
|
106
|
+
data = begin
|
|
107
|
+
JSON.parse(output)
|
|
108
|
+
rescue StandardError
|
|
109
|
+
nil
|
|
110
|
+
end
|
|
111
|
+
return nil unless data&.dig('Account')
|
|
112
|
+
|
|
113
|
+
"belt-terraform-state-#{data['Account']}"
|
|
114
|
+
end
|
|
83
115
|
end
|
|
84
116
|
end
|
|
85
117
|
end
|