hashicorp/packer · error

failed to open %s: %s

Error message

failed to open %s: %s

What it means

processFile opens the target file with os.Open before parsing; if the open fails (missing file, permission denied, path is a directory), it wraps the OS error as 'failed to open %s: %s'. This happens before any HCL parsing occurs.

Source

Thrown at hcl2template/formatter.go:133

	if f.Output == nil {
		f.Output = os.Stdout
	}

	if !(filename == "-") && !isHcl2FileOrVarFile(filename) {
		return nil, fmt.Errorf("file %s is not a HCL file", filename)
	}

	var in io.Reader
	var err error

	if filename == "-" {
		in = os.Stdin
		f.ShowDiff = false
	} else {
		in, err = os.Open(filename)
		if err != nil {
			return nil, fmt.Errorf("failed to open %s: %s", filename, err)
		}
	}

	inSrc, err := io.ReadAll(in)
	if err != nil {
		return nil, fmt.Errorf("failed to read %s: %s", filename, err)
	}

	_, diags := f.parser.ParseHCL(inSrc, filename)
	if diags.HasErrors() {
		return nil, multierror.Append(nil, diags.Errs()...)
	}

	outSrc := hclwrite.Format(inSrc)

	if bytes.Equal(inSrc, outSrc) {
		if filename == "-" {
			_, _ = f.Output.Write(outSrc)

View on GitHub (pinned to eb36e3c3e4)

Solutions

  1. Check the path exists with 'ls <file>' and fix typos
  2. Verify read permissions for the current user
  3. Ensure the argument is a regular file, not a directory
  4. If the path came from a glob, tighten the pattern to files only

Example fix

// before
packer fmt ./templates/   // directory
// after
packer fmt ./templates/*.pkr.hcl
Defensive patterns

Strategy: validation

Validate before calling

if info, err := os.Stat(path); err != nil || info.IsDir() { /* resolve before calling packer fmt */ }

Try / catch

if err := f.FormatFile(path); err != nil {
  var pe *fs.PathError
  if errors.As(err, &pe) && errors.Is(pe.Err, fs.ErrNotExist) { /* handle missing file */ }
}

Prevention

When it happens

Trigger: formatFile/processFile invoked with a filename that does not exist, lacks read permission, or is a directory (and filename is not '-', which uses stdin).

Common situations: Typo'd paths on 'packer fmt'; globbing patterns that matched directories; files deleted between discovery and formatting; restrictive permissions after checkout on Windows/CI.

Understand the failure class

Background: "open() failed", "failed to open file", "cannot create file" — what a file open error means and how to fix it — this error's family across 42 libraries.

Related errors


AI-assisted analysis of hashicorp/packer@eb36e3c3e4 (2026-09-05). Data as JSON: /api/errors/67e0417bab000ec7. Report an issue: GitHub.