# Managing Service Accounts

Managing Service AccountsA ServiceAccount provides an identity for processes that run in a Pod.A process inside a Pod can use the identity of its associated service account to authenticate to the cluster's API server.For an introduction to service accounts, read configure service accounts.This task guide explains some of the concepts behind ServiceAccounts. The guide also explains how to obtain or revoke tokens that represent ServiceAccounts, and how to (optionally) bind a ServiceAccount's validity to the lifetime of an API object.Before you beginYou need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:iximiuz LabsKillercodaKodeKloudPlay with KubernetesTo be able to follow these steps exactly, ensure you have a namespace named examplens. If you don't, create one by running:kubectl create namespace examplens User accounts versus service accountsKubernetes distinguishes between the concept of a user account and a service account for a number of reasons:User accounts are for humans. Service accounts are for application processes, which (for Kubernetes) run in containers that are part of pods.User accounts are intended to be global: names must be unique across all namespaces of a cluster. No matter what namespace you look at, a particular username that represents a user represents the same user. In Kubernetes, service accounts are namespaced: two different namespaces can contain ServiceAccounts that have identical names.Typically, a cluster's user accounts might be synchronised from a corporate database, where new user account creation requires special privileges and is tied to complex business processes. By contrast, service account creation is intended to be more lightweight, allowing cluster users to create service accounts for specific tasks on demand. Separating ServiceAccount creation from the steps to onboard human users makes it easier for workloads to follow the principle of least privilege.Auditing considerations for humans and service accounts may differ; the separation makes that easier to achieve.A configuration bundle for a complex system may include definition of various service accounts for components of that system. Because service accounts can be created without many constraints and have namespaced names, such configuration is usually portable.Bound service account tokensServiceAccount tokens can be bound to API objects that exist in the kube-apiserver. This can be used to tie the validity of a token to the existence of another API object. Supported object types are as follows:Pod (used for projected volume mounts, see below)Secret (can be used to allow revoking a token by deleting the Secret)Node (can be used to auto-revoke a token when its Node is deleted; creating new node-bound tokens is GA in v1.33+)When a token is bound to an object, the object's metadata.name and metadata.uid are stored as extra 'private claims' in the issued JWT.When a bound token is presented to the kube-apiserver, the service account authenticator will extract and verify these claims. If the referenced object or the ServiceAccount is pending deletion (for example, due to finalizers), then for any instant that is 60 seconds (or more) after the .metadata.deletionTimestamp date, authentication with that token would fail. If the referenced object no longer exists (or its metadata.uid does not match), the request will not be authenticated.Additional metadata in Pod bound tokensFEATURE STATE: Kubernetes v1.32 [stable] (enabled by default: true)When a service account token is bound to a Pod object, additional metadata is also embedded into the token that indicates the value of the bound pod's spec.nodeName field, and the uid of that Node, if available.This node information is not verified by the kube-apiserver when the token is used for authentication. It is included so integrators do not have to fetch Pod or Node API objects to check the associated Node name and uid when inspecting a JWT.Verifying and inspecting private claimsThe TokenReview API can be used to verify and extract private claims from a token:First, assume you have a pod named test-pod and a service account named my-sa.Create a token that is bound to this Pod:kubectl create token my-sa --bound-object-kind="Pod" --bound-object-name="test-pod" Copy this token into a new file named tokenreview.yaml:apiVersion: authentication.k8s.io/v1 kind: TokenReview spec: token: <token from step 2> Submit this resource to the apiserver for review:# use '-o yaml' to inspect the output kubectl create -o yaml -f tokenreview.yaml You should see an output like below:apiVersion: authentication.k8s.io/v1 kind: TokenReview metadata: creationTimestamp: null spec: token: <token> status: audiences: - https://kubernetes.default.svc.cluster.local authenticated: true user: extra: authentication.kubernetes.io/credential-id: - JTI=7ee52be0-9045-4653-aa5e-0da57b8dccdc authentication.kubernetes.io/node-name: - kind-control-plane authentication.kubernetes.io/node-uid: - 497e9d9a-47aa-4930-b0f6-9f2fb574c8c6 authentication.kubernetes.io/pod-name: - test-pod authentication.kubernetes.io/pod-uid: - e87dbbd6-3d7e-45db-aafb-72b24627dff5 groups: - system:serviceaccounts - system:serviceaccounts:default - system:authenticated uid: f8b4161b-2e2b-11e9-86b7-2afc33b31a7e username: system:serviceaccount:default:my-sa Note:Despite using kubectl create -f to create this resource, and defining it similar to other resource types in Kubernetes, TokenReview is a special type and the kube-apiserver does not actually persist the TokenReview object into etcd. Hence kubectl get tokenreview is not a valid command.Schema for service account private claimsThe schema for the Kubernetes-specific claims within JWT tokens is not currently documented, however the relevant code area can be found in the serviceaccount package in the Kubernetes codebase.You can inspect a JWT using standard JWT decoding tool. Below is an example of a JWT for the my-serviceaccount ServiceAccount, bound to a Pod object named my-pod which is scheduled to the Node my-node, in the my-namespace namespace:{ "aud": [ "https://my-audience.example.com" ], "exp": 1729605240, "iat": 1729601640, "iss": "https://my-cluster.example.com", "jti": "aed34954-b33a-4142-b1ec-389d6bbb4936", "kubernetes.io": { "namespace": "my-namespace", "node": { "name": "my-node", "uid": "646e7c5e-32d6-4d42-9dbd-e504e6cbe6b1" }, "pod": { "name": "my-pod", "uid": "5e0bd49b-f040-43b0-99b7-22765a53f7f3" }, "serviceaccount": { "name": "my-serviceaccount", "uid": "14ee3fa4-a7e2-420f-9f9a-dbc4507c3798" } }, "nbf": 1729601640, "sub": "system:serviceaccount:my-namespace:my-serviceaccount" } Note:The aud and iss fields in this JWT may differ between different Kubernetes clusters depending on your configuration.The presence of both the pod and node claim implies that this token is bound to a Pod object. When verifying Pod bound ServiceAccount tokens, the API server does not verify the existence of the referenced Node object.Services that run outside of Kubernetes and want to perform offline validation of JWTs may use this schema, along with a compliant JWT validator configured with OpenID Discovery information from the API server, to verify presented JWTs without requiring use of the TokenReview API.Services that verify JWTs in this way do not verify the claims embedded in the JWT token to be current and still valid. This means if the token is bound to an object, and that object no longer exists, the token will still be considered valid (until the configured token expires).Clients that require assurance that a token's bound claims are still valid MUST use the TokenReview API to present the token to the kube-apiserver for it to verify and expand the embedded claims, using similar steps to the Verifying and inspecting private claims section above, but with a supported client library. For more information on JWTs and their structure, see the JSON Web Token RFC.Bound service account token volume mechanismFEATURE STATE: Kubernetes v1.22 [stable] (enabled by default: true)By default, the Kubernetes control plane (specifically, the ServiceAccount admission controller) adds a projected volume to Pods, and this volume includes a token for Kubernetes API access.Here's an example of how that looks for a launched Pod:... - name: kube-api-access-<random-suffix> projected: sources: - serviceAccountToken: path: token # must match the path the app expects - configMap: items: - key: ca.crt path: ca.crt name: kube-root-ca.crt - downwardAPI: items: - fieldRef: apiVersion: v1 fieldPath: metadata.namespace path: namespace That manifest snippet defines a projected volume that consists of three sources. In this case, each source also represents a single path within that volume. The three sources are:A serviceAccountToken source, that contains a token that the kubelet acquires from kube-apiserver. The kubelet fetches time-bound tokens using the TokenRequest API. A token served for a TokenRequest expires either when the pod is deleted or after a defined lifespan (by default, that is 1 hour). The kubelet also refreshes that token before the token expires. The token is bound to the specific Pod and has the kube-apiserver as its audience. This mechanism superseded an earlier mechanism that added a volume based on a Secret, where the Secret represented the ServiceAccount for the Pod, but did not expire.A configMap source. The ConfigMap contains a bundle of certificate authority data. Pods can use these certificates to make sure that they are connecting to your cluster's kube-apiserver (and not to middlebox or an accidentally misconfigured peer).A downwardAPI source that looks up the name of the namespace containing the Pod, and makes that name information available to application code running inside the Pod.Any container within the Pod that mounts this particular volume can access the above information.Note:There is no specific mechanism to invalidate a token issued via TokenRequest. If you no longer trust a bound service account token for a Pod, you can delete that Pod. Deleting a Pod expires its bound service account tokens.Manual Secret management for ServiceAccountsVersions of Kubernetes before v1.22 automatically created credentials for accessing the Kubernetes API. This older mechanism was based on creating token Secrets that could then be mounted into running Pods.In more recent versions, including Kubernetes v1.34, API credentials are obtained directly using the TokenRequest API, and are mounted into Pods using a projected volume. The tokens obtained using this method have bounded lifetimes, and are automatically invalidated when the Pod they are mounted into is deleted.You can still manually create a Secret to hold a service account token; for example, if you need a token that never expires.Once you manually create a Secret and link it to a ServiceAccount, the Kubernetes control plane automatically populates the token into that Secret.Note:Although the manual mechanism for creating a long-lived ServiceAccount token exists, using TokenRequest to obtain short-lived API access tokens is recommended instead.Auto-generated legacy ServiceAccount token clean upBefore version 1.24, Kubernetes automatically generated Secret-based tokens for ServiceAccounts. To distinguish between automatically generated tokens and manually created ones, Kubernetes checks for a reference from the ServiceAccount's secrets field. If the Secret is referenced in the secrets field, it is considered an auto-generated legacy token. Otherwise, it is considered a manually created legacy token. For example:apiVersion: v1 kind: ServiceAccount metadata: name: build-robot namespace: default secrets: - name: build-robot-secret # usually NOT present for a manually generated token Beginning from version 1.29, legacy ServiceAccount tokens that were generated automatically will be marked as invalid if they remain unused for a certain period of time (set to default at one year). Tokens that continue to be unused for this defined period (again, by default, one year) will subsequently be purged by the control plane.If users use an invalidated auto-generated token, the token validator willadd an audit annotation for the key-value pair authentication.k8s.io/legacy-token-invalidated: <secret name>/<namespace>,increment the invalid_legacy_auto_token_uses_total metric count,update the Secret label kubernetes.io/legacy-token-last-used with the new date,return an error indicating that the token has been invalidated.When receiving this validation error, users can update the Secret to remove the kubernetes.io/legacy-token-invalid-since label to temporarily allow use of this token.Here's an example of an auto-generated legacy token that has been marked with the kubernetes.io/legacy-token-last-used and kubernetes.io/legacy-token-invalid-since labels:apiVersion: v1 kind: Secret metadata: name: build-robot-secret namespace: default labels: kubernetes.io/legacy-token-last-used: 2022-10-24 kubernetes.io/legacy-token-invalid-since: 2023-10-25 annotations: kubernetes.io/service-account.name: build-robot type: kubernetes.io/service-account-token Control plane detailsServiceAccount controllerA ServiceAccount controller manages the ServiceAccounts inside namespaces, and ensures a ServiceAccount named "default" exists in every active namespace.Token controllerThe service account token controller runs as part of kube-controller-manager. This controller acts asynchronously. It:watches for ServiceAccount deletion and deletes all corresponding ServiceAccount token Secrets.watches for ServiceAccount token Secret addition, and ensures the referenced ServiceAccount exists, and adds a token to the Secret if needed.watches for Secret deletion and removes a reference from the corresponding ServiceAccount if needed.You must pass a service account private key file to the token controller in the kube-controller-manager using the --service-account-private-key-file flag. The private key is used to sign generated service account tokens. Similarly, you must pass the corresponding public key to the kube-apiserver using the --service-account-key-file flag. The public key will be used to verify the tokens during authentication.FEATURE STATE: Kubernetes v1.34 [beta] (enabled by default: true)An alternate setup to setting --service-account-private-key-file and --service-account-key-file flags is to configure an external JWT signer for external ServiceAccount token signing and key management. Note that these setups are mutually exclusive and cannot be configured together.ServiceAccount admission controllerThe modification of pods is implemented via a plugin called an Admission Controller. It is part of the API server. This admission controller acts synchronously to modify pods as they are created. When this plugin is active (and it is by default on most distributions), then it does the following when a Pod is created:If the pod does not have a .spec.serviceAccountName set, the admission controller sets the name of the ServiceAccount for this incoming Pod to default.The admission controller ensures that the ServiceAccount referenced by the incoming Pod exists. If there is no ServiceAccount with a matching name, the admission controller rejects the incoming Pod. That check applies even for the default ServiceAccount.Provided that neither the ServiceAccount's automountServiceAccountToken field nor the Pod's automountServiceAccountToken field is set to false:the admission controller mutates the incoming Pod, adding an extra volume that contains a token for API access.the admission controller adds a volumeMount to each container in the Pod, skipping any containers that already have a volume mount defined for the path /var/run/secrets/kubernetes.io/serviceaccount. For Linux containers, that volume is mounted at /var/run/secrets/kubernetes.io/serviceaccount; on Windows nodes, the mount is at the equivalent path.If the spec of the incoming Pod doesn't already contain any imagePullSecrets, then the admission controller adds imagePullSecrets, copying them from the ServiceAccount.Legacy ServiceAccount token tracking controllerFEATURE STATE: Kubernetes v1.28 [stable] (enabled by default: true)This controller generates a ConfigMap called kube-system/kube-apiserver-legacy-service-account-token-tracking in the kube-system namespace. The ConfigMap records the timestamp when legacy service account tokens began to be monitored by the system.Legacy ServiceAccount token cleanerFEATURE STATE: Kubernetes v1.30 [stable] (enabled by default: true)The legacy ServiceAccount token cleaner runs as part of the kube-controller-manager and checks every 24 hours to see if any auto-generated legacy ServiceAccount token has not been used in a specified amount of time. If so, the cleaner marks those tokens as invalid.The cleaner works by first checking the ConfigMap created by the control plane (provided that LegacyServiceAccountTokenTracking is enabled). If the current time is a specified amount of time after the date in the ConfigMap, the cleaner then loops through the list of Secrets in the cluster and evaluates each Secret that has the type kubernetes.io/service-account-token.If a Secret meets all of the following conditions, the cleaner marks it as invalid:The Secret is auto-generated, meaning that it is bi-directionally referenced by a ServiceAccount.The Secret is not currently mounted by any pods.The Secret has not been used in a specified amount of time since it was created or since it was last used.The cleaner marks a Secret invalid by adding a label called kubernetes.io/legacy-token-invalid-since to the Secret, with the current date as the value. If an invalid Secret is not used in a specified amount of time, the cleaner will delete it.Note:All the specified amount of time above defaults to one year. The cluster administrator can configure this value through the --legacy-service-account-token-clean-up-period command line argument for the kube-controller-manager component.TokenRequest APIFEATURE STATE: Kubernetes v1.22 [stable]You use the TokenRequest subresource of a ServiceAccount to obtain a time-bound token for that ServiceAccount. You don't need to call this to obtain an API token for use within a container, since the kubelet sets this up for you using a projected volume.If you want to use the TokenRequest API from kubectl, see Manually create an API token for a ServiceAccount.The Kubernetes control plane (specifically, the ServiceAccount admission controller) adds a projected volume to Pods, and the kubelet ensures that this volume contains a token that lets containers authenticate as the right ServiceAccount.(This mechanism superseded an earlier mechanism that added a volume based on a Secret, where the Secret represented the ServiceAccount for the Pod but did not expire.)Here's an example of how that looks for a launched Pod:... - name: kube-api-access-<random-suffix> projected: defaultMode: 420 # decimal equivalent of octal 0644 sources: - serviceAccountToken: expirationSeconds: 3607 path: token - configMap: items: - key: ca.crt path: ca.crt name: kube-root-ca.crt - downwardAPI: items: - fieldRef: apiVersion: v1 fieldPath: metadata.namespace path: namespace That manifest snippet defines a projected volume that combines information from three sources:A serviceAccountToken source, that contains a token that the kubelet acquires from kube-apiserver. The kubelet fetches time-bound tokens using the TokenRequest API. A token served for a TokenRequest expires either when the pod is deleted or after a defined lifespan (by default, that is 1 hour). The token is bound to the specific Pod and has the kube-apiserver as its audience.A configMap source. The ConfigMap contains a bundle of certificate authority data. Pods can use these certificates to make sure that they are connecting to your cluster's kube-apiserver (and not to a middlebox or an accidentally misconfigured peer).A downwardAPI source. This downwardAPI volume makes the name of the namespace containing the Pod available to application code running inside the Pod.Any container within the Pod that mounts this volume can access the above information.Create additional API tokensCaution:Only create long-lived API tokens if the token request mechanism is not suitable. The token request mechanism provides time-limited tokens; because these expire, they represent a lower risk to information security.To create a non-expiring, persisted API token for a ServiceAccount, create a Secret of type kubernetes.io/service-account-token with an annotation referencing the ServiceAccount. The control plane then generates a long-lived token and updates that Secret with that generated token data.Here is a sample manifest for such a Secret:secret/serviceaccount/mysecretname.yaml apiVersion: v1 kind: Secret type: kubernetes.io/service-account-token metadata: name: mysecretname annotations: kubernetes.io/service-account.name: myserviceaccount To create a Secret based on this example, run:kubectl -n examplens create -f https://k8s.io/examples/secret/serviceaccount/mysecretname.yaml To see the details for that Secret, run:kubectl -n examplens describe secret mysecretname The output is similar to:Name: mysecretname Namespace: examplens Labels: <none> Annotations: kubernetes.io/service-account.name=myserviceaccount kubernetes.io/service-account.uid=8a85c4c4-8483-11e9-bc42-526af7764f64 Type: kubernetes.io/service-account-token Data ==== ca.crt: 1362 bytes namespace: 9 bytes token: ... If you launch a new Pod into the examplens namespace, it can use the myserviceaccount service-account-token Secret that you just created.Caution:Do not reference manually created Secrets in the secrets field of a ServiceAccount. Or the manually created Secrets will be cleaned if it is not used for a long time. Please refer to auto-generated legacy ServiceAccount token clean up.Delete/invalidate a ServiceAccount tokenDelete/invalidate a long-lived/legacy ServiceAccount tokenIf you know the name of the Secret that contains the token you want to remove:kubectl delete secret name-of-secret Otherwise, first find the Secret for the ServiceAccount.# This assumes that you already have a namespace named 'examplens' kubectl -n examplens get serviceaccount/example-automated-thing -o yaml The output is similar to:apiVersion: v1 kind: ServiceAccount metadata: annotations: kubectl.kubernetes.io/last-applied-configuration: | {"apiVersion":"v1","kind":"ServiceAccount","metadata":{"annotations":{},"name":"example-automated-thing","namespace":"examplens"}} creationTimestamp: "2019-07-21T07:07:07Z" name: example-automated-thing namespace: examplens resourceVersion: "777" selfLink: /api/v1/namespaces/examplens/serviceaccounts/example-automated-thing uid: f23fd170-66f2-4697-b049-e1e266b7f835 secrets: - name: example-automated-thing-token-zyxwv Then, delete the Secret you now know the name of:kubectl -n examplens delete secret/example-automated-thing-token-zyxwv Delete/invalidate a short-lived ServiceAccount tokenShort lived ServiceAccount tokens automatically expire after the time-limit specified during their creation. There is no central record of tokens issued, so there is no way to revoke individual tokens.If you have to revoke a short-lived token before its expiration, you can delete and re-create the ServiceAccount it is associated to. This will change its UID and hence invalidate all ServiceAccount tokens that were created for it.External ServiceAccount token signing and key managementFEATURE STATE: Kubernetes v1.34 [beta] (enabled by default: true)The kube-apiserver can be configured to use external signer for token signing and token verifying key management. This feature enables kubernetes distributions to integrate with key management solutions of their choice (for example, HSMs, cloud KMSes) for service account credential signing and verification. To configure kube-apiserver to use external-jwt-signer set the --service-account-signing-endpoint flag to the location of a Unix domain socket (UDS) on a filesystem, or be prefixed with an @ symbol and name a UDS in the abstract socket namespace. At the configured UDS shall be an RPC server which implements an ExternalJWTSigner gRPC service.The external-jwt-signer must be healthy and be ready to serve supported service account keys for the kube-apiserver to start.Note:The kube-apiserver flags --service-account-key-file and --service-account-signing-key-file will continue to be used for reading from files unless --service-account-signing-endpoint is set; they are mutually exclusive ways of supporting JWT signing and authentication.An external signer provides a v1.ExternalJWTSigner gRPC service that implements 3 methods:MetadataMetadata is meant to be called once by kube-apiserver on startup. This enables the external signer to share metadata with kube-apiserver, like the max token lifetime that signer supports.rpc Metadata(MetadataRequest) returns (MetadataResponse) {} message MetadataRequest {} message MetadataResponse { // used by kube-apiserver for defaulting/validation of JWT lifetime while accounting for configuration flag values: // 1. `--service-account-max-token-expiration` // 2. `--service-account-extend-token-expiration` // // * If `--service-account-max-token-expiration` is greater than `max_token_expiration_seconds`, kube-apiserver treats that as misconfiguration and exits. // * If `--service-account-max-token-expiration` is not explicitly set, kube-apiserver defaults to `max_token_expiration_seconds`. // * If `--service-account-extend-token-expiration` is true, the extended expiration is `min(1 year, max_token_expiration_seconds)`. // // `max_token_expiration_seconds` must be at least 600s. int64 max_token_expiration_seconds = 1; } FetchKeysFetchKeys returns the set of public keys that are trusted to sign Kubernetes service account tokens. Kube-apiserver will call this RPC:Every time it tries to validate a JWT from the service account issuer with an unknown key ID, andPeriodically, so it can serve reasonably-up-to-date keys from the OIDC JWKs endpoint.rpc FetchKeys(FetchKeysRequest) returns (FetchKeysResponse) {} message FetchKeysRequest {} message FetchKeysResponse { repeated Key keys = 1; // The timestamp when this data was pulled from the authoritative source of // truth for verification keys. // kube-apiserver can export this from metrics, to enable end-to-end SLOs. google.protobuf.Timestamp data_timestamp = 2; // refresh interval for verification keys to pick changes if any. // any value <= 0 is considered a misconfiguration. int64 refresh_hint_seconds = 3; } message Key { // A unique identifier for this key. // Length must be <=1024. string key_id = 1; // The public key, PKIX-serialized. // must be a public key supported by kube-apiserver (currently RSA 256 or ECDSA 256/384/521) bytes key = 2; // Set only for keys that are not used to sign bound tokens. // eg: supported keys for legacy tokens. // If set, key is used for verification but excluded from OIDC discovery docs. // if set, external signer should not use this key to sign a JWT. bool exclude_from_oidc_discovery = 3; } SignSign takes a serialized JWT payload, and returns the serialized header and signature. kube-apiserver then assembles the JWT from the header, payload, and signature.rpc Sign(SignJWTRequest) returns (SignJWTResponse) {} message SignJWTRequest { // URL-safe base64 wrapped payload to be signed. // Exactly as it appears in the second segment of the JWT string claims = 1; } message SignJWTResponse { // header must contain only alg, kid, typ claims. // typ must be “JWT”. // kid must be non-empty, <=1024 characters, and its corresponding public key should not be excluded from OIDC discovery. // alg must be one of the algorithms supported by kube-apiserver (currently RS256, ES256, ES384, ES512). // header cannot have any additional data that kube-apiserver does not recognize. // Already wrapped in URL-safe base64, exactly as it appears in the first segment of the JWT. string header = 1; // The signature for the JWT. // Already wrapped in URL-safe base64, exactly as it appears in the final segment of the JWT. string signature = 2; } Clean upIf you created a namespace examplens to experiment with, you can remove it:kubectl delete namespace examplens What's nextRead more details about projected volumes.


# Imperative Management of Kubernetes Objects Using Configuration Files

Imperative Management of Kubernetes Objects Using Configuration FilesKubernetes objects can be created, updated, and deleted by using the kubectl command-line tool along with an object configuration file written in YAML or JSON. This document explains how to define and manage objects using configuration files.Before you beginInstall kubectl.You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:iximiuz LabsKillercodaKodeKloudPlay with KubernetesTo check the version, enter kubectl version.Trade-offsThe kubectl tool supports three kinds of object management:Imperative commandsImperative object configurationDeclarative object configurationSee Kubernetes Object Management for a discussion of the advantages and disadvantage of each kind of object management.How to create objectsYou can use kubectl create -f to create an object from a configuration file. Refer to the kubernetes API reference for details.kubectl create -f <filename|url>How to update objectsWarning:Updating objects with the replace command drops all parts of the spec not specified in the configuration file. This should not be used with objects whose specs are partially managed by the cluster, such as Services of type LoadBalancer, where the externalIPs field is managed independently from the configuration file. Independently managed fields must be copied to the configuration file to prevent replace from dropping them.You can use kubectl replace -f to update a live object according to a configuration file.kubectl replace -f <filename|url>How to delete objectsYou can use kubectl delete -f to delete an object that is described in a configuration file.kubectl delete -f <filename|url>Note:If configuration file has specified the generateName field in the metadata section instead of the name field, you cannot delete the object using kubectl delete -f <filename|url>. You will have to use other flags for deleting the object. For example:kubectl delete <type> <name> kubectl delete <type> -l <label> How to view an objectYou can use kubectl get -f to view information about an object that is described in a configuration file.kubectl get -f <filename|url> -o yamlThe -o yaml flag specifies that the full object configuration is printed. Use kubectl get -h to see a list of options.LimitationsThe create, replace, and delete commands work well when each object's configuration is fully defined and recorded in its configuration file. However when a live object is updated, and the updates are not merged into its configuration file, the updates will be lost the next time a replace is executed. This can happen if a controller, such as a HorizontalPodAutoscaler, makes updates directly to a live object. Here's an example:You create an object from a configuration file.Another source updates the object by changing some field.You replace the object from the configuration file. Changes made by the other source in step 2 are lost.If you need to support multiple writers to the same object, you can use kubectl apply to manage the object.Creating and editing an object from a URL without saving the configurationSuppose you have the URL of an object configuration file. You can use kubectl create --edit to make changes to the configuration before the object is created. This is particularly useful for tutorials and tasks that point to a configuration file that could be modified by the reader.kubectl create -f <url> --edit Migrating from imperative commands to imperative object configurationMigrating from imperative commands to imperative object configuration involves several manual steps.Export the live object to a local object configuration file:kubectl get <kind>/<name> -o yaml > <kind>_<name>.yaml Manually remove the status field from the object configuration file.For subsequent object management, use replace exclusively.kubectl replace -f <kind>_<name>.yaml Defining controller selectors and PodTemplate labelsWarning:Updating selectors on controllers is strongly discouraged.The recommended approach is to define a single, immutable PodTemplate label used only by the controller selector with no other semantic meaning.Example label:selector: matchLabels: controller-selector: "apps/v1/deployment/nginx" template: metadata: labels: controller-selector: "apps/v1/deployment/nginx" What's nextManaging Kubernetes Objects Using Imperative CommandsDeclarative Management of Kubernetes Objects Using Configuration FilesKubectl Command ReferenceKubernetes API Reference


# kubectl cordon

kubectl cordonSynopsisMark node as unschedulable.kubectl cordon NODE Examples # Mark node "foo" as unschedulable kubectl cordon foo Options--dry-run string[="unchanged"] Default: "none"Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource.-h, --helphelp for cordon-l, --selector stringSelector (label query) to filter on, supports '=', '==', '!=', 'in', 'notin'.(e.g. -l key1=value1,key2=value2,key3 in (value3)). Matching objects must satisfy all of the specified label constraints.Parent Options Inherited--as stringUsername to impersonate for the operation. User could be a regular user or a service account in a namespace.--as-group stringsGroup to impersonate for the operation, this flag can be repeated to specify multiple groups.--as-uid stringUID to impersonate for the operation.--cache-dir string Default: "$HOME/.kube/cache"Default cache directory--certificate-authority stringPath to a cert file for the certificate authority--client-certificate stringPath to a client certificate file for TLS--client-key stringPath to a client key file for TLS--cluster stringThe name of the kubeconfig cluster to use--context stringThe name of the kubeconfig context to use--disable-compressionIf true, opt-out of response compression for all requests to the server--insecure-skip-tls-verifyIf true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure--kubeconfig stringPath to the kubeconfig file to use for CLI requests.--kuberc stringPath to the kuberc file to use for preferences. This can be disabled by exporting KUBECTL_KUBERC=false feature gate or turning off the feature KUBERC=off.--match-server-versionRequire server version to match client version-n, --namespace stringIf present, the namespace scope for this CLI request--password stringPassword for basic authentication to the API server--profile string Default: "none"Name of profile to capture. One of (none|cpu|heap|goroutine|threadcreate|block|mutex)--profile-output string Default: "profile.pprof"Name of the file to write the profile to--request-timeout string Default: "0"The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests.-s, --server stringThe address and port of the Kubernetes API server--storage-driver-buffer-duration duration Default: 1m0sWrites in the storage driver will be buffered for this duration, and committed to the non memory backends as a single transaction--storage-driver-db string Default: "cadvisor"database name--storage-driver-host string Default: "localhost:8086"database host:port--storage-driver-password string Default: "root"database password--storage-driver-secureuse secure connection with database--storage-driver-table string Default: "stats"table name--storage-driver-user string Default: "root"database username--tls-server-name stringServer name to use for server certificate validation. If it is not provided, the hostname used to contact the server is used--token stringBearer token for authentication to the API server--user stringThe name of the kubeconfig user to use--username stringUsername for basic authentication to the API server--version version[=true]--version, --version=raw prints version information and quits; --version=vX.Y.Z... sets the reported version--warnings-as-errorsTreat warnings received from the server as errors and exit with a non-zero exit codeSee Alsokubectl - kubectl controls the Kubernetes cluster managerThis page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.


# PersistentVolume

PersistentVolumePersistentVolume (PV) is a storage resource provisioned by an administrator.apiVersion: v1import "k8s.io/api/core/v1"PersistentVolumePersistentVolume (PV) is a storage resource provisioned by an administrator. It is analogous to a node. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumesapiVersion: v1kind: PersistentVolumemetadata (ObjectMeta)Standard object's metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#metadataspec (PersistentVolumeSpec)spec defines a specification of a persistent volume owned by the cluster. Provisioned by an administrator. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistent-volumesstatus (PersistentVolumeStatus)status represents the current information/status for the persistent volume. Populated by the system. Read-only. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#persistent-volumesPersistentVolumeSpecPersistentVolumeSpec is the specification of a persistent volume.accessModes ([]string)Atomic: will be replaced during a mergeaccessModes contains all ways the volume can be mounted. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#access-modescapacity (map[string]Quantity)capacity is the description of the persistent volume's resources and capacity. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#capacityclaimRef (ObjectReference)claimRef is part of a bi-directional binding between PersistentVolume and PersistentVolumeClaim. Expected to be non-nil when bound. claim.VolumeName is the authoritative bind between PV and PVC. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#bindingmountOptions ([]string)Atomic: will be replaced during a mergemountOptions is the list of mount options, e.g. ["ro", "soft"]. Not validated - mount will simply fail if one is invalid. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes/#mount-optionsnodeAffinity (VolumeNodeAffinity)nodeAffinity defines constraints that limit what nodes this volume can be accessed from. This field influences the scheduling of pods that use this volume.VolumeNodeAffinity defines constraints that limit what nodes this volume can be accessed from.nodeAffinity.required (NodeSelector)required specifies hard node constraints that must be met.A node selector represents the union of the results of one or more label queries over a set of nodes; that is, it represents the OR of the selectors represented by the node selector terms.nodeAffinity.required.nodeSelectorTerms ([]NodeSelectorTerm), requiredAtomic: will be replaced during a mergeRequired. A list of node selector terms. The terms are ORed.A null or empty node selector term matches no objects. The requirements of them are ANDed. The TopologySelectorTerm type implements a subset of the NodeSelectorTerm.nodeAffinity.required.nodeSelectorTerms.matchExpressions ([]NodeSelectorRequirement)Atomic: will be replaced during a mergeA list of node selector requirements by node's labels.nodeAffinity.required.nodeSelectorTerms.matchFields ([]NodeSelectorRequirement)Atomic: will be replaced during a mergeA list of node selector requirements by node's fields.persistentVolumeReclaimPolicy (string)persistentVolumeReclaimPolicy defines what happens to a persistent volume when released from its claim. Valid options are Retain (default for manually created PersistentVolumes), Delete (default for dynamically provisioned PersistentVolumes), and Recycle (deprecated). Recycle must be supported by the volume plugin underlying this PersistentVolume. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#reclaimingstorageClassName (string)storageClassName is the name of StorageClass to which this persistent volume belongs. Empty value means that this volume does not belong to any StorageClass.volumeAttributesClassName (string)Name of VolumeAttributesClass to which this persistent volume belongs. Empty value is not allowed. When this field is not set, it indicates that this volume does not belong to any VolumeAttributesClass. This field is mutable and can be changed by the CSI driver after a volume has been updated successfully to a new class. For an unbound PersistentVolume, the volumeAttributesClassName will be matched with unbound PersistentVolumeClaims during the binding process.volumeMode (string)volumeMode defines if a volume is intended to be used with a formatted filesystem or to remain in raw block state. Value of Filesystem is implied when not included in spec.LocalhostPath (HostPathVolumeSource)hostPath represents a directory on the host. Provisioned by a developer or tester. This is useful for single-node development and testing only! On-host storage is not supported in any way and WILL NOT WORK in a multi-node cluster. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpathRepresents a host path mapped into a pod. Host path volumes do not support ownership management or SELinux relabeling.hostPath.path (string), requiredpath of the directory on the host. If the path is a symlink, it will follow the link to the real path. More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpathhostPath.type (string)type for HostPath Volume Defaults to "" More info: https://kubernetes.io/docs/concepts/storage/volumes#hostpathlocal (LocalVolumeSource)local represents directly-attached storage with node affinityLocal represents directly-attached storage with node affinitylocal.path (string), requiredpath of the full path to the volume on the node. It can be either a directory or block device (disk, partition, ...).local.fsType (string)fsType is the filesystem type to mount. It applies only when the Path is a block device. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". The default value is to auto-select a filesystem if unspecified.Persistent volumesawsElasticBlockStore (AWSElasticBlockStoreVolumeSource)awsElasticBlockStore represents an AWS Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Deprecated: AWSElasticBlockStore is deprecated. All operations for the in-tree awsElasticBlockStore type are redirected to the ebs.csi.aws.com CSI driver. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstore*Represents a Persistent Disk resource in AWS.An AWS EBS disk must exist before mounting to a container. The disk must also be in the same AWS zone as the kubelet. An AWS EBS disk can only be mounted as read/write once. AWS EBS volumes support ownership management and SELinux relabeling.*awsElasticBlockStore.volumeID (string), requiredvolumeID is unique ID of the persistent disk resource in AWS (Amazon EBS volume). More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstoreawsElasticBlockStore.fsType (string)fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstoreawsElasticBlockStore.partition (int32)partition is the partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as "1". Similarly, the volume partition for /dev/sda is "0" (or you can leave the property empty).awsElasticBlockStore.readOnly (boolean)readOnly value true will force the readOnly setting in VolumeMounts. More info: https://kubernetes.io/docs/concepts/storage/volumes#awselasticblockstoreazureDisk (AzureDiskVolumeSource)azureDisk represents an Azure Data Disk mount on the host and bind mount to the pod. Deprecated: AzureDisk is deprecated. All operations for the in-tree azureDisk type are redirected to the disk.csi.azure.com CSI driver.AzureDisk represents an Azure Data Disk mount on the host and bind mount to the pod.azureDisk.diskName (string), requireddiskName is the Name of the data disk in the blob storageazureDisk.diskURI (string), requireddiskURI is the URI of data disk in the blob storageazureDisk.cachingMode (string)cachingMode is the Host Caching mode: None, Read Only, Read Write.azureDisk.fsType (string)fsType is Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.azureDisk.kind (string)kind expected values are Shared: multiple blob disks per storage account Dedicated: single blob disk per storage account Managed: azure managed data disk (only in managed availability set). defaults to sharedazureDisk.readOnly (boolean)readOnly Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.azureFile (AzureFilePersistentVolumeSource)azureFile represents an Azure File Service mount on the host and bind mount to the pod. Deprecated: AzureFile is deprecated. All operations for the in-tree azureFile type are redirected to the file.csi.azure.com CSI driver.AzureFile represents an Azure File Service mount on the host and bind mount to the pod.azureFile.secretName (string), requiredsecretName is the name of secret that contains Azure Storage Account Name and KeyazureFile.shareName (string), requiredshareName is the azure Share NameazureFile.readOnly (boolean)readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.azureFile.secretNamespace (string)secretNamespace is the namespace of the secret that contains Azure Storage Account Name and Key default is the same as the Podcephfs (CephFSPersistentVolumeSource)cephFS represents a Ceph FS mount on the host that shares a pod's lifetime. Deprecated: CephFS is deprecated and the in-tree cephfs type is no longer supported.Represents a Ceph Filesystem mount that lasts the lifetime of a pod Cephfs volumes do not support ownership management or SELinux relabeling.cephfs.monitors ([]string), requiredAtomic: will be replaced during a mergemonitors is Required: Monitors is a collection of Ceph monitors More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-itcephfs.path (string)path is Optional: Used as the mounted root, rather than the full Ceph tree, default is /cephfs.readOnly (boolean)readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-itcephfs.secretFile (string)secretFile is Optional: SecretFile is the path to key ring for User, default is /etc/ceph/user.secret More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-itcephfs.secretRef (SecretReference)secretRef is Optional: SecretRef is reference to the authentication secret for User, default is empty. More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-itSecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespacecephfs.secretRef.name (string)name is unique within a namespace to reference a secret resource.cephfs.secretRef.namespace (string)namespace defines the space within which the secret name must be unique.cephfs.user (string)user is Optional: User is the rados user name, default is admin More info: https://examples.k8s.io/volumes/cephfs/README.md#how-to-use-itcinder (CinderPersistentVolumeSource)cinder represents a cinder volume attached and mounted on kubelets host machine. Deprecated: Cinder is deprecated. All operations for the in-tree cinder type are redirected to the cinder.csi.openstack.org CSI driver. More info: https://examples.k8s.io/mysql-cinder-pd/README.mdRepresents a cinder volume resource in Openstack. A Cinder volume must exist before mounting to a container. The volume must also be in the same region as the kubelet. Cinder volumes support ownership management and SELinux relabeling.cinder.volumeID (string), requiredvolumeID used to identify the volume in cinder. More info: https://examples.k8s.io/mysql-cinder-pd/README.mdcinder.fsType (string)fsType Filesystem type to mount. Must be a filesystem type supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://examples.k8s.io/mysql-cinder-pd/README.mdcinder.readOnly (boolean)readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts. More info: https://examples.k8s.io/mysql-cinder-pd/README.mdcinder.secretRef (SecretReference)secretRef is Optional: points to a secret object containing parameters used to connect to OpenStack.SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespacecinder.secretRef.name (string)name is unique within a namespace to reference a secret resource.cinder.secretRef.namespace (string)namespace defines the space within which the secret name must be unique.csi (CSIPersistentVolumeSource)csi represents storage that is handled by an external CSI driver.Represents storage that is managed by an external CSI volume drivercsi.driver (string), requireddriver is the name of the driver to use for this volume. Required.csi.volumeHandle (string), requiredvolumeHandle is the unique volume name returned by the CSI volume plugin’s CreateVolume to refer to the volume on all subsequent calls. Required.csi.controllerExpandSecretRef (SecretReference)controllerExpandSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI ControllerExpandVolume call. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespacecsi.controllerExpandSecretRef.name (string)name is unique within a namespace to reference a secret resource.csi.controllerExpandSecretRef.namespace (string)namespace defines the space within which the secret name must be unique.csi.controllerPublishSecretRef (SecretReference)controllerPublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI ControllerPublishVolume and ControllerUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespacecsi.controllerPublishSecretRef.name (string)name is unique within a namespace to reference a secret resource.csi.controllerPublishSecretRef.namespace (string)namespace defines the space within which the secret name must be unique.csi.fsType (string)fsType to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs".csi.nodeExpandSecretRef (SecretReference)nodeExpandSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodeExpandVolume call. This field is optional, may be omitted if no secret is required. If the secret object contains more than one secret, all secrets are passed.SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespacecsi.nodeExpandSecretRef.name (string)name is unique within a namespace to reference a secret resource.csi.nodeExpandSecretRef.namespace (string)namespace defines the space within which the secret name must be unique.csi.nodePublishSecretRef (SecretReference)nodePublishSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodePublishVolume and NodeUnpublishVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespacecsi.nodePublishSecretRef.name (string)name is unique within a namespace to reference a secret resource.csi.nodePublishSecretRef.namespace (string)namespace defines the space within which the secret name must be unique.csi.nodeStageSecretRef (SecretReference)nodeStageSecretRef is a reference to the secret object containing sensitive information to pass to the CSI driver to complete the CSI NodeStageVolume and NodeStageVolume and NodeUnstageVolume calls. This field is optional, and may be empty if no secret is required. If the secret object contains more than one secret, all secrets are passed.SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespacecsi.nodeStageSecretRef.name (string)name is unique within a namespace to reference a secret resource.csi.nodeStageSecretRef.namespace (string)namespace defines the space within which the secret name must be unique.csi.readOnly (boolean)readOnly value to pass to ControllerPublishVolumeRequest. Defaults to false (read/write).csi.volumeAttributes (map[string]string)volumeAttributes of the volume to publish.fc (FCVolumeSource)fc represents a Fibre Channel resource that is attached to a kubelet's host machine and then exposed to the pod.Represents a Fibre Channel volume. Fibre Channel volumes can only be mounted as read/write once. Fibre Channel volumes support ownership management and SELinux relabeling.fc.fsType (string)fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.fc.lun (int32)lun is Optional: FC target lun numberfc.readOnly (boolean)readOnly is Optional: Defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.fc.targetWWNs ([]string)Atomic: will be replaced during a mergetargetWWNs is Optional: FC target worldwide names (WWNs)fc.wwids ([]string)Atomic: will be replaced during a mergewwids Optional: FC volume world wide identifiers (wwids) Either wwids or combination of targetWWNs and lun must be set, but not both simultaneously.flexVolume (FlexPersistentVolumeSource)flexVolume represents a generic volume resource that is provisioned/attached using an exec based plugin. Deprecated: FlexVolume is deprecated. Consider using a CSIDriver instead.FlexPersistentVolumeSource represents a generic persistent volume resource that is provisioned/attached using an exec based plugin.flexVolume.driver (string), requireddriver is the name of the driver to use for this volume.flexVolume.fsType (string)fsType is the Filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". The default filesystem depends on FlexVolume script.flexVolume.options (map[string]string)options is Optional: this field holds extra command options if any.flexVolume.readOnly (boolean)readOnly is Optional: defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.flexVolume.secretRef (SecretReference)secretRef is Optional: SecretRef is reference to the secret object containing sensitive information to pass to the plugin scripts. This may be empty if no secret object is specified. If the secret object contains more than one secret, all secrets are passed to the plugin scripts.SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespaceflexVolume.secretRef.name (string)name is unique within a namespace to reference a secret resource.flexVolume.secretRef.namespace (string)namespace defines the space within which the secret name must be unique.flocker (FlockerVolumeSource)flocker represents a Flocker volume attached to a kubelet's host machine and exposed to the pod for its usage. This depends on the Flocker control service being running. Deprecated: Flocker is deprecated and the in-tree flocker type is no longer supported.Represents a Flocker volume mounted by the Flocker agent. One and only one of datasetName and datasetUUID should be set. Flocker volumes do not support ownership management or SELinux relabeling.flocker.datasetName (string)datasetName is Name of the dataset stored as metadata -> name on the dataset for Flocker should be considered as deprecatedflocker.datasetUUID (string)datasetUUID is the UUID of the dataset. This is unique identifier of a Flocker datasetgcePersistentDisk (GCEPersistentDiskVolumeSource)gcePersistentDisk represents a GCE Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin. Deprecated: GCEPersistentDisk is deprecated. All operations for the in-tree gcePersistentDisk type are redirected to the pd.csi.storage.gke.io CSI driver. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdisk*Represents a Persistent Disk resource in Google Compute Engine.A GCE PD must exist before mounting to a container. The disk must also be in the same GCE project and zone as the kubelet. A GCE PD can only be mounted as read/write once or read-only many times. GCE PDs support ownership management and SELinux relabeling.*gcePersistentDisk.pdName (string), requiredpdName is unique name of the PD resource in GCE. Used to identify the disk in GCE. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdiskgcePersistentDisk.fsType (string)fsType is filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdiskgcePersistentDisk.partition (int32)partition is the partition in the volume that you want to mount. If omitted, the default is to mount by volume name. Examples: For volume /dev/sda1, you specify the partition as "1". Similarly, the volume partition for /dev/sda is "0" (or you can leave the property empty). More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdiskgcePersistentDisk.readOnly (boolean)readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#gcepersistentdiskglusterfs (GlusterfsPersistentVolumeSource)glusterfs represents a Glusterfs volume that is attached to a host and exposed to the pod. Provisioned by an admin. Deprecated: Glusterfs is deprecated and the in-tree glusterfs type is no longer supported. More info: https://examples.k8s.io/volumes/glusterfs/README.mdRepresents a Glusterfs mount that lasts the lifetime of a pod. Glusterfs volumes do not support ownership management or SELinux relabeling.glusterfs.endpoints (string), requiredendpoints is the endpoint name that details Glusterfs topology. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-podglusterfs.path (string), requiredpath is the Glusterfs volume path. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-podglusterfs.endpointsNamespace (string)endpointsNamespace is the namespace that contains Glusterfs endpoint. If this field is empty, the EndpointNamespace defaults to the same namespace as the bound PVC. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-podglusterfs.readOnly (boolean)readOnly here will force the Glusterfs volume to be mounted with read-only permissions. Defaults to false. More info: https://examples.k8s.io/volumes/glusterfs/README.md#create-a-podiscsi (ISCSIPersistentVolumeSource)iscsi represents an ISCSI Disk resource that is attached to a kubelet's host machine and then exposed to the pod. Provisioned by an admin.ISCSIPersistentVolumeSource represents an ISCSI disk. ISCSI volumes can only be mounted as read/write once. ISCSI volumes support ownership management and SELinux relabeling.iscsi.iqn (string), requirediqn is Target iSCSI Qualified Name.iscsi.lun (int32), requiredlun is iSCSI Target Lun number.iscsi.targetPortal (string), requiredtargetPortal is iSCSI Target Portal. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).iscsi.chapAuthDiscovery (boolean)chapAuthDiscovery defines whether support iSCSI Discovery CHAP authenticationiscsi.chapAuthSession (boolean)chapAuthSession defines whether support iSCSI Session CHAP authenticationiscsi.fsType (string)fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#iscsiiscsi.initiatorName (string)initiatorName is the custom iSCSI Initiator Name. If initiatorName is specified with iscsiInterface simultaneously, new iSCSI interface <target portal>:<volume name> will be created for the connection.iscsi.iscsiInterface (string)iscsiInterface is the interface Name that uses an iSCSI transport. Defaults to 'default' (tcp).iscsi.portals ([]string)Atomic: will be replaced during a mergeportals is the iSCSI Target Portal List. The Portal is either an IP or ip_addr:port if the port is other than default (typically TCP ports 860 and 3260).iscsi.readOnly (boolean)readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false.iscsi.secretRef (SecretReference)secretRef is the CHAP Secret for iSCSI target and initiator authenticationSecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespaceiscsi.secretRef.name (string)name is unique within a namespace to reference a secret resource.iscsi.secretRef.namespace (string)namespace defines the space within which the secret name must be unique.nfs (NFSVolumeSource)nfs represents an NFS mount on the host. Provisioned by an admin. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfsRepresents an NFS mount that lasts the lifetime of a pod. NFS volumes do not support ownership management or SELinux relabeling.nfs.path (string), requiredpath that is exported by the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfsnfs.server (string), requiredserver is the hostname or IP address of the NFS server. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfsnfs.readOnly (boolean)readOnly here will force the NFS export to be mounted with read-only permissions. Defaults to false. More info: https://kubernetes.io/docs/concepts/storage/volumes#nfsphotonPersistentDisk (PhotonPersistentDiskVolumeSource)photonPersistentDisk represents a PhotonController persistent disk attached and mounted on kubelets host machine. Deprecated: PhotonPersistentDisk is deprecated and the in-tree photonPersistentDisk type is no longer supported.Represents a Photon Controller persistent disk resource.photonPersistentDisk.pdID (string), requiredpdID is the ID that identifies Photon Controller persistent diskphotonPersistentDisk.fsType (string)fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.portworxVolume (PortworxVolumeSource)portworxVolume represents a portworx volume attached and mounted on kubelets host machine. Deprecated: PortworxVolume is deprecated. All operations for the in-tree portworxVolume type are redirected to the pxd.portworx.com CSI driver when the CSIMigrationPortworx feature-gate is on.PortworxVolumeSource represents a Portworx volume resource.portworxVolume.volumeID (string), requiredvolumeID uniquely identifies a Portworx volumeportworxVolume.fsType (string)fSType represents the filesystem type to mount Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs". Implicitly inferred to be "ext4" if unspecified.portworxVolume.readOnly (boolean)readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.quobyte (QuobyteVolumeSource)quobyte represents a Quobyte mount on the host that shares a pod's lifetime. Deprecated: Quobyte is deprecated and the in-tree quobyte type is no longer supported.Represents a Quobyte mount that lasts the lifetime of a pod. Quobyte volumes do not support ownership management or SELinux relabeling.quobyte.registry (string), requiredregistry represents a single or multiple Quobyte Registry services specified as a string as host:port pair (multiple entries are separated with commas) which acts as the central registry for volumesquobyte.volume (string), requiredvolume is a string that references an already created Quobyte volume by name.quobyte.group (string)group to map volume access to Default is no groupquobyte.readOnly (boolean)readOnly here will force the Quobyte volume to be mounted with read-only permissions. Defaults to false.quobyte.tenant (string)tenant owning the given Quobyte volume in the Backend Used with dynamically provisioned Quobyte volumes, value is set by the pluginquobyte.user (string)user to map volume access to Defaults to serivceaccount userrbd (RBDPersistentVolumeSource)rbd represents a Rados Block Device mount on the host that shares a pod's lifetime. Deprecated: RBD is deprecated and the in-tree rbd type is no longer supported. More info: https://examples.k8s.io/volumes/rbd/README.mdRepresents a Rados Block Device mount that lasts the lifetime of a pod. RBD volumes support ownership management and SELinux relabeling.rbd.image (string), requiredimage is the rados image name. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-itrbd.monitors ([]string), requiredAtomic: will be replaced during a mergemonitors is a collection of Ceph monitors. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-itrbd.fsType (string)fsType is the filesystem type of the volume that you want to mount. Tip: Ensure that the filesystem type is supported by the host operating system. Examples: "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified. More info: https://kubernetes.io/docs/concepts/storage/volumes#rbdrbd.keyring (string)keyring is the path to key ring for RBDUser. Default is /etc/ceph/keyring. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-itrbd.pool (string)pool is the rados pool name. Default is rbd. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-itrbd.readOnly (boolean)readOnly here will force the ReadOnly setting in VolumeMounts. Defaults to false. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-itrbd.secretRef (SecretReference)secretRef is name of the authentication secret for RBDUser. If provided overrides keyring. Default is nil. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-itSecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespacerbd.secretRef.name (string)name is unique within a namespace to reference a secret resource.rbd.secretRef.namespace (string)namespace defines the space within which the secret name must be unique.rbd.user (string)user is the rados user name. Default is admin. More info: https://examples.k8s.io/volumes/rbd/README.md#how-to-use-itscaleIO (ScaleIOPersistentVolumeSource)scaleIO represents a ScaleIO persistent volume attached and mounted on Kubernetes nodes. Deprecated: ScaleIO is deprecated and the in-tree scaleIO type is no longer supported.ScaleIOPersistentVolumeSource represents a persistent ScaleIO volumescaleIO.gateway (string), requiredgateway is the host address of the ScaleIO API Gateway.scaleIO.secretRef (SecretReference), requiredsecretRef references to the secret for ScaleIO user and other sensitive information. If this is not provided, Login operation will fail.SecretReference represents a Secret Reference. It has enough information to retrieve secret in any namespacescaleIO.secretRef.name (string)name is unique within a namespace to reference a secret resource.scaleIO.secretRef.namespace (string)namespace defines the space within which the secret name must be unique.scaleIO.system (string), requiredsystem is the name of the storage system as configured in ScaleIO.scaleIO.fsType (string)fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Default is "xfs"scaleIO.protectionDomain (string)protectionDomain is the name of the ScaleIO Protection Domain for the configured storage.scaleIO.readOnly (boolean)readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.scaleIO.sslEnabled (boolean)sslEnabled is the flag to enable/disable SSL communication with Gateway, default falsescaleIO.storageMode (string)storageMode indicates whether the storage for a volume should be ThickProvisioned or ThinProvisioned. Default is ThinProvisioned.scaleIO.storagePool (string)storagePool is the ScaleIO Storage Pool associated with the protection domain.scaleIO.volumeName (string)volumeName is the name of a volume already created in the ScaleIO system that is associated with this volume source.storageos (StorageOSPersistentVolumeSource)storageOS represents a StorageOS volume that is attached to the kubelet's host machine and mounted into the pod. Deprecated: StorageOS is deprecated and the in-tree storageos type is no longer supported. More info: https://examples.k8s.io/volumes/storageos/README.mdRepresents a StorageOS persistent volume resource.storageos.fsType (string)fsType is the filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.storageos.readOnly (boolean)readOnly defaults to false (read/write). ReadOnly here will force the ReadOnly setting in VolumeMounts.storageos.secretRef (ObjectReference)secretRef specifies the secret to use for obtaining the StorageOS API credentials. If not specified, default values will be attempted.storageos.volumeName (string)volumeName is the human-readable name of the StorageOS volume. Volume names are only unique within a namespace.storageos.volumeNamespace (string)volumeNamespace specifies the scope of the volume within StorageOS. If no namespace is specified then the Pod's namespace will be used. This allows the Kubernetes name scoping to be mirrored within StorageOS for tighter integration. Set VolumeName to any name to override the default behaviour. Set to "default" if you are not using namespaces within StorageOS. Namespaces that do not pre-exist within StorageOS will be created.vsphereVolume (VsphereVirtualDiskVolumeSource)vsphereVolume represents a vSphere volume attached and mounted on kubelets host machine. Deprecated: VsphereVolume is deprecated. All operations for the in-tree vsphereVolume type are redirected to the csi.vsphere.vmware.com CSI driver.Represents a vSphere volume resource.vsphereVolume.volumePath (string), requiredvolumePath is the path that identifies vSphere volume vmdkvsphereVolume.fsType (string)fsType is filesystem type to mount. Must be a filesystem type supported by the host operating system. Ex. "ext4", "xfs", "ntfs". Implicitly inferred to be "ext4" if unspecified.vsphereVolume.storagePolicyID (string)storagePolicyID is the storage Policy Based Management (SPBM) profile ID associated with the StoragePolicyName.vsphereVolume.storagePolicyName (string)storagePolicyName is the storage Policy Based Management (SPBM) profile name.PersistentVolumeStatusPersistentVolumeStatus is the current status of a persistent volume.lastPhaseTransitionTime (Time)lastPhaseTransitionTime is the time the phase transitioned from one to another and automatically resets to current time everytime a volume phase transitions.Time is a wrapper around time.Time which supports correct marshaling to YAML and JSON. Wrappers are provided for many of the factory methods that the time package offers.message (string)message is a human-readable message indicating details about why the volume is in this state.phase (string)phase indicates if a volume is available, bound to a claim, or released by a claim. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumes#phasereason (string)reason is a brief CamelCase string that describes any failure and is meant for machine parsing and tidy display in the CLI.PersistentVolumeListPersistentVolumeList is a list of PersistentVolume items.apiVersion: v1kind: PersistentVolumeListmetadata (ListMeta)Standard list metadata. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kindsitems ([]PersistentVolume), requireditems is a list of persistent volumes. More info: https://kubernetes.io/docs/concepts/storage/persistent-volumesOperationsget read the specified PersistentVolumeHTTP RequestGET /api/v1/persistentvolumes/{name}Parametersname (in path): string, requiredname of the PersistentVolumepretty (in query): stringprettyResponse200 (PersistentVolume): OK401: Unauthorizedget read status of the specified PersistentVolumeHTTP RequestGET /api/v1/persistentvolumes/{name}/statusParametersname (in path): string, requiredname of the PersistentVolumepretty (in query): stringprettyResponse200 (PersistentVolume): OK401: Unauthorizedlist list or watch objects of kind PersistentVolumeHTTP RequestGET /api/v1/persistentvolumesParametersallowWatchBookmarks (in query): booleanallowWatchBookmarkscontinue (in query): stringcontinuefieldSelector (in query): stringfieldSelectorlabelSelector (in query): stringlabelSelectorlimit (in query): integerlimitpretty (in query): stringprettyresourceVersion (in query): stringresourceVersionresourceVersionMatch (in query): stringresourceVersionMatchsendInitialEvents (in query): booleansendInitialEventstimeoutSeconds (in query): integertimeoutSecondswatch (in query): booleanwatchResponse200 (PersistentVolumeList): OK401: Unauthorizedcreate create a PersistentVolumeHTTP RequestPOST /api/v1/persistentvolumesParametersbody: PersistentVolume, requireddryRun (in query): stringdryRunfieldManager (in query): stringfieldManagerfieldValidation (in query): stringfieldValidationpretty (in query): stringprettyResponse200 (PersistentVolume): OK201 (PersistentVolume): Created202 (PersistentVolume): Accepted401: Unauthorizedupdate replace the specified PersistentVolumeHTTP RequestPUT /api/v1/persistentvolumes/{name}Parametersname (in path): string, requiredname of the PersistentVolumebody: PersistentVolume, requireddryRun (in query): stringdryRunfieldManager (in query): stringfieldManagerfieldValidation (in query): stringfieldValidationpretty (in query): stringprettyResponse200 (PersistentVolume): OK201 (PersistentVolume): Created401: Unauthorizedupdate replace status of the specified PersistentVolumeHTTP RequestPUT /api/v1/persistentvolumes/{name}/statusParametersname (in path): string, requiredname of the PersistentVolumebody: PersistentVolume, requireddryRun (in query): stringdryRunfieldManager (in query): stringfieldManagerfieldValidation (in query): stringfieldValidationpretty (in query): stringprettyResponse200 (PersistentVolume): OK201 (PersistentVolume): Created401: Unauthorizedpatch partially update the specified PersistentVolumeHTTP RequestPATCH /api/v1/persistentvolumes/{name}Parametersname (in path): string, requiredname of the PersistentVolumebody: Patch, requireddryRun (in query): stringdryRunfieldManager (in query): stringfieldManagerfieldValidation (in query): stringfieldValidationforce (in query): booleanforcepretty (in query): stringprettyResponse200 (PersistentVolume): OK201 (PersistentVolume): Created401: Unauthorizedpatch partially update status of the specified PersistentVolumeHTTP RequestPATCH /api/v1/persistentvolumes/{name}/statusParametersname (in path): string, requiredname of the PersistentVolumebody: Patch, requireddryRun (in query): stringdryRunfieldManager (in query): stringfieldManagerfieldValidation (in query): stringfieldValidationforce (in query): booleanforcepretty (in query): stringprettyResponse200 (PersistentVolume): OK201 (PersistentVolume): Created401: Unauthorizeddelete delete a PersistentVolumeHTTP RequestDELETE /api/v1/persistentvolumes/{name}Parametersname (in path): string, requiredname of the PersistentVolumebody: DeleteOptionsdryRun (in query): stringdryRungracePeriodSeconds (in query): integergracePeriodSecondsignoreStoreReadErrorWithClusterBreakingPotential (in query): booleanignoreStoreReadErrorWithClusterBreakingPotentialpretty (in query): stringprettypropagationPolicy (in query): stringpropagationPolicyResponse200 (PersistentVolume): OK202 (PersistentVolume): Accepted401: Unauthorizeddeletecollection delete collection of PersistentVolumeHTTP RequestDELETE /api/v1/persistentvolumesParametersbody: DeleteOptionscontinue (in query): stringcontinuedryRun (in query): stringdryRunfieldSelector (in query): stringfieldSelectorgracePeriodSeconds (in query): integergracePeriodSecondsignoreStoreReadErrorWithClusterBreakingPotential (in query): booleanignoreStoreReadErrorWithClusterBreakingPotentiallabelSelector (in query): stringlabelSelectorlimit (in query): integerlimitpretty (in query): stringprettypropagationPolicy (in query): stringpropagationPolicyresourceVersion (in query): stringresourceVersionresourceVersionMatch (in query): stringresourceVersionMatchsendInitialEvents (in query): booleansendInitialEventstimeoutSeconds (in query): integertimeoutSecondsResponse200 (Status): OK401: UnauthorizedThis page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.


# kubectl create secret generic

kubectl create secret genericSynopsisCreate a secret based on a file, directory, or specified literal value.A single secret may package one or more key/value pairs.When creating a secret based on a file, the key will default to the basename of the file, and the value will default to the file content. If the basename is an invalid key or you wish to chose your own, you may specify an alternate key.When creating a secret based on a directory, each file whose basename is a valid key in the directory will be packaged into the secret. Any directory entries except regular files are ignored (e.g. subdirectories, symlinks, devices, pipes, etc).kubectl create secret generic NAME [--type=string] [--from-file=[key=]source] [--from-literal=key1=value1] [--dry-run=server|client|none] Examples # Create a new secret named my-secret with keys for each file in folder bar kubectl create secret generic my-secret --from-file=path/to/bar # Create a new secret named my-secret with specified keys instead of names on disk kubectl create secret generic my-secret --from-file=ssh-privatekey=path/to/id_rsa --from-file=ssh-publickey=path/to/id_rsa.pub # Create a new secret named my-secret with key1=supersecret and key2=topsecret kubectl create secret generic my-secret --from-literal=key1=supersecret --from-literal=key2=topsecret # Create a new secret named my-secret using a combination of a file and a literal kubectl create secret generic my-secret --from-file=ssh-privatekey=path/to/id_rsa --from-literal=passphrase=topsecret # Create a new secret named my-secret from env files kubectl create secret generic my-secret --from-env-file=path/to/foo.env --from-env-file=path/to/bar.env Options--allow-missing-template-keys Default: trueIf true, ignore any errors in templates when a field or map key is missing in the template. Only applies to golang and jsonpath output formats.--append-hashAppend a hash of the secret to its name.--dry-run string[="unchanged"] Default: "none"Must be "none", "server", or "client". If client strategy, only print the object that would be sent, without sending it. If server strategy, submit server-side request without persisting the resource.--field-manager string Default: "kubectl-create"Name of the manager used to track field ownership.--from-env-file stringsSpecify the path to a file to read lines of key=val pairs to create a secret.--from-file stringsKey files can be specified using their file path, in which case a default name will be given to them, or optionally with a name and file path, in which case the given name will be used. Specifying a directory will iterate each named file in the directory that is a valid secret key.--from-literal stringsSpecify a key and literal value to insert in secret (i.e. mykey=somevalue)-h, --helphelp for generic-o, --output stringOutput format. One of: (json, yaml, name, go-template, go-template-file, template, templatefile, jsonpath, jsonpath-as-json, jsonpath-file).--save-configIf true, the configuration of current object will be saved in its annotation. Otherwise, the annotation will be unchanged. This flag is useful when you want to perform kubectl apply on this object in the future.--show-managed-fieldsIf true, keep the managedFields when printing objects in JSON or YAML format.--template stringTemplate string or path to template file to use when -o=go-template, -o=go-template-file. The template format is golang templates [http://golang.org/pkg/text/template/#pkg-overview].--type stringThe type of secret to create--validate string[="strict"] Default: "strict"Must be one of: strict (or true), warn, ignore (or false). "true" or "strict" will use a schema to validate the input and fail the request if invalid. It will perform server side validation if ServerSideFieldValidation is enabled on the api-server, but will fall back to less reliable client-side validation if not. "warn" will warn about unknown or duplicate fields without blocking the request if server-side field validation is enabled on the API server, and behave as "ignore" otherwise. "false" or "ignore" will not perform any schema validation, silently dropping any unknown or duplicate fields.Parent Options Inherited--as stringUsername to impersonate for the operation. User could be a regular user or a service account in a namespace.--as-group stringsGroup to impersonate for the operation, this flag can be repeated to specify multiple groups.--as-uid stringUID to impersonate for the operation.--cache-dir string Default: "$HOME/.kube/cache"Default cache directory--certificate-authority stringPath to a cert file for the certificate authority--client-certificate stringPath to a client certificate file for TLS--client-key stringPath to a client key file for TLS--cluster stringThe name of the kubeconfig cluster to use--context stringThe name of the kubeconfig context to use--disable-compressionIf true, opt-out of response compression for all requests to the server--insecure-skip-tls-verifyIf true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure--kubeconfig stringPath to the kubeconfig file to use for CLI requests.--kuberc stringPath to the kuberc file to use for preferences. This can be disabled by exporting KUBECTL_KUBERC=false feature gate or turning off the feature KUBERC=off.--match-server-versionRequire server version to match client version-n, --namespace stringIf present, the namespace scope for this CLI request--password stringPassword for basic authentication to the API server--profile string Default: "none"Name of profile to capture. One of (none|cpu|heap|goroutine|threadcreate|block|mutex)--profile-output string Default: "profile.pprof"Name of the file to write the profile to--request-timeout string Default: "0"The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests.-s, --server stringThe address and port of the Kubernetes API server--storage-driver-buffer-duration duration Default: 1m0sWrites in the storage driver will be buffered for this duration, and committed to the non memory backends as a single transaction--storage-driver-db string Default: "cadvisor"database name--storage-driver-host string Default: "localhost:8086"database host:port--storage-driver-password string Default: "root"database password--storage-driver-secureuse secure connection with database--storage-driver-table string Default: "stats"table name--storage-driver-user string Default: "root"database username--tls-server-name stringServer name to use for server certificate validation. If it is not provided, the hostname used to contact the server is used--token stringBearer token for authentication to the API server--user stringThe name of the kubeconfig user to use--username stringUsername for basic authentication to the API server--version version[=true]--version, --version=raw prints version information and quits; --version=vX.Y.Z... sets the reported version--warnings-as-errorsTreat warnings received from the server as errors and exit with a non-zero exit codeSee Alsokubectl create secret - Create a secret using a specified subcommandThis page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.


# Container Lifecycle Hooks

Container Lifecycle HooksThis page describes how kubelet managed Containers can use the Container lifecycle hook framework to run code triggered by events during their management lifecycle.OverviewAnalogous to many programming language frameworks that have component lifecycle hooks, such as Angular, Kubernetes provides Containers with lifecycle hooks. The hooks enable Containers to be aware of events in their management lifecycle and run code implemented in a handler when the corresponding lifecycle hook is executed.Container hooksThere are two hooks that are exposed to Containers:PostStartThis hook is executed immediately after a container is created. However, there is no guarantee that the hook will execute before the container ENTRYPOINT. No parameters are passed to the handler.PreStopThis hook is called immediately before a container is terminated due to an API request or management event such as a liveness/startup probe failure, preemption, resource contention and others. A call to the PreStop hook fails if the container is already in a terminated or completed state and the hook must complete before the TERM signal to stop the container can be sent. The Pod's termination grace period countdown begins before the PreStop hook is executed, so regardless of the outcome of the handler, the container will eventually terminate within the Pod's termination grace period. No parameters are passed to the handler.A more detailed description of the termination behavior can be found in Termination of Pods.StopSignalThe StopSignal lifecycle can be used to define a stop signal which would be sent to the container when it is stopped. If you set this, it overrides any STOPSIGNAL instruction defined within the container image.A more detailed description of termination behaviour with custom stop signals can be found in Stop Signals.Hook handler implementationsContainers can access a hook by implementing and registering a handler for that hook. There are three types of hook handlers that can be implemented for Containers:Exec - Executes a specific command, such as pre-stop.sh, inside the cgroups and namespaces of the Container. Resources consumed by the command are counted against the Container.HTTP - Executes an HTTP request against a specific endpoint on the Container.Sleep - Pauses the container for a specified duration.Hook handler executionWhen a Container lifecycle management hook is called, the Kubernetes management system executes the handler according to the hook action, httpGet, tcpSocket (deprecated) and sleep are executed by the kubelet process, and exec is executed in the container.The PostStart hook handler call is initiated when a container is created, meaning the container ENTRYPOINT and the PostStart hook are triggered simultaneously. However, if the PostStart hook takes too long to execute or if it hangs, it can prevent the container from transitioning to a running state.PreStop hooks are not executed asynchronously from the signal to stop the Container; the hook must complete its execution before the TERM signal can be sent. If a PreStop hook hangs during execution, the Pod's phase will be Terminating and remain there until the Pod is killed after its terminationGracePeriodSeconds expires. This grace period applies to the total time it takes for both the PreStop hook to execute and for the Container to stop normally. If, for example, terminationGracePeriodSeconds is 60, and the hook takes 55 seconds to complete, and the Container takes 10 seconds to stop normally after receiving the signal, then the Container will be killed before it can stop normally, since terminationGracePeriodSeconds is less than the total time (55+10) it takes for these two things to happen.If either a PostStart or PreStop hook fails, it kills the Container.Users should make their hook handlers as lightweight as possible. There are cases, however, when long running commands make sense, such as when saving state prior to stopping a Container.Hook delivery guaranteesHook delivery is intended to be at least once, which means that a hook may be called multiple times for any given event, such as for PostStart or PreStop. It is up to the hook implementation to handle this correctly.Generally, only single deliveries are made. If, for example, an HTTP hook receiver is down and is unable to take traffic, there is no attempt to resend. In some rare cases, however, double delivery may occur. For instance, if a kubelet restarts in the middle of sending a hook, the hook might be resent after the kubelet comes back up.Debugging Hook handlersThe logs for a Hook handler are not exposed in Pod events. If a handler fails for some reason, it broadcasts an event. For PostStart, this is the FailedPostStartHook event, and for PreStop, this is the FailedPreStopHook event. To generate a failed FailedPostStartHook event yourself, modify the lifecycle-events.yaml file to change the postStart command to "badcommand" and apply it. Here is some example output of the resulting events you see from running kubectl describe pod lifecycle-demo:Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 7s default-scheduler Successfully assigned default/lifecycle-demo to ip-XXX-XXX-XX-XX.us-east-2... Normal Pulled 6s kubelet Successfully pulled image "nginx" in 229.604315ms Normal Pulling 4s (x2 over 6s) kubelet Pulling image "nginx" Normal Created 4s (x2 over 5s) kubelet Created container lifecycle-demo-container Normal Started 4s (x2 over 5s) kubelet Started container lifecycle-demo-container Warning FailedPostStartHook 4s (x2 over 5s) kubelet Exec lifecycle hook ([badcommand]) for Container "lifecycle-demo-container" in Pod "lifecycle-demo_default(30229739-9651-4e5a-9a32-a8f1688862db)" failed - error: command 'badcommand' exited with 126: , message: "OCI runtime exec failed: exec failed: container_linux.go:380: starting container process caused: exec: \"badcommand\": executable file not found in $PATH: unknown\r\n" Normal Killing 4s (x2 over 5s) kubelet FailedPostStartHook Normal Pulled 4s kubelet Successfully pulled image "nginx" in 215.66395ms Warning BackOff 2s (x2 over 3s) kubelet Back-off restarting failed container What's nextLearn more about the Container environment.Get hands-on experience attaching handlers to Container lifecycle events.


# kubectl exec

kubectl execSynopsisExecute a command in a container.kubectl exec (POD | TYPE/NAME) [-c CONTAINER] [flags] -- COMMAND [args...] Examples # Get output from running the 'date' command from pod mypod, using the first container by default kubectl exec mypod -- date # Get output from running the 'date' command in ruby-container from pod mypod kubectl exec mypod -c ruby-container -- date # Switch to raw terminal mode; sends stdin to 'bash' in ruby-container from pod mypod # and sends stdout/stderr from 'bash' back to the client kubectl exec mypod -c ruby-container -i -t -- bash -il # List contents of /usr from the first container of pod mypod and sort by modification time # If the command you want to execute in the pod has any flags in common (e.g. -i), # you must use two dashes (--) to separate your command's flags/arguments # Also note, do not surround your command and its flags/arguments with quotes # unless that is how you would execute it normally (i.e., do ls -t /usr, not "ls -t /usr") kubectl exec mypod -i -t -- ls -t /usr # Get output from running 'date' command from the first pod of the deployment mydeployment, using the first container by default kubectl exec deploy/mydeployment -- date # Get output from running 'date' command from the first pod of the service myservice, using the first container by default kubectl exec svc/myservice -- date Options-c, --container stringContainer name. If omitted, use the kubectl.kubernetes.io/default-container annotation for selecting the container to be attached or the first container in the pod will be chosen-f, --filename stringsto use to exec into the resource-h, --helphelp for exec--pod-running-timeout duration Default: 1m0sThe length of time (like 5s, 2m, or 3h, higher than zero) to wait until at least one pod is running-q, --quietOnly print output from the remote session-i, --stdinPass stdin to the container-t, --ttyStdin is a TTYParent Options Inherited--as stringUsername to impersonate for the operation. User could be a regular user or a service account in a namespace.--as-group stringsGroup to impersonate for the operation, this flag can be repeated to specify multiple groups.--as-uid stringUID to impersonate for the operation.--cache-dir string Default: "$HOME/.kube/cache"Default cache directory--certificate-authority stringPath to a cert file for the certificate authority--client-certificate stringPath to a client certificate file for TLS--client-key stringPath to a client key file for TLS--cluster stringThe name of the kubeconfig cluster to use--context stringThe name of the kubeconfig context to use--disable-compressionIf true, opt-out of response compression for all requests to the server--insecure-skip-tls-verifyIf true, the server's certificate will not be checked for validity. This will make your HTTPS connections insecure--kubeconfig stringPath to the kubeconfig file to use for CLI requests.--kuberc stringPath to the kuberc file to use for preferences. This can be disabled by exporting KUBECTL_KUBERC=false feature gate or turning off the feature KUBERC=off.--match-server-versionRequire server version to match client version-n, --namespace stringIf present, the namespace scope for this CLI request--password stringPassword for basic authentication to the API server--profile string Default: "none"Name of profile to capture. One of (none|cpu|heap|goroutine|threadcreate|block|mutex)--profile-output string Default: "profile.pprof"Name of the file to write the profile to--request-timeout string Default: "0"The length of time to wait before giving up on a single server request. Non-zero values should contain a corresponding time unit (e.g. 1s, 2m, 3h). A value of zero means don't timeout requests.-s, --server stringThe address and port of the Kubernetes API server--storage-driver-buffer-duration duration Default: 1m0sWrites in the storage driver will be buffered for this duration, and committed to the non memory backends as a single transaction--storage-driver-db string Default: "cadvisor"database name--storage-driver-host string Default: "localhost:8086"database host:port--storage-driver-password string Default: "root"database password--storage-driver-secureuse secure connection with database--storage-driver-table string Default: "stats"table name--storage-driver-user string Default: "root"database username--tls-server-name stringServer name to use for server certificate validation. If it is not provided, the hostname used to contact the server is used--token stringBearer token for authentication to the API server--user stringThe name of the kubeconfig user to use--username stringUsername for basic authentication to the API server--version version[=true]--version, --version=raw prints version information and quits; --version=vX.Y.Z... sets the reported version--warnings-as-errorsTreat warnings received from the server as errors and exit with a non-zero exit codeSee Alsokubectl - kubectl controls the Kubernetes cluster managerThis page is automatically generated.If you plan to report an issue with this page, mention that the page is auto-generated in your issue description. The fix may need to happen elsewhere in the Kubernetes project.