Format Resource with Provisioner Blocks

Format Terraform resources that include provisioner blocks for remote-exec, local-exec, and file provisioners with proper nesting and connection blocks.

Resources

Detailed Explanation

Formatting Provisioner Blocks

Provisioners add complexity to resource blocks because they introduce multiple levels of nesting: the resource itself, the provisioner block, and often a connection block. Clean formatting is essential for understanding the execution flow.

Example with Provisioners

resource "aws_instance" "web" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = var.instance_type
  key_name      = aws_key_pair.deployer.key_name
  subnet_id     = aws_subnet.public[0].id

  vpc_security_group_ids = [
    aws_security_group.web.id,
    aws_security_group.ssh.id,
  ]

  connection {
    type        = "ssh"
    user        = "ubuntu"
    private_key = file("~/.ssh/deployer.pem")
    host        = self.public_ip
  }

  provisioner "remote-exec" {
    inline = [
      "sudo apt-get update",
      "sudo apt-get install -y nginx",
      "sudo systemctl enable nginx",
      "sudo systemctl start nginx",
    ]
  }

  provisioner "local-exec" {
    command = "echo ${self.public_ip} >> inventory.txt"
  }

  lifecycle {
    create_before_destroy = true
    ignore_changes        = [ami]
  }

  tags = {
    Name = "web-server"
    Role = "frontend"
  }
}

Nesting Structure

The formatter handles three levels of nesting:

  1. Resource level: ami, instance_type, key_name — aligned at 2 spaces
  2. Block level: connection, provisioner, lifecycle — their contents at 4 spaces
  3. List values: vpc_security_group_ids and inline lists have items indented within brackets

List Formatting

Lists of strings (like security group IDs and inline commands) are formatted with:

  • Opening bracket on the same line as the key
  • Each item on its own line with trailing comma
  • Closing bracket on its own line at the key's indent level

Use Case

Formatting Terraform configurations that use provisioners for initial server setup, configuration management bootstrap, or post-deployment scripts.

Try It — Terraform HCL Formatter

Open full tool