hashicorp/nomad · error

Failed to open file %s: %w

Error message

Failed to open file %s: %w

What it means

When nomad fmt encounters a regular file recognized as a Nomad file (isNomadFile), it opens it with os.Open. If the open fails (permission denied, race where the file vanished after stat, too many open files), it reports "Failed to open file %s: %w" with the wrapped cause and skips the file.

Source

Thrown at command/fmt.go:185

	if len(f.paths) == 0 {
		f.processFile(stdinPath, f.stdin)
		return
	}

	for _, path := range f.paths {
		info, err := os.Stat(path)
		if err != nil {
			f.appendError(fmt.Errorf("No file or directory at %s", path))
			continue
		}

		if info.IsDir() {
			f.processDir(path)
		} else {
			if isNomadFile(info) {
				fp, err := os.Open(path)
				if err != nil {
					f.appendError(fmt.Errorf("Failed to open file %s: %w", path, err))
					continue
				}

				f.processFile(path, fp)

				fp.Close()
			} else {
				f.appendError(fmt.Errorf("Only .nomad and .hcl files can be processed using nomad fmt"))
				continue
			}
		}
	}
}

func (f *FormatCommand) processDir(path string) {
	entries, err := os.ReadDir(path)
	if err != nil {
		f.appendError(fmt.Errorf("Failed to list directory %s", path))

View on GitHub (pinned to 482b49bf1a)

Solutions

  1. Check/fix file permissions (read access for the invoking user)
  2. Re-run fmt; if a race deleted the file, ensure no concurrent process removes files during formatting
  3. For 'too many open files', raise ulimit -n or run fmt on smaller directory subsets

Example fix

// before
nomad fmt /etc/nomad.d/  # Failed to open file /etc/nomad.d/jobs.hcl: permission denied
// after
sudo chmod o+r /etc/nomad.d/jobs.hcl   # or run nomad fmt as a user with read access
Defensive patterns

Strategy: try-catch

Validate before calling

f, err := os.OpenFile(path, os.O_RDONLY, 0)
if err != nil {
    if os.IsPermission(err) { /* fix perms or skip */ }
}

Try / catch

fp, err := os.Open(path)
if err != nil {
    if os.IsPermission(err) {
        // report and skip or escalate permissions
    } else if errors.Is(err, syscall.EMFILE) {
        // raise ulimit or batch the directory walk
    }
    return err
}
defer fp.Close()

Prevention

When it happens

Trigger: fmt → os.Open(path) failing after a successful os.Stat: file permissions changed, file deleted between stat and open, or EMFILE when processing huge directory trees.

Common situations: Files owned by another user with restrictive modes; files removed concurrently by a build process; recursive fmt over enormous trees hitting the OS file-descriptor limit.

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/nomad@482b49bf1a (2026-09-04). Data as JSON: /api/errors/a769a43078e54542. Report an issue: GitHub.