---
title: "kubectl-generated YAML lists container fields alphabetically, so sed on '- name:' silently misses"
url: "https://www.dariuszparys.com/notes/kubectl-generated-yaml-lists-container-fields-alphabetically"
author: "Dariusz Parys"
published: 2026-11-20T00:00:00.000Z
description: "kubectl writes a container's fields in alphabetical order, so the list item starts with image, and a sed pattern on '- name:' matches nothing while still exiting 0."
tags:
  - "Kubernetes"
  - "Shell"
---

# kubectl-generated YAML lists container fields alphabetically, so sed on '- name:' silently misses

## Context

A common speed trick: generate a pod with `kubectl run ... --dry-run=client -o yaml`, then rename the container with `sed` before applying.

## Insight

kubectl writes each container's fields in alphabetical order, so the list item starts with `- image:`, and `name:` sits on the next line **without** the dash:

<!-- prettier-ignore -->
```yaml
  containers:
  - image: nginx:1.27
    name: webpod
```

A pattern like `s/- name: webpod/- name: webcont/` never matches. `sed` still exits 0, so you get no error, and the pod is created with the old container name. Later steps that use the new name then fail, such as `kubectl set image pod/webpod webcont=...`.

## Fix

Match the indented line instead, or edit in vim, and check the result:

```bash
kubectl run webpod --image=nginx:1.27 --dry-run=client -o yaml > pod.yaml
sed -i 's/^    name: webpod$/    name: webcont/' pod.yaml   # GNU sed; macOS: sed -i ''
kubectl apply -f pod.yaml
kubectl get pod webpod -o jsonpath='{.spec.containers[0].name}{"\n"}'   # webcont
```

`metadata.name` stays `webpod`, because only the container's indented line matches.
