kubectl Usage Conventions
Recommended usage conventions for kubectl.
Using kubectl in Reusable Scripts
For a stable output in a script:
- Request one of the machine-oriented output forms, such as
-o name,-o json,-o yaml,-o go-template, or-o jsonpath. - Fully-qualify the version. For example,
jobs.v1.batch/myjob. This will ensure that kubectl does not use its default version that can change over time. - Don't rely on context, preferences, or other implicit states.
Subresources
- You can use the
--subresourceargument for kubectl subcommands such asget,patch,edit,applyandreplaceto fetch and update subresources for all resources that support them. In Kubernetes version 1.36, only thestatus,scaleandresizesubresources are supported.- For
kubectl edit, thescalesubresource is not supported. If you use--subresourcewithkubectl editand specifyscaleas the subresource, the command will error out.
- For
- The API contract against a subresource is identical to a full resource. While updating the
statussubresource to a new value, keep in mind that the subresource could be potentially reconciled by a controller to a different value.
Best Practices
kubectl run
For kubectl run to satisfy infrastructure as code:
- Tag the image with a version-specific tag and don't move that tag to a new version. For example, use
:v1234,v1.2.3,r03062016-1-4, rather than:latest(For more information, see Kubernetes Configuration Good Practices). - Check in the script for an image that is heavily parameterized.
- Switch to configuration files checked into source control for features that are needed, but not expressible via
kubectl runflags.
You can use the --dry-run=client flag to preview the object that would be sent to your cluster, without really submitting it.
kubectl proxy
Caution:
Browsing untrusted pod or service endpoints through kubectl proxy is dangerous,
as the served content has implicit access to the Kubernetes API using the proxy's
credentials. Use caution and avoid accessing untrusted endpoints while using
privileged credentials.
To reduce risk:
- Avoid browsing to untrusted pods or services through
kubectl proxy. - Use
--reject-methods='POST,PUT,PATCH,DELETE'to restrict the proxy to read-only operations when you only need to view resources. - Use
--reject-pathsto limit which API paths the proxy exposes. - Do not run
kubectl proxywith cluster-admin credentials unless necessary.
kubectl apply
- You can use
kubectl applyto create or update resources. For more information about using kubectl apply to update resources, see Kubectl Book.