kubernetes/kops · error

failed to update /etc/hosts: %w

Error message

failed to update /etc/hosts: %w

What it means

The UpdateEtcHosts task rewrites /etc/hosts via hosts.UpdateHostsFileWithRecords, which reads the current file, applies the record mutator, and writes it back atomically. Any failure in that read-modify-write pipeline (unwritable file, read error, rename failure) is wrapped with %w into this error.

Source

Thrown at upup/pkg/fi/nodeup/nodetasks/update_etc_hosts_task.go:92

func (_ *UpdateEtcHostsTask) RenderLocal(t *local.LocalTarget, a, e, changes *UpdateEtcHostsTask) error {
	etcHostsPath := "/etc/hosts"

	mutator := func(existing []string) (*hosts.HostMap, error) {
		hostMap := &hosts.HostMap{}
		badLines := hostMap.Parse(existing)
		if len(badLines) != 0 {
			klog.Warningf("ignoring unexpected lines in /etc/hosts: %v", badLines)
		}

		for _, record := range e.Records {
			hostMap.ReplaceRecords(record.Hostname, record.Addresses)
		}

		return hostMap, nil
	}

	if err := hosts.UpdateHostsFileWithRecords(etcHostsPath, mutator); err != nil {
		return fmt.Errorf("failed to update /etc/hosts: %w", err)
	}
	return nil
}

View on GitHub (pinned to 4c8573c808)

Solutions

  1. Check for the immutable bit: lsattr /etc/hosts; remove with chattr -i /etc/hosts
  2. Verify write permission on /etc and /etc/hosts for the nodeup user (root)
  3. Check disk space (df -h) — atomic writes need free space for a temp file
  4. Inspect the wrapped cause (%w) in the error chain to identify the exact OS error and fix accordingly

Example fix

# before
$ lsattr /etc/hosts
----i--------- /etc/hosts
# after
$ chattr -i /etc/hosts && kops-nodeup ...
Defensive patterns

Strategy: validation

Validate before calling

// Pre-check on the node:
sudo test -w /etc/hosts && echo writable || echo 'not writable'
lsattr /etc/hosts | grep -q i && echo 'immutable /etc/hosts!' || true
df -h /etc | awk 'NR==2{exit ($5+0>95)?1:0}' || echo 'disk nearly full'

Try / catch

if err := task.RenderLocal(...); err != nil {
	var wrapped error
	if errors.As(err, &wrapped) || strings.Contains(err.Error(), "failed to update /etc/hosts") {
		return fmt.Errorf("check immutability/permissions/space on /etc/hosts: %w", err)
	}
	return err
}

Prevention

When it happens

Trigger: RenderLocal calls UpdateHostsFileWithRecords("/etc/hosts", mutator) and it errors: /etc read-only, /etc/hosts unreadable/corrupt, disk full preventing the temp-file+rename, or permission denied for the writing user.

Common situations: Immutable /etc/hosts (chattr +i, common on some container images and cloud-init templates), read-only rootfs, disk-full nodes, or running the task as a non-root user.

Related errors


AI-assisted analysis of kubernetes/kops@4c8573c808 (2026-09-05). Data as JSON: /api/errors/861931eab9e34020. Report an issue: GitHub.