2 min read | by Jordi Prats
To update a kubernetes object we can use kubectl apply or kubectl replace, but depending on what and how we want it updated we need to use one or the other.
When using kubectl apply, it uses the provided spec to create a resource if it doesn't exists, but if it does, patch it. The spec that we need to provide all the different parts, using defaults for the rest when creating or the current values when updating:
Depending on the current state, Kubernetes it's going to decide what properties of the object need to be changed.
When using kubectl replace, it tries to replace the current object with the one we are providing. When using it we need to provide a complete spec, including the readonly properties like metadata.resourceVersion
When using kubectl replace with a partial object, it will use the default values for any fields that are not specified in the partial object, rather than preserving the current values as kubectl apply would. Additionally, if the object you are trying to replace does not already exist, kubectl replace will return an error and the object will not be created.
It's use case is usually: getting a resource, updating it by some means and pushing it back with kubectl replace.
To update an object in Kubernetes, use kubectl apply if you only have a partial object with specific settings to update, while keeping the rest of the object unchanged. If you have the complete object and have made changes to it, use kubectl replace to apply the changes.
Posted on 23/01/2023