Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: CI

on:
push:
branches: [main, master]
pull_request:

permissions:
contents: read

jobs:
test:
name: Ruby ${{ matrix.ruby }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
ruby: ['3.2', '3.3', '3.4']
steps:
- uses: actions/checkout@v4
- uses: ruby/setup-ruby@v1
with:
ruby-version: ${{ matrix.ruby }}
bundler-cache: true
- run: bundle exec rspec
- run: bundle exec rubocop
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ log
convox.yml
.convox
convox_installer-*.gem
Gemfile.lock
.installer_config.json
.rspec_status
24 changes: 20 additions & 4 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -1,15 +1,20 @@
require: rubocop-rspec
plugins:
- rubocop-rspec

AllCops:
NewCops: enable
TargetRubyVersion: 2.5
TargetRubyVersion: 3.2
SuggestExtensions: false
Exclude:
- vendor/**/*
- tmp/**/*

Style/MixinUsage:
Exclude:
- examples/**/*

Layout/LineLength:
Max: 100
Max: 120

Style/StringLiterals:
EnforcedStyle: single_quotes
Expand Down Expand Up @@ -47,6 +52,9 @@ Metrics/BlockLength:
Metrics/BlockNesting:
Max: 7

Naming/PredicateMethod:
Enabled: false

RSpec/MessageSpies:
Enabled: false

Expand All @@ -59,5 +67,13 @@ RSpec/MultipleExpectations:
RSpec/ExampleLength:
Enabled: false

RSpec/AnyInstance:
RSpec/MultipleMemoizedHelpers:
Enabled: false

RSpec/NestedGroups:
Max: 4

# The fake convox, aws and terraform commands print their output.
RSpec/Output:
Exclude:
- spec/fixtures/**/*
101 changes: 101 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,101 @@
# AGENTS.md

Notes for coding agents. The first part covers running an install script built with this gem; the second covers changing the gem. People should start with [README.md](./README.md).

## Running an install script

An install script (`install.rb`) uses this gem's DSL. It creates real AWS resources that cost money, so:

- Run `plan` first and show the person what it reports. Run `install` only when they've asked for it.
- Never pass AWS keys on the command line. Use the person's AWS profile or SSO session (`AWS_PROFILE=...`). If credentials are missing or expired, the run exits 3 and says which command to run (for example `aws sso login --profile prod`); ask the person to run it.
- `.installer_config.json` holds generated passwords and tokens. Don't print it, paste it or commit it.

### Commands and flags

```sh
ruby install.rb plan --yes --json # what would change; changes nothing
ruby install.rb status --yes --json # the same checks, to see what exists
ruby install.rb install --yes --json # set everything up (also: apply, or no command)
ruby install.rb --help # every flag and setting
```

- `--yes` (or `--non-interactive`, or `CONVOX_INSTALLER_NON_INTERACTIVE=1`): never prompt. Always pass it: without a terminal and without `--yes`, the run stops before changing anything (exit 2, `missing: ["confirmation"]`).
- `--json` (or `CONVOX_INSTALLER_JSON=1`): JSON events on stdout, one per line. Human logs, and all output from `convox`, `terraform` and the script itself, go to stderr.
- Settings: `--stack-name prod`, `--set key=value`, `CONVOX_INSTALLER_<KEY>=value`, the config file (`--config FILE`, default `./.installer_config.json`). Flags win over environment variables, which win over the file. Prompt keys also read bare names (`STACK_NAME`). Pass secrets as environment variables rather than flags, so they stay out of the process list.

### Exit codes

| Code | Type | What to do |
| --- | --- | --- |
| 0 | | Done. For `plan` and `status`, read `changes_pending` and `pending`. |
| 1 | `unexpected_error` | A bug in the gem or the script. Report it with the stderr output. |
| 2 | `missing_input`, `usage` | Supply the settings in `error.missing` or fix `error.invalid`, then run the same command again. |
| 3 | `precondition_failed` | Fix the environment (install a tool, sign in to AWS, use the right account), then run again. |
| 4 | `step_failed` | A command failed in `error.step`. Read stderr, fix the cause, run the same command again. |
| 5 | `cancelled` | The input ended at a prompt. Use `--yes`. |
| 130 | `interrupted` | Interrupted. Run the same command again to resume. |

### JSON events

Every event has `event` and `time` (UTC, ISO 8601). Secrets are replaced with `[hidden]` in every event and log line.

- `start`: `version` (gem), `command` (`install`, `plan` or `status`), `dry_run` (true for `plan` and `status`).
- `config`: `file`, `settings` (visible settings, secrets hidden) and `sources` (where each came from: `flag`, `env:<NAME>`, `file`, `default`, `generated`, `prompt`).
- `step`: `step` (a stable name), `status`, and `description`. Statuses:
- `started`: the step began (install only).
- `done`: it made its change, or a check passed.
- `skipped`: nothing to do; `state` is `present` and `reason` says why.
- `pending`: in `plan` and `status`, the step would make a change. `action` (`create`, `update`, `resume`, `apply`, `run`, `check`), `state` (`missing`, `outdated`, `incomplete`, `unknown`) and an optional `reason`.
- `failed`: `error` with `type`, `message`, `next_step`.
- Some steps add fields: `rack_dir`, `command`, `files` (Terraform files that would change), `resources` (each address `present` or `missing`), `keys` (environment variable names that changed), `version`, `file`.
- `would_run`: in `plan` and `status`, a `convox` command the script would run (`command`, secrets masked).
- `result`: always the last event. `command`, `status` (`succeeded`, `failed`, `cancelled`), `exit_code`, `steps` (each `step`, `status`, `action`, `state`), `outputs` (values the script added with `result_output`), `config_file`, and on failure `error` (`type`, `message`, `step`, `next_step`, plus `missing` and `invalid` for input errors). `plan` and `status` add `pending` (step names), `changes_pending`, and `stopped_early` (`reason`) when a later step needs a resource that doesn't exist yet.

### Resuming

Every step checks the current state first, so after a failure, fix the cause and run the same command again: finished steps report `skipped`. An interrupted `convox rack install` is resumed with `terraform apply` in the rack directory. Generated names and passwords are saved to the config file as soon as they're made, so a re-run reuses them. If the config file is lost, a re-run generates new ones and tries to create new resources, so keep it.

### Steps

`requirements`, `config`, `convox_rack`, `convox_current_rack`, `convox_rack_api`, `convox_app`, `convox_app_directory`, `docker_registry`, `terraform_s3_bucket`, `terraform_rds_database`, `terraform_elasticache`, `terraform_apply`, `convox_env`, then any custom steps the script defines. The `terraform_*` steps that write files are skipped when the file on disk already matches; `terraform_apply` is skipped when `terraform plan` finds no changes. `requirements`, `config` and `convox_rack_api` are checks and report `done` on every run.

## Changing the gem

```sh
bundle install
bundle exec rspec # must pass; no network
bundle exec rubocop # must be clean
```

CI (`.github/workflows/ci.yml`) runs both on Ruby 3.2, 3.3 and 3.4. Gemfile.lock isn't committed (it's a gem, and the newest RuboCop dependencies need a newer Ruby than 3.2).

### Layout

- `lib/convox_installer.rb`: the DSL that scripts `include`. It parses the command line on first use, sets up the context and prints the result at exit (`at_exit` calls `Runner#finish`, then exits with its code).
- `lib/convox_installer/`:
- `options.rb` (command line), `settings.rb` (the gem's own settings: drives `--help`, flags and env names), `config.rb` (loading, prompting, validating and saving settings).
- `runner.rb` (named steps and the result), `reporter.rb` (JSON events and the logger), `errors.rb` (error classes and exit codes).
- `shell.rb` (every subprocess goes through `Shell`), `masker.rb` (hides secrets in logs and events), `aws_session.rb` (credential chain, `sts get-caller-identity`, exported credentials), `requirements.rb` (tool checks), `platform.rb` (OS, Convox config directory, install hints), `context.rb` (holds them together).
- `lib/convox/client.rb`: the steps that touch Convox, Terraform and AWS.
- `terraform/*.tf.erb`: templates written into the rack directory. `s(:key)` renders an escaped HCL string, `v(:key)` a raw value.
- `spec/`: unit specs use `FakeExecutor` (`spec/support/fake_executor.rb`) to answer commands. `spec/lib/convox_installer_spec.rb` runs `examples/full_installation.rb` as a real process with fake `convox`, `aws` and `terraform` executables (`spec/fixtures/fake_tools.rb`).

### Rules

- **No real commands or network in specs.** `spec_helper.rb` installs `RefusingExecutor`, which raises on any command not stubbed, and WebMock blocks HTTP. Never run `convox rack install`, `terraform apply` or any AWS command while developing.
- **Every subprocess goes through `context.shell`** (`capture` or `stream`), with an argv array. Pass secrets on stdin or in the environment, never as arguments; when that can't be avoided, register them with `context.masker.add`.
- **Steps check before they change.** Inside `runner.step`, look at the current state, call `step.skip!(reason)` when there's nothing to do, and call `step.plan!(action:)` immediately before the first change. In `plan` and `status`, `plan!` ends the step as pending; code after it must be the only code that changes anything. Step names are part of the interface: don't rename them.
- **Errors say what to do next.** Raise `MissingInput`, `PreconditionFailed` or `StepFailed` with a `next_step:`. Anything else becomes exit code 1.
- **Templates must stay compatible with existing installs.** Resource addresses (`aws_db_instance.rds_database`, `aws_s3_bucket.docs_s3_bucket`, `aws_iam_access_key.docspring_user_access_key` and the rest) and names are in real Terraform state; changing one makes Terraform destroy and recreate the resource. Defaults for an existing resource come from its state (`resource_attributes`), and new defaults apply only to new resources. Don't add a `required_providers` block: Convox pins the AWS provider (5.100.0 in Convox 3.26.0), and `convox rack update` and `uninstall` run `terraform init -upgrade`.
- **New settings** go in `Settings::KNOWN` with a title and description, and in the README's settings table. Bare environment names are read only for a script's prompt keys.

### Convox facts the code relies on

Checked against the Convox source at tag 3.26.0 (`pkg/cli/rack.go`, `pkg/rack/terraform.go`, `vendor/github.com/convox/stdcli`):

- `convox rack install aws <name> [key=value ...]` takes `--version` and writes the rack's Terraform config to `<config dir>/racks/<name>/` (`main.tf`, `vars.json`, local `terraform.tfstate` unless `CONVOX_TERRAFORM_BACKEND` is set). It fails with "rack name in use" if that directory exists.
- The config directory is `$CONVOX_CONFIG`, otherwise `~/Library/Preferences/convox` on macOS and `$XDG_CONFIG_HOME/convox` (`~/.config/convox`) on Linux. `convox switch <rack>` writes `current` there.
- For AWS, the CLI requires `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` in the environment and runs a binary named `terraform` (no OpenTofu option; the gem puts a `terraform` symlink to `tofu` first on `PATH`).
- The rack's Terraform outputs include `api` (the rack API URL with credentials, sensitive); `module.system.cluster` has `vpc` and `subnets`.
- Rack names match `^[a-z][a-z0-9-]*$`, at most 26 characters.
- Most commands have no JSON output; `convox api get <path>` returns the API's JSON. `convox env` prints `KEY=value` lines, and `convox env set` reads `KEY=value` lines from stdin when stdin isn't a terminal.
52 changes: 52 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
# Changelog

## 4.0.0

4.0.0 brings the gem up to date with the current Convox v3 CLI, Terraform or OpenTofu, the AWS provider and Ruby. It also adds a non-interactive mode for CI and coding agents. Scripts written for 3.x keep working with a few changes (see "Upgrading a 3.x script" below).

### Breaking changes

- **Ruby 3.2 or later.** The gem no longer depends on ActiveSupport, HTTParty, `os` or `json`. If your script used ActiveSupport methods (`present?`, `symbolize_keys`, `1.day`) because the gem loaded it, require ActiveSupport yourself or replace those calls.
- **AWS credentials come from the standard AWS credential chain** (`AWS_PROFILE`, SSO, environment variables, instance roles). The installer no longer prompts for an access key, and `Config::DEFAULT_PROMPTS` no longer has `aws_access_key_id` or `aws_secret_access_key`. `config.fetch(:aws_access_key_id)` raises `KeyError` on a new install. Use `aws_env` (an environment hash for your own `aws` commands) and `aws_identity` (account and principal) instead. Explicit keys in `AWS_ACCESS_KEY_ID` and `AWS_SECRET_ACCESS_KEY` still work. Keys saved in a 3.x config file are kept and used.
- **The installer checks the AWS account.** It shows the account and principal from `aws sts get-caller-identity` in the summary, saves the account ID to the config file, and stops if a later run uses credentials for a different account.
- **Convox v2 support is gone.** The gem needs the Convox v3 CLI. The last version for Convox v2 is 1.0.9.
- **Terraform 1.6 or later, or OpenTofu.** Set `terraform_binary` to `tofu` to use OpenTofu; the installer uses `tofu` on its own when `terraform` isn't installed. The AWS CLI must be v2.9 or later.
- **New Terraform resources:**
- The S3 bucket uses the separate resources the AWS provider now expects: versioning, KMS encryption (now with a bucket key), a public access block, ownership controls (new buckets) and CORS. The deprecated inline `acl`, `cors_rule` and encryption blocks are gone. Versioning is on for new buckets, with old versions expiring after 30 days. Existing buckets keep their versioning setting.
- New RDS databases use Postgres 17, gp3 storage, encryption, 7 days of backups and deletion protection. Existing databases keep their engine version (read from AWS, so Terraform doesn't plan a downgrade), storage type and encryption. Changing `database_storage_encrypted` on an existing database is refused, since it would replace the database.
- New installs get an ElastiCache replication group with TLS, encryption at rest and an AUTH token, so `elasticache_details[:redis_url]` starts with `rediss://`. Your app's Redis client must support TLS. Installs that already have the 3.x `aws_elasticache_cluster` keep it unchanged (or set `elasticache_legacy_cluster`).
- `convox_installer.tf` now holds the `provider "aws"` block and a data source for the rack's VPC. The installer stops with instructions if an older file in the rack directory still configures the provider.
- **`apply_terraform_update!` runs `terraform plan` and applies that saved plan**, instead of `terraform apply -auto-approve`. It skips the apply when the plan has no changes. The installer reads the rack's state with `terraform state pull` instead of the local `terraform.tfstate` file, so remote backends work.
- **Environment variables:** every setting reads `CONVOX_INSTALLER_<KEY>` first. Bare names (`STACK_NAME`) still work for the keys in your script's prompts, as in 3.x. The gem's own optional settings (`database_instance_class` and the rest) read only the prefixed name, so a `DATABASE_PASSWORD` in your shell for another project isn't picked up.
- **Output and exit codes:** each step prints `==> <step>: <description>`, and the script ends with a summary and an exit code that says how it went (see the README). Errors from the gem no longer print a Ruby backtrace. `run_convox_command!` prints the command with secrets masked.
- `backup_convox_host_and_rack` does nothing when the rack is already installed, so a re-run keeps your current rack.
- The config file (`.installer_config.json`) is written with mode 0600 and records the gem version. AWS credentials passed in the environment or on the command line are not saved to it.

### New

- **Commands:** `install` (the default, also called `apply`), `plan` (shows which steps would change something, and changes nothing) and `status` (the same checks, to see what exists).
- **Non-interactive mode:** `--yes` (or `--non-interactive`, or `CONVOX_INSTALLER_NON_INTERACTIVE=1`) never prompts. A run with missing settings exits with code 2 and lists them. A run without a terminal and without `--yes` stops before it changes anything and asks for `--yes`.
- **Settings from anywhere:** flags (`--stack-name prod`, `--set key=value`), environment variables, a config file (`--config FILE`), then defaults.
- **`--json`:** one JSON event per line on stdout (`start`, `config`, `step`, `would_run`, `result`), with human logs on stderr. Secrets are masked in every event and log line.
- **Named, resumable steps.** Each step checks the current state first and is skipped when it's done, so a failed run can be repeated. Custom steps in your script: `step 'name', 'description', check: -> { ... } do ... end`.
- `set_convox_env!(values, promote: false)` sets only the app environment variables that changed, sending values on stdin rather than the command line. `convox_env_vars`, `convox_processes` and `convox_api_get(path)` read the app's state.
- `capture_convox_command!(cmd)` runs a `convox` command and returns its output, such as the release ID from `convox build --id`.
- `result_output(key, value)` adds a value to the final result.
- Resuming an interrupted `convox rack install`: if the rack directory exists without an API endpoint, the installer runs `terraform apply` in it.
- Linux support, with install hints for macOS and Linux.
- Rack options: `convox_rack_version`, `convox_rack_params`, `convox_proxy_protocol`, `availability_zones`.

### Upgrading a 3.x script

1. Change the gem version to `'~> 4.0'` and run with Ruby 3.2 or later.
2. Remove anything that reads `config.fetch(:aws_access_key_id)` or `:aws_secret_access_key`. For your own `aws` commands, pass `aws_env` as the environment: `system(aws_env, 'aws', 's3', 'rm', ...)`.
3. Replace backtick calls such as `` `convox env --rack ...` `` and `` `convox ps --rack ...` `` with `convox_env_vars` and `convox_processes`. They use the same credentials as the installer and raise a clear error when they fail.
4. Replace `run_convox_command! "env set #{...}"` with `set_convox_env!(desired_env)`. It compares with the current values, sets only what changed and keeps the values off the command line.
5. Wrap your own changes in `step` blocks with a `check:`, so re-runs and `plan` report them properly.
6. If your app connects to Redis, make sure it accepts `rediss://` URLs for new installs.

Existing installs keep their resources: the installer reads the Terraform state and keeps the current database version, storage, bucket versioning and the 3.x Redis cluster. Run `ruby install.rb plan` first to see what would change.

## 3.2.1 and earlier

See the [git history](https://github.com/DocSpring/convox_installer/commits/master).
15 changes: 6 additions & 9 deletions Gemfile
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,10 @@ source 'https://rubygems.org'

gemspec

group :test do
gem 'pry', require: false
gem 'pry-byebug', require: false
gem 'rspec'
gem 'rubocop'
gem 'rubocop-daemon'
gem 'rubocop-rspec'
gem 'vcr'
gem 'webmock'
group :development, :test do
gem 'rake'
gem 'rspec', '~> 3.13'
gem 'rubocop', '~> 1.75'
gem 'rubocop-rspec', '~> 3.6'
gem 'webmock', '~> 3.25'
end
Loading
Loading