Skip to content

trevorrea/sortTF

Β 
Β 

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

15 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

sortTF

A powerful command-line tool for sorting and formatting Terraform (.tf) and Terragrunt (.hcl) files to ensure consistency and readability across your infrastructure code.

πŸš€ Features at a Glance

  • Smart Block Sorting: Orders Terraform blocks for readability and best practices.
  • Attribute Sorting: Alphabetizes attributes, with special handling for count, for_each, and name.
  • Nested Block Support: Handles deeply nested and complex HCL structures.
  • IAM Policy Document Exclusion: Option to exclude aws_iam_policy_document data blocks from sorting.
  • Formatting: Applies terraform fmt standards.
  • Multiple Modes: Dry-run, validation, and recursive directory processing.
  • Comprehensive Error Handling: Detailed, colorized error messages.
  • Cross-Platform: Works on macOS, Linux, and Windows.
  • Tested & Modular: Well-tested, DRY, and maintainable codebase.

⚑ Quickstart

# Install (from source)
git clone https://github.com/yourusername/sortTF.git
cd sortTF
go build -o sorttf
sudo mv sorttf /usr/local/bin/

# Or using Go install
go install github.com/OBerger96/sortTF@latest

# Basic usage
sorttf .

πŸ› οΈ Prerequisites

  • Go 1.24.4+ (for building from source)
  • Terraform (for formatting functionality)

πŸ“– Usage

Basic Usage

sorttf .                                  # Sort and format files in current directory
sorttf main.tf                            # Sort and format a specific file
sorttf --recursive .                      # Recursively process subdirectories
sorttf --dry-run .                        # Show what would change without writing
sorttf --validate .                       # Validate files without making changes
sorttf --verbose .                        # Verbose output
sorttf --exclude-iam-policy-documents .   # Exclude aws_iam_policy_document data blocks

Command Line Options

Flag Description
--recursive Scan directories recursively
--dry-run Show what would be changed without writing (shows a unified diff)
--verbose Print detailed logs about which files were parsed, sorted, and formatted
--validate Exit with a non-zero code if any files are not sorted/formatted
--exclude-iam-policy-documents Exclude aws_iam_policy_document data blocks from sorting

Examples

sorttf main.tf
sorttf --recursive --verbose .
sorttf --validate --recursive .
sorttf --dry-run --recursive .
sorttf --exclude-iam-policy-documents --recursive .

πŸ”§ How It Works

Block Sorting Order

sortTF sorts Terraform blocks in the following order:

  1. terraform
  2. provider
  3. variable
  4. locals
  5. data
  6. resource
  7. module
  8. output

Attribute Sorting

  • count or for_each are always placed first (if present, they are mutually exclusive)
  • name attribute is placed second (if present)
  • Other attributes are sorted alphabetically
  • Nested blocks are sorted by type and then by labels

Example Transformation

Before:

resource "aws_instance" "web" {
  instance_type = "t3.micro"
  ami           = "ami-123456"
  tags = { Name = "web-server" }
}
provider "aws" { region = "us-west-2" }
variable "environment" { type = string }

After:

provider "aws" { region = "us-west-2" }
variable "environment" { type = string }
resource "aws_instance" "web" {
  ami           = "ami-123456"
  instance_type = "t3.micro"
  tags = { Name = "web-server" }
}

πŸ§ͺ Testing

go test ./...           # Run all tests
go test -v ./...        # Verbose output
go test -cover ./...    # Run with coverage

πŸ—οΈ Development

Project Structure

sortTF/
β”œβ”€β”€ main.go                 # Application entry point
β”œβ”€β”€ utils/
β”‚   β”œβ”€β”€ cliutil/           # Command-line interface
β”‚   β”œβ”€β”€ argsutil/          # CLI argument parsing
β”‚   β”œβ”€β”€ errorutil/         # Error helpers and types
β”‚   β”œβ”€β”€ fileutil/          # File system operations
β”‚   β”œβ”€β”€ formattingutil/    # HCL formatting
β”‚   β”œβ”€β”€ parsingutil/       # HCL parsing and validation
β”‚   └── sortingutil/       # Block and attribute sorting

Building

# Build for current platform
go build -o sorttf

# Build for specific platforms
GOOS=linux GOARCH=amd64 go build -o sorttf-linux
GOOS=darwin GOARCH=amd64 go build -o sorttf-darwin
GOOS=windows GOARCH=amd64 go build -o sorttf-windows.exe

Code Quality

# Run linter
go vet ./...

# Format code
go fmt ./...

# Run tests with coverage
go test -cover ./...

🀝 Contributing

  1. Fork the repository
  2. Create a feature branch (git checkout -b feature/amazing-feature)
  3. Commit your changes (git commit -m 'Add some amazing feature')
  4. Push to the branch (git push origin feature/amazing-feature)
  5. Open a Pull Request

Development Guidelines

  • Follow Go coding standards
  • Add tests for new features
  • Update documentation as needed
  • Ensure all tests pass before submitting PR

πŸ“ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ› Known Issues & Limitations

Inline Comments Not Preserved

sortTF does not preserve inline comments (comments on the same line as code). This is a fundamental limitation of the HCL writer library used by the tool.

Example:

# Before sorting
resource "aws_instance" "example" {
  limit_amount = "100" # Not used due to https://github.com/hashicorp/terraform-provider-aws/issues/28981
  instance_type = "t3.micro"
}

# After sorting - inline comment is lost
resource "aws_instance" "example" {
  instance_type = "t3.micro"
  limit_amount = "100"
}

Workaround: Place important comments on their own line above the attribute:

resource "aws_instance" "example" {
  instance_type = "t3.micro"
  # Not used due to https://github.com/hashicorp/terraform-provider-aws/issues/28981
  limit_amount = "100"
}

Block-level comments (comments on their own lines) are preserved and will move with the blocks they precede.

Other Known Issues

  • Requires Terraform to be installed for formatting functionality
  • Some edge cases with deeply nested blocks may need manual review

πŸ“ž Support

πŸ™ Acknowledgments

  • Built with HashiCorp HCL
  • Inspired by terraform fmt and similar formatting tools
  • Thanks to the Go community for excellent tooling and libraries

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Go 100.0%