torrust-tracker-deployer 0.1.0

Torrust Tracker Deployer - Deployment Infrastructure with Ansible and OpenTofu
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
# Console Commands - Torrust Tracker Deployer

> **Note**: This document describes the console commands for the Torrust Tracker Deployer tool.

## Current Implementation Status

### ✅ What's Currently Implemented (Available via CLI)

- **Create Template**: Generate environment configuration template (JSON)
- **Create Environment**: Create new deployment environment from configuration file
- **Show**: Display environment information with state-aware details
- **Exists**: Check whether an environment exists (boolean output)
- **Render**: Generate deployment artifacts without provisioning infrastructure
- **Provision**: VM infrastructure provisioning with OpenTofu (LXD and Hetzner Cloud)
- **Register**: Register existing instances as an alternative to provisioning (for pre-existing VMs, servers, or containers)
- **Configure**: VM configuration with Docker, Docker Compose, and firewall via Ansible
- **Test**: Verification of deployment infrastructure (cloud-init, Docker, Docker Compose)
- **Release**: Deploy application configuration and files (tracker config, docker-compose stack)
- **Run**: Start Torrust Tracker services and validate accessibility
- **Destroy**: Infrastructure cleanup and environment destruction
- Template rendering system (OpenTofu, Ansible, Tracker, Docker Compose templates)
- SSH connectivity validation
- Environment state management and persistence

### ⚠️ What's NOT Yet Implemented

- Porcelain commands (high-level `deploy` command)
- Additional cloud providers (AWS, Azure, GCP)

## Deployment States

The deployment follows a linear state progression:

1. **created** → Environment configuration exists
2. **provisioned** → VM/container infrastructure is running
3. **configured** → Basic system setup complete (Docker, networking, etc.)
4. **released** → Application files and configuration deployed
5. **running** → Torrust Tracker application is active
6. **destroyed** → Infrastructure cleaned up

Each command transitions the deployment to the next state.

## Complete Deployment Workflow

The full deployment workflow with all implemented commands:

```bash
# 1. Generate configuration template
torrust-tracker-deployer create template --provider lxd > my-env.json

# 2. Edit my-env.json with your settings (SSH keys, tracker config, etc.)

# 3. Create environment from configuration
torrust-tracker-deployer create environment --env-file my-env.json

# 4a. Provision NEW VM infrastructure
torrust-tracker-deployer provision my-environment

# 4b. OR Register EXISTING infrastructure (alternative to provision)
torrust-tracker-deployer register my-environment --instance-ip 192.168.1.100

# 5. Configure system (Docker, Docker Compose, firewall)
torrust-tracker-deployer configure my-environment

# 6. Verify deployment infrastructure
torrust-tracker-deployer test my-environment

# 7. Deploy application configuration and files
torrust-tracker-deployer release my-environment

# 8. Start Torrust Tracker services
torrust-tracker-deployer run my-environment

# 9. Destroy environment when done
torrust-tracker-deployer destroy my-environment
```

This workflow deploys a complete Torrust Tracker instance with all configuration and services running.

## Hybrid Command Architecture

The deployer implements a **hybrid approach** offering two levels of command interface:

### Plumbing Commands (Low-Level, Implemented First)

Individual commands for precise control over each deployment step:

- `create` → `provision` → `configure` → `release` → `run`
- Each command performs one specific operation
- Ideal for CI/CD, automation, debugging, and advanced users
- **Implementation Priority**: High (these are implemented first)

### Porcelain Commands (High-Level, Implemented Later)

Simplified commands that orchestrate multiple plumbing commands:

- `deploy` - Intelligent deployment from current state to running
- Automatically determines next steps based on environment state
- If environment is already provisioned, starts from configure
- If environment is already configured, starts from release
- **Implementation Priority**: Medium (after plumbing commands are stable)

### Example Usage Patterns

```bash
# Porcelain: Simple deployment (future)
torrust-tracker-deployer create myenv
torrust-tracker-deployer deploy myenv    # Runs provision→configure→release→run

# Plumbing: Step-by-step control (current focus)
torrust-tracker-deployer create myenv
torrust-tracker-deployer provision myenv
torrust-tracker-deployer configure myenv
torrust-tracker-deployer release myenv
torrust-tracker-deployer run myenv
```

**Note**: Porcelain commands only automate the core deployment workflow (`provision` → `configure` → `release` → `run`). Management commands like `create`, `list`, `check`, `status`, `destroy` remain individual operations.

## Quick Command Reference

```bash
# Utility Commands (Planned)
torrust-tracker-deployer check           # Validate required tools (not yet implemented)
torrust-tracker-deployer list            # List all environments (not yet implemented)

# Environment Management
torrust-tracker-deployer create template [PATH]         # ✅ Generate configuration template
torrust-tracker-deployer create environment -f <file>   # ✅ Create environment from config
torrust-tracker-deployer show <env>      # ✅ Display environment information
torrust-tracker-deployer exists <env>   # ✅ Check if environment exists

# Plumbing Commands (Low-Level)
torrust-tracker-deployer render --env-name <env> --instance-ip <IP> --output-dir <PATH> # ✅ Generate deployment artifacts
torrust-tracker-deployer provision <env> # ✅ Create VM infrastructure
torrust-tracker-deployer register <env> --instance-ip <IP>  # ✅ Register existing infrastructure
torrust-tracker-deployer configure <env> # ✅ Setup VM (Docker, Docker Compose, firewall)
torrust-tracker-deployer release <env>   # ✅ Deploy application files and configuration
torrust-tracker-deployer run <env>       # ✅ Start Torrust Tracker services

# Validation
torrust-tracker-deployer test <env>      # ✅ Verify infrastructure (cloud-init, Docker, Docker Compose)

# Cleanup
torrust-tracker-deployer destroy <env>   # ✅ Destroy infrastructure and clean up
```

## Detailed Command Specifications

### `check` - Tool Validation

**Status**: ❌ Not Implemented  
**State Transition**: None  
**Purpose**: Verify all required third-party tools are installed and properly configured.

```bash
torrust-tracker-deployer check [OPTIONS]
```

**Validates**:

- OpenTofu installation and version
- Ansible installation and version
- LXD setup and permissions
- SSH key availability
- Network connectivity to container registries

**Options**:

- `--fix` - Attempt to auto-install missing tools

**Environment Variables**:

- `RUST_LOG=debug` - Show detailed validation steps via tracing

**Example Output**:

```text
✅ OpenTofu v1.6.0 - OK
✅ Ansible v2.15.0 - OK
✅ LXD v5.0 - OK
❌ SSH key not found at ~/.ssh/id_rsa
⚠️  Docker registry connectivity - Slow response
```

---

### `list` - Environment Listing

**Status**: ❌ Not Implemented  
**State Transition**: None (read-only)  
**Purpose**: Display a summary of all available deployment environments.

```bash
torrust-tracker-deployer list [OPTIONS]
```

**Should Display**:

- Environment name
- Current deployment state (created, provisioned, configured, etc.)
- Creation timestamp
- Last modified timestamp
- Infrastructure status (if provisioned)
- Brief resource summary (IP address, instance type)

**Options**:

- `--format <table|json|yaml>` - Output format
- `--state <state>` - Filter by deployment state
- `--sort <name|created|modified|state>` - Sort criteria

**Environment Variables**:

- `RUST_LOG=debug` - Show detailed listing information via tracing

**Example Output**:

```text
NAME          STATE        CREATED      MODIFIED     IP ADDRESS
e2e-test      provisioned  2 hours ago  30 min ago   10.140.190.14
production    running      5 days ago   1 hour ago   10.140.192.45
staging       configured   1 day ago    6 hours ago  10.140.191.23
development   destroyed    3 days ago   2 days ago   -
```

---

### `show` - Environment Information

**Status**: ✅ Implemented  
**State Transition**: None (read-only)  
**Purpose**: Display detailed information about a specific environment's current state.

```bash
torrust-tracker-deployer show <environment>
```

**Displays State-Aware Information**:

- Environment name and current state
- Provider type (LXD, Hetzner, etc.)
- Infrastructure details (IP, SSH port, SSH user, SSH key path) for Provisioned+ states
- Ready-to-use SSH connection command
- Tracker service URLs for Released/Running states
- Next-step guidance based on current state

**Key Features**:

- **Fast execution** - Reads only from local storage, no network connections
- **State-aware output** - Shows different information based on environment state
- **Actionable guidance** - Tells users what to do next

**Example Output (Running State)**:

```text
Environment: my-environment
State: Running
Provider: LXD

Infrastructure:
  Instance IP: 10.140.190.171
  SSH Port: 22
  SSH User: torrust
  SSH Key: ~/.ssh/torrust_deployer_key

Connection:
  ssh -i ~/.ssh/torrust_deployer_key torrust@10.140.190.171

Tracker Services:
  UDP Trackers:
    - udp://10.140.190.171:6969/announce
  HTTP Trackers:
    - http://10.140.190.171:7070/announce
  API Endpoint:
    - http://10.140.190.171:1212/api
  Health Check:
    - http://10.140.190.171:1313/health_check

Tracker is running! Use the URLs above to connect.
```

**Example Output (Created State)**:

```text
Environment: my-environment
State: Created
Provider: LXD

Next: Run 'provision my-environment' to create infrastructure
```

---

### `exists` - Check Environment Existence

**Status**: ✅ Implemented
**State Transition**: None (read-only)
**Purpose**: Check whether an environment with the given name exists in the local data directory.

```bash
torrust-tracker-deployer exists <environment>
```

**Output**:

- `true` — Environment exists
- `false` — Environment does not exist

Output is the same for both text and JSON formats (bare boolean is valid JSON).

**Exit Code Contract**:

- **Exit 0**: Command completed successfully (check stdout for `true`/`false`)
- **Exit 1**: An error occurred (repository failure, invalid name)

"Environment not found" is NOT an error — it produces `false` with exit 0.

**Key Features**:

- **Sub-millisecond** — Checks local file existence only, no network calls
- **Scriptable** — Bare boolean output, easy to use in shell conditionals
- **Same output for text and JSON** — `true`/`false` are valid JSON values

**Example Usage**:

```bash
# Check if environment exists
torrust-tracker-deployer exists my-env

# Use in shell scripts
if [ "$(torrust-tracker-deployer exists my-env)" = "true" ]; then
  echo "Environment exists"
fi
```

---

### `deploy` - Smart Deployment (Porcelain Command)

**Status**: ❌ Not Implemented (future porcelain command)  
**State Transition**: Current state → `running` (intelligent progression)  
**Purpose**: Orchestrate the deployment workflow from the current environment state to running.

```bash
torrust-tracker-deployer deploy <environment> [OPTIONS]
```

**Intelligent Behavior**:

- **From `created`**: Runs `provision` → `configure` → `release` → `run`
- **From `provisioned`**: Runs `configure` → `release` → `run`
- **From `configured`**: Runs `release` → `run`
- **From `released`**: Runs `run`
- **From `running`**: Reports already running (no-op)

**Benefits**:

- Simplified user experience for common deployment workflow
- Automatic state detection and appropriate action selection
- Reduces need to remember command sequences
- Ideal for development and testing workflows

**Options**:

- `--skip-run` - Deploy but don't start services
- `--dry-run` - Show what steps would be executed
- `--verbose` - Show detailed progress information

**Environment Variables**:

- `RUST_LOG=debug` - Show detailed deployment orchestration via tracing

**Implementation Note**: This is a **porcelain command** that will be implemented after the underlying plumbing commands (`provision`, `configure`, `release`, `run`) are stable.

---

### `create` - Environment Creation

**Status**: ❌ Not Implemented (essential for deployment)  
**State Transition**: → `created`  
**Purpose**: Initialize a new deployment environment configuration.

```bash
torrust-tracker-deployer create <environment-name> [OPTIONS]
```

**Current Limitation**: Only one hardcoded environment is supported. This command is essential for creating environments and must be implemented for basic deployment functionality.

**Essential Functionality**:

- Generate environment configuration files
- Set up directory structure for the environment
- Create SSH key pairs if needed
- Initialize template customizations

**Options**:

- `--provider <lxd|multipass>` - Infrastructure provider
- `--template <path>` - Custom template directory
- `--ssh-key <path>` - Specific SSH key to use

---

### `provision` - Infrastructure Provisioning

**Status**: ✅ Implemented (in E2E tests)  
**State Transition**: `created` → `provisioned`  
**Purpose**: Create and initialize VM/container infrastructure.

```bash
torrust-tracker-deployer provision <environment> [OPTIONS]
```

**Current Implementation**:

- Renders OpenTofu templates to `build/tofu/`
- Runs `tofu init` and `tofu apply`
- Creates LXD container with cloud-init
- Waits for network connectivity
- Returns instance IP address

**What It Does**:

1. Template rendering (OpenTofu configurations)
2. Infrastructure initialization (`tofu init`)
3. Resource creation (`tofu apply`)
4. Network and SSH connectivity validation

**Options**:

- `--auto-approve` - Skip confirmation prompts
- `--keep-on-failure` - Don't cleanup on provision failure

**Environment Variables**:

- `RUST_LOG=debug` - Detailed provisioning logs via tracing

---

### `register` - Register Existing Infrastructure

**Status**: ✅ Implemented  
**State Transition**: `created` → `provisioned`  
**Purpose**: Register existing infrastructure as an alternative to provisioning new resources.

```bash
torrust-tracker-deployer register <environment> --instance-ip <IP_ADDRESS>
```

**Current Implementation**:

- Loads existing environment in `Created` state
- Validates SSH connectivity using environment's SSH credentials
- Sets `runtime_outputs.instance_ip` to the provided IP address
- Marks environment with `provision_method: Registered` metadata
- Renders Ansible templates with runtime variables
- Transitions to `Provisioned` state

**Use Cases**:

- Deploy to spare/existing servers
- Use infrastructure from unsupported cloud providers
- E2E testing with Docker containers (faster than VMs)
- Custom infrastructure configurations

**Arguments**:

- `<environment>` - Name of environment in `Created` state
- `--instance-ip <IP_ADDRESS>` - IP address of existing instance (IPv4 or IPv6)

**Instance Requirements**:

- Ubuntu 24.04 LTS
- SSH connectivity with credentials from `create environment`
- Public SSH key installed for access
- Username with sudo access

**Example**:

```bash
# First, create the environment with SSH credentials
torrust-tracker-deployer create environment -f config.json

# Register existing server instead of provisioning
torrust-tracker-deployer register my-environment --instance-ip 192.168.1.100

# Output:
# ✓ Loading environment...
# ✓ Validating SSH connectivity...
# ✓ Registering instance IP: 192.168.1.100
# ✓ Rendering Ansible templates...
# ✓ Environment registered successfully
```

**Important**: When you destroy a registered environment, the underlying infrastructure is **preserved**. Only the deployer's environment data is removed. This is a key safety feature for registered instances.

**Environment Variables**:

- `RUST_LOG=debug` - Detailed registration logs via tracing

---

### `render` - Generate Deployment Artifacts

**Status**: ✅ Implemented  
**State Transition**: None (read-only operation)  
**Purpose**: Generate all deployment artifacts without provisioning infrastructure.

```bash
# From existing environment
torrust-tracker-deployer render --env-name <environment> --instance-ip <IP_ADDRESS> --output-dir <OUTPUT_PATH>

# From configuration file
torrust-tracker-deployer render --env-file <config_file> --instance-ip <IP_ADDRESS> --output-dir <OUTPUT_PATH>

# Overwrite existing output directory
torrust-tracker-deployer render --env-name <environment> --instance-ip <IP_ADDRESS> --output-dir <OUTPUT_PATH> --force
```

**Current Implementation**:

- Validates input parameters (environment exists or config file valid)
- Parses environment configuration
- Validates IP address format (IPv4/IPv6)
- Renders all 8 service templates:
  - OpenTofu infrastructure code
  - Ansible playbooks and inventory
  - Docker Compose service definitions
  - Tracker configuration (tracker.toml)
  - Prometheus monitoring configuration
  - Grafana dashboard provisioning
  - Caddy reverse proxy configuration (if HTTPS enabled)
  - Backup scripts (if backup enabled)
- Writes artifacts to user-specified output directory
- Does NOT change environment state

**Use Cases**:

- **Preview artifacts** - Inspect what will be deployed before provisioning
- **Manual deployment** - Generate artifacts for use with external tools
- **Configuration validation** - Verify template rendering with actual values
- **Artifact comparison** - Compare configurations between different setups

**Input Modes**:

1. **`--env-name` mode** - Uses existing environment in `Created` state
2. **`--env-file` mode** - Generates artifacts directly from config file (no environment required)

**Arguments**:

- `--env-name <NAME>` - Name of existing environment (mutually exclusive with `--env-file`)
- `--env-file <PATH>` - Path to configuration file (mutually exclusive with `--env-name`)
- `--instance-ip <IP>` - Target instance IP address (required)
- `--output-dir <PATH>` - Output directory for generated artifacts (required)
- `--force` - Overwrite existing output directory (optional)

**Why IP is Required**:

- In `Created` state, infrastructure doesn't exist yet (no real IP)
- With `--env-file`, no infrastructure is ever created
- IP is needed for Ansible inventory generation

**Why Output Directory is Required**:

- **Prevents conflicts** with provision artifacts in `build/{env}/`
- **Enables preview** without overwriting deployment artifacts
- **Allows multiple renders** with different IPs or configurations
- **Clear separation** between preview (render) and deployment (provision)

**Examples**:

```bash
# Preview artifacts before provisioning
torrust-tracker-deployer create environment -f envs/prod.json
torrust-tracker-deployer render --env-name prod --instance-ip 203.0.113.50 --output-dir ./preview-prod
ls -la preview-prod/  # Inspect generated artifacts
torrust-tracker-deployer provision prod  # Proceed if satisfied (writes to build/prod/)

# Generate artifacts directly from config (no environment)
torrust-tracker-deployer render \
  --env-file envs/staging.json \
  --instance-ip 192.168.1.100 \
  --output-dir /tmp/staging-artifacts

# Manual deployment workflow
torrust-tracker-deployer render --env-file envs/prod.json --instance-ip 203.0.113.50 --output-dir /tmp/manual-deploy
cd /tmp/manual-deploy/tofu && tofu apply
cd ../ansible && ansible-playbook -i inventory.yml deploy.yml
```

**Output Directory Structure**:

```text
<output-dir>/
├── tofu/           # Infrastructure code (OpenTofu)
├── ansible/        # Configuration management (playbooks + inventory with IP)
├── docker-compose/ # Service orchestration
├── tracker/        # Tracker configuration
├── prometheus/     # Metrics collection
├── grafana/        # Visualization dashboards
├── caddy/          # Reverse proxy (if HTTPS)
└── backup/         # Backup scripts (if enabled)
```

**Comparison with Provision**:

| Aspect          | render                   | provision                  |
| --------------- | ------------------------ | -------------------------- |
| Infrastructure  | None created             | Creates VMs/servers        |
| State Change    | No change                | Created → Provisioned      |
| IP Address      | User-provided            | From actual infrastructure |
| Output Location | User-specified directory | build/{env}/ directory     |
| Time            | Seconds                  | Minutes                    |
| Cost            | Free                     | Provider charges           |

**Key Feature**: Render generates **identical** artifacts to provision (except IP addresses in Ansible inventory).

**Environment Variables**:

- `RUST_LOG=debug` - Detailed rendering logs via tracing

**See Also**: [Render Command Guide](user-guide/commands/render.md), [Manual E2E Testing: Render Verification](e2e-testing/manual/render-verification.md)

---

### `configure` - System Configuration

**Status**: ✅ Implemented  
**State Transition**: `provisioned` → `configured`  
**Purpose**: Configure the provisioned infrastructure with required software and system settings.

```bash
torrust-tracker-deployer configure <environment>
```

**Current Implementation**:

- Renders Ansible templates with runtime variables
- Waits for cloud-init completion
- Installs Docker engine via Ansible playbook
- Installs Docker Compose via Ansible playbook
- Verifies successful installation
- Updates environment state to `configured`

**Planned Enhancements** (Future):

- System security configuration (UFW firewall, automatic updates) - Partially implemented in app layer
- User account setup
- System monitoring setup
- Log rotation configuration

**Example**:

```bash
# Configure provisioned environment
torrust-tracker-deployer configure my-environment

# Output:
# ✓ Rendering Ansible templates...
# ✓ Waiting for cloud-init completion...
# ✓ Installing Docker...
# ✓ Installing Docker Compose...
# ✓ Environment configured successfully
```

---

### `release` - Application Deployment

**Status**: ❌ Not Implemented (critical for deployment)  
**State Transition**: `configured` → `released`  
**Purpose**: Deploy Torrust Tracker application files and configuration.

```bash
torrust-tracker-deployer release <environment> [OPTIONS]
```

**Critical Functionality**:

- Generate Docker Compose configuration for Torrust Tracker
- Create environment variable files
- Copy application configuration to VM
- Pull required Docker images
- Validate configuration files

**Options**:

- `--config <path>` - Custom tracker configuration
- `--image-tag <tag>` - Specific Torrust Tracker image version
- `--dry-run` - Validate without deploying

---

### `run` - Application Startup

**Status**: ❌ Not Implemented  
**State Transition**: `released` → `running`  
**Purpose**: Start the Torrust Tracker Docker Compose stack.

```bash
torrust-tracker-deployer run <environment> [OPTIONS]
```

**Should Include**:

- Execute `docker-compose up -d`
- Validate service startup
- Check container health status
- Display service URLs and ports

**Options**:

- `--wait` - Wait for all services to be healthy
- `--logs` - Show service logs during startup
- `--timeout <seconds>` - Startup timeout

---

### `test` - Infrastructure Validation

**Status**: ✅ Implemented  
**State Transition**: None (validation only, does not change environment state)  
**Purpose**: Verify that the deployment infrastructure is properly configured and ready.

```bash
torrust-tracker-deployer test <environment>
```

**Current Implementation**:

- Verifies cloud-init completion on the provisioned instance
- Validates Docker installation and availability
- Validates Docker Compose installation and version
- Returns success/failure status for the entire infrastructure stack

**Use Cases**:

- Verify infrastructure after provisioning
- Confirm configuration was successful
- Validate environment before application deployment
- Troubleshooting infrastructure issues

**Example**:

```bash
# Test infrastructure readiness
torrust-tracker-deployer test my-environment

# Output:
# ✓ Checking cloud-init status...
# ✓ Validating Docker installation...
# ✓ Validating Docker Compose installation...
# ✓ All infrastructure checks passed
```

**Planned Enhancements** (Future):

- HTTP endpoint health checks (when application is deployed)
- Torrent tracker API validation (when tracker is running)
- Database connectivity tests (when database is deployed)
- Performance baseline checks

---

### `release` - Deploy Application Configuration

**Status**: ✅ Implemented  
**State Transition**: `Configured` → `Released`  
**Purpose**: Deploy application configuration files and prepare the environment for running services.

```bash
torrust-tracker-deployer release <environment>
```

**Current Implementation**:

- Creates storage directory structure on VM (`/opt/torrust/storage/tracker/`)
- Initializes SQLite database for tracker
- Renders tracker configuration from environment settings (`tracker.toml`)
- Generates Docker Compose environment variables (`.env`)
- Deploys all configuration files to VM
- Synchronizes Docker Compose stack files

**What Gets Deployed**:

- Tracker configuration: `/opt/torrust/storage/tracker/etc/tracker.toml`
- Database file: `/opt/torrust/storage/tracker/lib/database/tracker.db`
- Environment variables: `/opt/torrust/.env`
- Docker Compose stack: `/opt/torrust/docker-compose.yml`

**Use Cases**:

- Deploy application after infrastructure is configured
- Update tracker configuration (re-run after editing environment.json)
- Prepare environment for running services

**Example**:

```bash
# Deploy application configuration
torrust-tracker-deployer release my-environment

# Output:
# ✓ Creating tracker storage directories...
# ✓ Initializing tracker database...
# ✓ Rendering tracker templates...
# ✓ Deploying tracker configuration...
# ✓ Deploying Docker Compose files...
# ✓ Release complete - environment ready to run
```

**Configuration Source**:

The release command uses tracker configuration from your environment JSON:

```json
{
  "tracker": {
    "core": {
      "database_name": "tracker.db",
      "private": false
    },
    "udp_trackers": [{ "bind_address": "0.0.0.0:6868" }],
    "http_trackers": [{ "bind_address": "0.0.0.0:7070" }],
    "http_api": {
      "bind_address": "0.0.0.0:1212",
      "admin_token": "MyAccessToken"
    }
  }
}
```

**Idempotent Operation**:

- Can be re-run safely to update configuration
- Existing database is preserved
- Configuration files are overwritten with new values

---

### `run` - Start Tracker Services

**Status**: ✅ Implemented  
**State Transition**: `Released` → `Running`  
**Purpose**: Start the Torrust Tracker application services and validate they are running.

```bash
torrust-tracker-deployer run <environment>
```

**Current Implementation**:

- Starts Docker Compose services (`docker compose up -d`)
- Validates services are running via Docker status
- Performs external health checks on tracker API
- Verifies firewall allows external access

**Services Started**:

- **Tracker container** (`torrust/tracker:develop`)
  - UDP Tracker endpoints (ports 6868, 6969 by default)
  - HTTP Tracker endpoint (port 7070 by default)
  - HTTP API endpoint (port 1212 by default)

**Health Checks Performed**:

1. **Docker Compose Status** - Verifies containers are running
2. **Tracker API Health** (required) - Tests external accessibility of HTTP API
   - Endpoint: `http://<vm-ip>:1212/api/health_check`
   - Validates service functionality AND firewall configuration
3. **HTTP Tracker Health** (required) - Tests external accessibility of HTTP tracker
   - Endpoint: `http://<vm-ip>:7070/health_check`
   - Validates HTTP tracker is accessible externally

**Use Cases**:

- Start tracker services after release
- Restart services after configuration changes
- Validate tracker is accessible externally

**Example**:

```bash
# Start tracker services
torrust-tracker-deployer run my-environment

# Output:
# ✓ Validating environment name...
# ✓ Running application services...
# ✓ Run command completed for 'my-environment'
#
# Service URLs:
#   API:             http://192.168.1.100:1212
#   HTTP Tracker:    http://192.168.1.100:7070
#   Health Check:    http://192.168.1.100:1212/api/health_check
#
# Tip: Run 'torrust-tracker-deployer show my-environment' for full details
```

**Verification**:

After running, you can access the tracker:

```bash
# Get VM IP
VM_IP=$(torrust-tracker-deployer show my-environment | grep 'IP Address' | awk '{print $3}')

# Test tracker API
curl http://$VM_IP:1212/api/health_check

# Get tracker statistics
curl http://$VM_IP:1212/api/v1/stats
```

**Announce URLs**:

- UDP: `udp://<vm-ip>:6868/announce` or `udp://<vm-ip>:6969/announce`
- HTTP: `http://<vm-ip>:7070/announce`

---

### `status` - Environment Information

**Status**: ❌ Not Implemented  
**State Transition**: None (read-only)  
**Purpose**: Display comprehensive environment status and information.

```bash
torrust-tracker-deployer status <environment> [OPTIONS]
```

**Should Display**:

- Current deployment state
- Infrastructure status (VM running, IP address)
- Service health (containers, ports, endpoints)
- Resource usage (CPU, memory, disk)
- Recent deployment history

**Options**:

- `--format <table|json|yaml>` - Output format
- `--watch` - Continuous monitoring mode
- `--services-only` - Show only service status

---

### `destroy` - Infrastructure Cleanup

**Status**: 🔄 Being Implemented  
**State Transition**: Any state → `destroyed`  
**Purpose**: Clean up all infrastructure and resources for an environment.

```bash
torrust-tracker-deployer destroy <environment> [OPTIONS]
```

**Current Implementation**:

- Runs `tofu destroy --auto-approve`
- Removes LXD containers and networks
- Cleans up temporary files

**Should Include**:

- Stop running services gracefully
- Backup data if requested
- Remove all infrastructure resources
- Clean up local configuration files
- Confirm destruction completion

**Options**:

- `--force` - Skip confirmation prompts
- `--backup` - Create backup before destruction
- `--keep-data` - Preserve persistent data volumes

## Implementation Priority

### Phase 1: Plumbing Commands (High Priority) - ✅ MOSTLY COMPLETE

Essential low-level commands for the complete deployment workflow:

- ✅ `create template` - Template generation (completed)
- ✅ `create environment` - Environment initialization (completed)
- ✅ `provision` - Infrastructure provisioning (completed)
- ✅ `register` - Register existing infrastructure (completed)
- ✅ `configure` - System configuration (completed)
- ✅ `test` - Infrastructure validation (completed)
- ✅ `destroy` - Infrastructure cleanup (completed)
- ❌ `release` - Application deployment (not yet implemented - critical for deploying Torrust Tracker)
- ❌ `run` - Service management (not yet implemented)

### Phase 2: Operations Commands (Medium Priority)

Management and operational commands:

- ❌ `status` - Environment monitoring (not yet implemented)
- ❌ `list` - Environment listing and overview (not yet implemented)

### Phase 3: Porcelain Commands (Medium Priority)

High-level commands built on top of stable plumbing commands:

- ❌ `deploy` - Smart deployment orchestration (not yet implemented - porcelain command)

### Phase 4: Enhanced Functionality (Low Priority)

Additional features and utilities:

- ❌ `check` - Tool validation (not yet implemented)

## Notes

### Command Architecture

- **Hybrid approach**: Combines low-level plumbing commands with high-level porcelain commands
- **Plumbing first**: Individual commands (`provision`, `configure`, etc.) implemented before orchestration commands
- **Porcelain commands scope**: Only automate the deployment workflow (`provision` → `configure` → `release` → `run`)
- **Management commands**: `create`, `list`, `check`, `status`, `destroy` remain individual operations

### Technical Implementation

- All commands use the tracing crate for logging (control verbosity with `RUST_LOG` environment variable)
- Set `RUST_LOG=debug` for detailed output, `RUST_LOG=info` for standard output
- Configuration should be environment-aware once multi-env support is added
- Error handling should be consistent across all commands
- Each command should validate prerequisites before execution
- State transitions should be atomic where possible