# Preserve existing selectors

Kubernetes does not allow a Deployment or StatefulSet selector to change in
place. Before Kix takes ownership of an existing workload, configure its
instance to retain that selector.

## Read the current selector

Get the selector from the live workload:

<Command
  commands={[
    "kubectl get deployment legacy-web -n apps -o jsonpath='{.spec.selector.matchLabels}'",
  ]}
/>

Use the labels from `spec.selector.matchLabels`, not every label on the
workload. Confirm that the Pod template has the same labels before continuing.

## Set the selector on the instance

Copy those labels into `selectorLabels`:

<Snippet {...preserveExistingSelectors} />

Kix passes this value to package builders as `scope.selectorLabels`. Workload
helpers use it for both `spec.selector.matchLabels` and the Pod template
labels, and Service helpers use it when selecting the workload.

The package must build its selectors from `scope.selectorLabels` for this
instance option to take effect.

## Check before deploying

Evaluate the cluster:

<Command {...check} />

Render the workload and compare both label sets with the live Deployment:

<Command {...deployment} />

The rendered selector and Pod labels contain the existing `app` and `tier`
values. Compare them against the `kubectl get` output from the first step.

`kix diff` cannot make this comparison. It finds live resources through Kix's
management labels, which the existing workload does not yet have. The diff
therefore shows the workload as a new resource and never compares the
selectors.

Ask the API server instead:

<Command
  commands={["kix deploy how-to-adoption --dry-run"]}
  cwd="kix-examples/"
/>

Deployment and StatefulSet selectors are immutable. A mismatch therefore
fails the dry run, either as an immutable-field error or as a field-ownership
conflict when another manager owns the selector.

:::caution
Do not deploy if the rendered `spec.selector.matchLabels` differs from the
live one, or if the dry run reports the workload being replaced. Correct
`selectorLabels` first.
:::