Merge branch 'kubernetes:main' into update-assign-pod-node

pull/38800/head
ziyi-xie 2023-03-10 16:03:40 +09:00 committed by GitHub
commit 1a3ff55b9a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
125 changed files with 3711 additions and 1299 deletions

View File

@ -70,7 +70,7 @@ This will start the local Hugo server on port 1313. Open up your browser to <htt
## Building the API reference pages
The API reference pages located in `content/en/docs/reference/kubernetes-api` are built from the Swagger specification, using <https://github.com/kubernetes-sigs/reference-docs/tree/master/gen-resourcesdocs>.
The API reference pages located in `content/en/docs/reference/kubernetes-api` are built from the Swagger specification, also known as OpenAPI specification, using <https://github.com/kubernetes-sigs/reference-docs/tree/master/gen-resourcesdocs>.
To update the reference pages for a new Kubernetes release follow these steps:

View File

@ -33,7 +33,7 @@ General Availability means different things for different projects. For kubeadm,
We now consider kubeadm to have achieved GA-level maturity in each of these important domains:
* **Stable command-line UX** --- The kubeadm CLI conforms to [#5a GA rule of the Kubernetes Deprecation Policy](/docs/reference/using-api/deprecation-policy/#deprecating-a-flag-or-cli), which states that a command or flag that exists in a GA version must be kept for at least 12 months after deprecation.
* **Stable underlying implementation** --- kubeadm now creates a new Kubernetes cluster using methods that shouldn't change any time soon. The control plane, for example, is run as a set of static Pods, bootstrap tokens are used for the [`kubeadm join`](/docs/reference/setup-tools/kubeadm/kubeadm-join/) flow, and [ComponentConfig](https://github.com/kubernetes/enhancements/blob/master/keps/sig-cluster-lifecycle/wgs/0014-20180707-componentconfig-api-types-to-staging.md) is used for configuring the [kubelet](/docs/reference/command-line-tools-reference/kubelet/).
* **Stable underlying implementation** --- kubeadm now creates a new Kubernetes cluster using methods that shouldn't change any time soon. The control plane, for example, is run as a set of static Pods, bootstrap tokens are used for the [`kubeadm join`](/docs/reference/setup-tools/kubeadm/kubeadm-join/) flow, and [ComponentConfig](https://github.com/kubernetes/enhancements/blob/master/keps/sig-cluster-lifecycle/wgs/115-componentconfig) is used for configuring the [kubelet](/docs/reference/command-line-tools-reference/kubelet/).
* **Configuration file schema** --- With the new **v1beta1** API version, you can now tune almost every part of the cluster declaratively and thus build a "GitOps" flow around kubeadm-built clusters. In future versions, we plan to graduate the API to version **v1** with minimal changes (and perhaps none).
* **The "toolbox" interface of kubeadm** --- Also known as **phases**. If you don't want to perform all [`kubeadm init`](/docs/reference/setup-tools/kubeadm/kubeadm-init/) tasks, you can instead apply more fine-grained actions using the `kubeadm init phase` command (for example generating certificates or control plane [Static Pod](/docs/tasks/administer-cluster/static-pod/) manifests).
* **Upgrades between minor versions** --- The [`kubeadm upgrade`](/docs/reference/setup-tools/kubeadm/kubeadm-upgrade/) command is now fully GA. It handles control plane upgrades for you, which includes upgrades to [etcd](https://etcd.io), the [API Server](/docs/reference/using-api/api-overview/), the [Controller Manager](/docs/reference/command-line-tools-reference/kube-controller-manager/), and the [Scheduler](/docs/reference/command-line-tools-reference/kube-scheduler/). You can seamlessly upgrade your cluster between minor or patch versions (e.g. v1.12.2 -> v1.13.1 or v1.13.1 -> v1.13.3).

View File

@ -207,3 +207,11 @@ and without losing the state of the containers in that Pod.
You can reach SIG Node by several means:
- Slack: [#sig-node](https://kubernetes.slack.com/messages/sig-node)
- [Mailing list](https://groups.google.com/forum/#!forum/kubernetes-sig-node)
## Further reading
Please see the follow-up article [Forensic container
analysis][forensic-container-analysis] for details on how a container checkpoint
can be analyzed.
[forensic-container-analysis]: /blog/2023/03/10/forensic-container-analysis/

View File

@ -0,0 +1,373 @@
---
layout: blog
title: "Forensic container analysis"
date: 2023-03-10
slug: forensic-container-analysis
---
**Authors:** Adrian Reber (Red Hat)
In my previous article, [Forensic container checkpointing in
Kubernetes][forensic-blog], I introduced checkpointing in Kubernetes
and how it has to be setup and how it can be used. The name of the
feature is Forensic container checkpointing, but I did not go into
any details how to do the actual analysis of the checkpoint created by
Kubernetes. In this article I want to provide details how the
checkpoint can be analyzed.
Checkpointing is still an alpha feature in Kubernetes and this article
wants to provide a preview how the feature might work in the future.
## Preparation
Details about how to configure Kubernetes and the underlying CRI implementation
to enable checkpointing support can be found in my [Forensic container
checkpointing in Kubernetes][forensic-blog] article.
As an example I prepared a container image (`quay.io/adrianreber/counter:blog`)
which I want to checkpoint and then analyze in this article. This container allows
me to create files in the container and also store information in memory which
I later want to find in the checkpoint.
To run that container I need a pod, and for this example I am using the following Pod manifest:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: counters
spec:
containers:
- name: counter
image: quay.io/adrianreber/counter:blog
```
This results in a container called `counter` running in a pod called `counters`.
Once the container is running I am performing following actions with that
container:
```console
$ kubectl get pod counters --template '{{.status.podIP}}'
10.88.0.25
$ curl 10.88.0.25:8088/create?test-file
$ curl 10.88.0.25:8088/secret?RANDOM_1432_KEY
$ curl 10.88.0.25:8088
```
The first access creates a file called `test-file` with the content `test-file`
in the container and the second access stores my secret information
(`RANDOM_1432_KEY`) somewhere in the container's memory. The last access just
adds an additional line to the internal log file.
The last step before I can analyze the checkpoint it to tell Kubernetes to create
the checkpoint. As described in the previous article this requires access to the
*kubelet* only `checkpoint` API endpoint.
For a container named *counter* in a pod named *counters* in a namespace named
*default* the *kubelet* API endpoint is reachable at:
```shell
# run this on the node where that Pod is executing
curl -X POST "https://localhost:10250/checkpoint/default/counters/counter"
```
For completeness the following `curl` command-line options are necessary to
have `curl` accept the *kubelet*'s self signed certificate and authorize the
use of the *kubelet* `checkpoint` API:
```shell
--insecure --cert /var/run/kubernetes/client-admin.crt --key /var/run/kubernetes/client-admin.key
```
Once the checkpointing has finished the checkpoint should be available at
`/var/lib/kubelet/checkpoints/checkpoint-<pod-name>_<namespace-name>-<container-name>-<timestamp>.tar`
In the following steps of this article I will use the name `checkpoint.tar`
when analyzing the checkpoint archive.
## Checkpoint archive analysis using `checkpointctl`
To get some initial information about the checkpointed container I am using the
tool [checkpointctl][checkpointctl] like this:
```console
$ checkpointctl show checkpoint.tar --print-stats
+-----------+----------------------------------+--------------+---------+---------------------+--------+------------+------------+-------------------+
| CONTAINER | IMAGE | ID | RUNTIME | CREATED | ENGINE | IP | CHKPT SIZE | ROOT FS DIFF SIZE |
+-----------+----------------------------------+--------------+---------+---------------------+--------+------------+------------+-------------------+
| counter | quay.io/adrianreber/counter:blog | 059a219a22e5 | runc | 2023-03-02T06:06:49 | CRI-O | 10.88.0.23 | 8.6 MiB | 3.0 KiB |
+-----------+----------------------------------+--------------+---------+---------------------+--------+------------+------------+-------------------+
CRIU dump statistics
+---------------+-------------+--------------+---------------+---------------+---------------+
| FREEZING TIME | FROZEN TIME | MEMDUMP TIME | MEMWRITE TIME | PAGES SCANNED | PAGES WRITTEN |
+---------------+-------------+--------------+---------------+---------------+---------------+
| 100809 us | 119627 us | 11602 us | 7379 us | 7800 | 2198 |
+---------------+-------------+--------------+---------------+---------------+---------------+
```
This gives me already some information about the checkpoint in that checkpoint
archive. I can see the name of the container, information about the container
runtime and container engine. It also lists the size of the checkpoint (`CHKPT
SIZE`). This is mainly the size of the memory pages included in the checkpoint,
but there is also information about the size of all changed files in the
container (`ROOT FS DIFF SIZE`).
The additional parameter `--print-stats` decodes information in the checkpoint
archive and displays them in the second table (*CRIU dump statistics*). This
information is collected during checkpoint creation and gives an overview how much
time CRIU needed to checkpoint the processes in the container and how many
memory pages were analyzed and written during checkpoint creation.
## Digging deeper
With the help of `checkpointctl` I am able to get some high level information
about the checkpoint archive. To be able to analyze the checkpoint archive
further I have to extract it. The checkpoint archive is a *tar* archive and can
be extracted with the help of `tar xf checkpoint.tar`.
Extracting the checkpoint archive will result in following files and directories:
* `bind.mounts` - this file contains information about bind mounts and is needed
during restore to mount all external files and directories at the right location
* `checkpoint/` - this directory contains the actual checkpoint as created by
CRIU
* `config.dump` and `spec.dump` - these files contain metadata about the container
which is needed during restore
* `dump.log` - this file contains the debug output of CRIU created during
checkpointing
* `stats-dump` - this file contains the data which is used by `checkpointctl`
to display dump statistics (`--print-stats`)
* `rootfs-diff.tar` - this file contains all changed files on the container's
file-system
### File-system changes - `rootfs-diff.tar`
The first step to analyze the container's checkpoint further is to look at
the files that have changed in my container. This can be done by looking at the
file `rootfs-diff.tar`:
```console
$ tar xvf rootfs-diff.tar
home/counter/logfile
home/counter/test-file
```
Now the files that changed in the container can be studied:
```console
$ cat home/counter/logfile
10.88.0.1 - - [02/Mar/2023 06:07:29] "GET /create?test-file HTTP/1.1" 200 -
10.88.0.1 - - [02/Mar/2023 06:07:40] "GET /secret?RANDOM_1432_KEY HTTP/1.1" 200 -
10.88.0.1 - - [02/Mar/2023 06:07:43] "GET / HTTP/1.1" 200 -
$ cat home/counter/test-file
test-file 
```
Compared to the container image (`quay.io/adrianreber/counter:blog`) this
container is based on, I can see that the file `logfile` contains information
about all access to the service the container provides and the file `test-file`
was created just as expected.
With the help of `rootfs-diff.tar` it is possible to inspect all files that
were created or changed compared to the base image of the container.
### Analyzing the checkpointed processes - `checkpoint/`
The directory `checkpoint/` contains data created by CRIU while checkpointing
the processes in the container. The content in the directory `checkpoint/`
consists of different [image files][image-files] which can be analyzed with the
help of the tool [CRIT][crit] which is distributed as part of CRIU.
First lets get an overview of the processes inside of the container:
```console
$ crit show checkpoint/pstree.img | jq .entries[].pid
1
7
8
```
This output means that I have three processes inside of the container's PID
namespace with the PIDs: 1, 7, 8
This is only the view from the inside of the container's PID namespace. During
restore exactly these PIDs will be recreated. From the outside of the
container's PID namespace the PIDs will change after restore.
The next step is to get some additional information about these three processes:
```console
$ crit show checkpoint/core-1.img | jq .entries[0].tc.comm
"bash"
$ crit show checkpoint/core-7.img | jq .entries[0].tc.comm
"counter.py"
$ crit show checkpoint/core-8.img | jq .entries[0].tc.comm
"tee"
```
This means the three processes in my container are `bash`, `counter.py` (a Python
interpreter) and `tee`. For details about the parent child relations of these processes there
is more data to be analyzed in `checkpoint/pstree.img`.
Let's compare the so far collected information to the still running container:
```console
$ crictl inspect --output go-template --template "{{(index .info.pid)}}" 059a219a22e56
722520
$ ps auxf | grep -A 2 722520
fedora 722520 \_ bash -c /home/counter/counter.py 2>&1 | tee /home/counter/logfile
fedora 722541 \_ /usr/bin/python3 /home/counter/counter.py
fedora 722542 \_ /usr/bin/coreutils --coreutils-prog-shebang=tee /usr/bin/tee /home/counter/logfile
$ cat /proc/722520/comm
bash
$ cat /proc/722541/comm
counter.py
$ cat /proc/722542/comm
tee
```
In this output I am first retrieving the PID of the first process in the
container and then I am looking for that PID and child processes on the system
where the container is running. I am seeing three processes and the first one is
"bash" which is PID 1 inside of the containers PID namespace. Then I am looking
at `/proc/<PID>/comm` and I can find the exact same value
as in the checkpoint image.
Important to remember is that the checkpoint will contain the view from within the
container's PID namespace because that information is important to restore the
processes.
One last example of what `crit` can tell us about the container is the information
about the UTS namespace:
```console
$ crit show checkpoint/utsns-12.img
{
"magic": "UTSNS",
"entries": [
{
"nodename": "counters",
"domainname": "(none)"
}
]
}
```
This tells me that the hostname inside of the UTS namespace is `counters`.
For every resource CRIU collected during checkpointing the `checkpoint/`
directory contains corresponding image files which can be analyzed with the help
of `crit`.
#### Looking at the memory pages
In addition to the information from CRIU that can be decoded with the help
of CRIT, there are also files containing the raw memory pages written by
CRIU to disk:
```console
$ ls checkpoint/pages-*
checkpoint/pages-1.img checkpoint/pages-2.img checkpoint/pages-3.img
```
When I initially used the container I stored a random key (`RANDOM_1432_KEY`)
somewhere in the memory. Let see if I can find it:
```console
$ grep -ao RANDOM_1432_KEY checkpoint/pages-*
checkpoint/pages-2.img:RANDOM_1432_KEY
```
And indeed, there is my data. This way I can easily look at the content
of all memory pages of the processes in the container, but it is also
important to remember that anyone that can access the checkpoint
archive has access to all information that was stored in the memory of the
container's processes.
#### Using gdb for further analysis
Another possibility to look at the checkpoint images is `gdb`. The CRIU repository
contains the script [coredump][criu-coredump] which can convert a checkpoint
into a coredump file:
```console
$ /home/criu/coredump/coredump-python3
$ ls -al core*
core.1 core.7 core.8
```
Running the `coredump-python3` script will convert the checkpoint images into
one coredump file for each process in the container. Using `gdb` I can also look
at the details of the processes:
```console
$ echo info registers | gdb --core checkpoint/core.1 -q
[New LWP 1]
Core was generated by `bash -c /home/counter/counter.py 2>&1 | tee /home/counter/logfile'.
#0 0x00007fefba110198 in ?? ()
(gdb)
rax 0x3d 61
rbx 0x8 8
rcx 0x7fefba11019a 140667595587994
rdx 0x0 0
rsi 0x7fffed9c1110 140737179816208
rdi 0xffffffff 4294967295
rbp 0x1 0x1
rsp 0x7fffed9c10e8 0x7fffed9c10e8
r8 0x1 1
r9 0x0 0
r10 0x0 0
r11 0x246 582
r12 0x0 0
r13 0x7fffed9c1170 140737179816304
r14 0x0 0
r15 0x0 0
rip 0x7fefba110198 0x7fefba110198
eflags 0x246 [ PF ZF IF ]
cs 0x33 51
ss 0x2b 43
ds 0x0 0
es 0x0 0
fs 0x0 0
gs 0x0 0
```
In this example I can see the value of all registers as they were during
checkpointing and I can also see the complete command-line of my container's PID
1 process: `bash -c /home/counter/counter.py 2>&1 | tee /home/counter/logfile`
## Summary
With the help of container checkpointing, it is possible to create a
checkpoint of a running container without stopping the container and without the
container knowing that it was checkpointed. The result of checkpointing a
container in Kubernetes is a checkpoint archive; using different tools like
`checkpointctl`, `tar`, `crit` and `gdb` the checkpoint can be analyzed. Even
with simple tools like `grep` it is possible to find information in the
checkpoint archive.
The different examples I have shown in this article how to analyze a checkpoint
are just the starting point. Depending on your requirements it is possible to
look at certain things in much more detail, but this article should give you an
introduction how to start the analysis of your checkpoint.
## How do I get involved?
You can reach SIG Node by several means:
* Slack: [#sig-node][slack-sig-node]
* Slack: [#sig-security][slack-sig-security]
* [Mailing list][sig-node-ml]
[forensic-blog]: https://kubernetes.io/blog/2022/12/05/forensic-container-checkpointing-alpha/
[checkpointctl]: https://github.com/checkpoint-restore/checkpointctl
[image-files]: https://criu.org/Images
[crit]: https://criu.org/CRIT
[slack-sig-node]: https://kubernetes.slack.com/messages/sig-node
[slack-sig-security]: https://kubernetes.slack.com/messages/sig-security
[sig-node-ml]: https://groups.google.com/forum/#!forum/kubernetes-sig-node
[criu-coredump]: https://github.com/checkpoint-restore/criu/tree/criu-dev/coredump

View File

@ -18,7 +18,7 @@ This page lists some of the available add-ons and links to their respective inst
* [ACI](https://www.github.com/noironetworks/aci-containers) provides integrated container networking and network security with Cisco ACI.
* [Antrea](https://antrea.io/) operates at Layer 3/4 to provide networking and security services for Kubernetes, leveraging Open vSwitch as the networking data plane. Antrea is a [CNCF project at the Sandbox level](https://www.cncf.io/projects/antrea/).
* [Calico](https://docs.projectcalico.org/latest/introduction/) is a networking and network policy provider. Calico supports a flexible set of networking options so you can choose the most efficient option for your situation, including non-overlay and overlay networks, with or without BGP. Calico uses the same engine to enforce network policy for hosts, pods, and (if using Istio & Envoy) applications at the service mesh layer.
* [Calico](https://www.tigera.io/project-calico/) is a networking and network policy provider. Calico supports a flexible set of networking options so you can choose the most efficient option for your situation, including non-overlay and overlay networks, with or without BGP. Calico uses the same engine to enforce network policy for hosts, pods, and (if using Istio & Envoy) applications at the service mesh layer.
* [Canal](https://projectcalico.docs.tigera.io/getting-started/kubernetes/flannel/flannel) unites Flannel and Calico, providing networking and network policy.
* [Cilium](https://github.com/cilium/cilium) is a networking, observability, and security solution with an eBPF-based data plane. Cilium provides a simple flat Layer 3 network with the ability to span multiple clusters in either a native routing or overlay/encapsulation mode, and can enforce network policies on L3-L7 using an identity-based security model that is decoupled from network addressing. Cilium can act as a replacement for kube-proxy; it also offers additional, opt-in observability and security features. Cilium is a [CNCF project at the Incubation level](https://www.cncf.io/projects/cilium/).
* [CNI-Genie](https://github.com/cni-genie/CNI-Genie) enables Kubernetes to seamlessly connect to a choice of CNI plugins, such as Calico, Canal, Flannel, or Weave. CNI-Genie is a [CNCF project at the Sandbox level](https://www.cncf.io/projects/cni-genie/).

View File

@ -235,7 +235,7 @@ at different times.
{{< note >}}
Clients of the EndpointSlice API must iterate through all the existing EndpointSlices
associated to a Service and build a complete list of unique network endpoints. It is
important to mention that endpoints may be duplicated in different EndointSlices.
important to mention that endpoints may be duplicated in different EndpointSlices.
You can find a reference implementation for how to perform this endpoint aggregation
and deduplication as part of the `EndpointSliceCache` code within `kube-proxy`.

View File

@ -656,7 +656,7 @@ by making the changes that are equivalent to you requesting a Service of
`type: NodePort`. The cloud-controller-manager component then configures the external load balancer to
forward traffic to that assigned node port.
_As an alpha feature_, you can configure a load balanced Service to
You can configure a load balanced Service to
[omit](#load-balancer-nodeport-allocation) assigning a node port, provided that the
cloud provider implementation supports this.
@ -1165,7 +1165,7 @@ will be routed to one of the Service endpoints. `externalIPs` are not managed by
of the cluster administrator.
In the Service spec, `externalIPs` can be specified along with any of the `ServiceTypes`.
In the example below, "`my-service`" can be accessed by clients on "`80.11.12.10:80`" (`externalIP:port`)
In the example below, "`my-service`" can be accessed by clients on "`198.51.100.32:80`" (`externalIP:port`)
```yaml
apiVersion: v1

View File

@ -202,7 +202,7 @@ That is, the CronJob does _not_ update existing Jobs, even if those remain runni
A CronJob creates a Job object approximately once per execution time of its schedule.
The scheduling is approximate because there
are certain circumstances where two Jobs might be created, or no Job might be created.
Kubernetes tries to avoid those situations, but do not completely prevent them. Therefore,
Kubernetes tries to avoid those situations, but does not completely prevent them. Therefore,
the Jobs that you define should be _idempotent_.
If `startingDeadlineSeconds` is set to a large value or left unset (the default)

View File

@ -71,7 +71,7 @@ A Pod is given a QoS class of `Burstable` if:
Pods in the `BestEffort` QoS class can use node resources that aren't specifically assigned
to Pods in other QoS classes. For example, if you have a node with 16 CPU cores available to the
kubelet, and you assign assign 4 CPU cores to a `Guaranteed` Pod, then a Pod in the `BestEffort`
kubelet, and you assign 4 CPU cores to a `Guaranteed` Pod, then a Pod in the `BestEffort`
QoS class can try to use any amount of the remaining 12 CPU cores.
The kubelet prefers to evict `BestEffort` Pods if the node comes under resource pressure.

View File

@ -10,7 +10,7 @@ min-kubernetes-server-version: v1.25
{{< feature-state for_k8s_version="v1.25" state="alpha" >}}
This page explains how user namespaces are used in Kubernetes pods. A user
namespace allows to isolate the user running inside the container from the one
namespace isolates the user running inside the container from the one
in the host.
A process running as root in a container can run as a different (non-root) user

View File

@ -271,6 +271,33 @@ Renders to:
{{< tab name="JSON File" include="podtemplate.json" />}}
{{< /tabs >}}
### Source code files
You can use the `{{</* codenew */>}}` shortcode to embed the contents of file in a code block to allow users to download or copy its content to their clipboard. This shortcode is used when the contents of the sample file is generic and reusable, and you want the users to try it out themselves.
This shortcode takes in two named parameters: `language` and `file`. The mandatory parameter `file` is used to specify the path to the file being displayed. The optional parameter `language` is used to specify the programming language of the file. If the `language` parameter is not provided, the shortcode will attempt to guess the language based on the file extension.
For example:
```none
{{</* codenew language="yaml" file="application/deployment-scale.yaml" */>}}
```
The output is:
{{< codenew language="yaml" file="application/deployment-scale.yaml" >}}
When adding a new sample file, such as a YAML file, create the file in one of the `<LANG>/examples/` subdirectories where `<LANG>` is the language for the page. In the markdown of your page, use the `codenew` shortcode:
```none
{{</* codenew file="<RELATIVE-PATH>/example-yaml>" */>}}
```
where `<RELATIVE-PATH>` is the path to the sample file to include, relative to the `examples` directory. The following shortcode references a YAML file located at `/content/en/examples/configmap/configmaps.yaml`.
```none
{{</* codenew file="configmap/configmaps.yaml" */>}}
```
## Third party content marker
Running Kubernetes requires third-party software. For example: you

View File

@ -631,4 +631,5 @@ These steps ... | These simple steps ...
* Learn about [writing a new topic](/docs/contribute/style/write-new-topic/).
* Learn about [using page templates](/docs/contribute/style/page-content-types/).
* Learn about [custom hugo shortcodes](/docs/contribute/style/hugo-shortcodes/).
* Learn about [creating a pull request](/docs/contribute/new-content/open-a-pr/).

View File

@ -107,7 +107,7 @@ CertificateApproval, CertificateSigning, CertificateSubjectRestriction, DefaultI
{{< note >}}
The [`ValidatingAdmissionPolicy`](#validatingadmissionpolicy) admission plugin is enabled
by default, but is only active if you enable the the `ValidatingAdmissionPolicy`
by default, but is only active if you enable the `ValidatingAdmissionPolicy`
[feature gate](/docs/reference/command-line-tools-reference/feature-gates/) **and**
the `admissionregistration.k8s.io/v1alpha1` API.
{{< /note >}}

View File

@ -0,0 +1,293 @@
---
title: Common Expression Language in Kubernetes
reviewers:
- jpbetz
- cici37
content_type: concept
weight: 35
min-kubernetes-server-version: 1.25
---
<!-- overview -->
The [Common Expression Language (CEL)](https://github.com/google/cel-go) is used
in the Kubernetes API to declare validation rules, policy rules, and other
constraints or conditions.
CEL expressions are evaluated directly in the
{{< glossary_tooltip text="API server" term_id="kube-apiserver" >}}, making CEL a
convenient alternative to out-of-process mechanisms, such as webhooks, for many
extensibility use cases. Your CEL expressions continue to execute so long as the
control plane's API server component remains available.
<!-- body -->
## Language overview
The [CEL
language](https://github.com/google/cel-spec/blob/master/doc/langdef.md) has a
straightforward syntax that is similar to the expressions in C, C++, Java,
JavaScript and Go.
CEL was designed to be embedded into applications. Each CEL "program" is a
single expression that evaluates to a single value. CEL expressions are
typically short "one-liners" that inline well into the string fields of Kubernetes
API resources.
Inputs to a CEL program are "variables". Each Kubernetes API field that contains
CEL declares in the API documentation which variables are available to use for
that field. For example, in the `x-kubernetes-validations[i].rules` field of
CustomResourceDefinitions, the `self` and `oldSelf` variables are available and
refer to the previous and current state of the custom resource data to be
validated by the CEL expression. Other Kubernetes API fields may declare
different variables. See the API documentation of the API fields to learn which
variables are available for that field.
Example CEL expressions:
{{< table caption="Examples of CEL expressions and the purpose of each" >}}
| Rule | Purpose |
|------------------------------------------------------------------------------------|-----------------------------------------------------------------------------------|
| `self.minReplicas <= self.replicas && self.replicas <= self.maxReplicas` | Validate that the three fields defining replicas are ordered appropriately |
| `'Available' in self.stateCounts` | Validate that an entry with the 'Available' key exists in a map |
| `(self.list1.size() == 0) != (self.list2.size() == 0)` | Validate that one of two lists is non-empty, but not both |
| `self.envars.filter(e, e.name = 'MY_ENV').all(e, e.value.matches('^[a-zA-Z]*$')` | Validate the 'value' field of a listMap entry where key field 'name' is 'MY_ENV' |
| `has(self.expired) && self.created + self.ttl < self.expired` | Validate that 'expired' date is after a 'create' date plus a 'ttl' duration |
| `self.health.startsWith('ok')` | Validate a 'health' string field has the prefix 'ok' |
| `self.widgets.exists(w, w.key == 'x' && w.foo < 10)` | Validate that the 'foo' property of a listMap item with a key 'x' is less than 10 |
| `type(self) == string ? self == '99%' : self == 42` | Validate an int-or-string field for both the the int and string cases |
| `self.metadata.name == 'singleton'` | Validate that an object's name matches a specific value (making it a singleton) |
| `self.set1.all(e, !(e in self.set2))` | Validate that two listSets are disjoint |
| `self.names.size() == self.details.size() && self.names.all(n, n in self.details)` | Validate the 'details' map is keyed by the items in the 'names' listSet |
## CEL community libraries
Kubernetes CEL expressions have access to the following CEL community libraries:
- CEL standard functions, defined in the [list of standard definitions](https://github.com/google/cel-spec/blob/master/doc/langdef.md#list-of-standard-definitions)
- CEL standard [macros](https://github.com/google/cel-spec/blob/v0.7.0/doc/langdef.md#macros)
- CEL [extended string function library](https://pkg.go.dev/github.com/google/cel-go/ext#Strings)
## Kubernetes CEL libraries
In additional to the CEL community libraries, Kubernetes includes CEL libraries
that are available everywhere CEL is used in Kubernetes.
### Kubernetes list library
The list library includes `indexOf` and `lastIndexOf`, which work similar to the
strings functions of the same names. These functions either the first or last
positional index of the provided element in the list.
The list library also includes `min`, `max` and `sum`. Sum is supported on all
number types as well as the duration type. Min and max are supported on all
comparable types.
`isSorted` is also provided as a convenience function and is supported on all
comparable types.
Examples:
{{< table caption="Examples of CEL expressions using list library functions" >}}
| CEL Expression | Purpose |
|------------------------------------------------------------------------------------|-----------------------------------------------------------|
| `names.isSorted()` | Verify that a list of names is kept in alphabetical order |
| `items.map(x, x.weight).sum() == 1.0` | Verify that the "weights" of a list of objects sum to 1.0 |
| `lowPriorities.map(x, x.priority).max() < highPriorities.map(x, x.priority).min()` | Verify that two sets of priorities do not overlap |
| `names.indexOf('should-be-first') == 1` | Require that the first name in a list if a specific value |
See the [Kubernetes List Library](https://pkg.go.dev/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/library#Lists)
godoc for more information.
### Kubernetes regex library
In addition to the `matches` function provided by the CEL standard library, the
regex library provides `find` and `findAll`, enabling a much wider range of
regex operations.
Examples:
{{< table caption="Examples of CEL expressions using regex library functions" >}}
| CEL Expression | Purpose |
|-------------------------------------------------------------|----------------------------------------------------------|
| `"abc 123".find('[0-9]*')` | Find the first number in a string |
| `"1, 2, 3, 4".findAll('[0-9]*').map(x, int(x)).sum() < 100` | Verify that the numbers in a string sum to less than 100 |
See the [Kubernetes regex library](https://pkg.go.dev/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/library#Regex)
godoc for more information.
### Kubernetes URL library
To make it easier and safer to process URLs, the following functions have been added:
- `isURL(string)` checks if a string is a valid URL according to the [Go's
net/url](https://pkg.go.dev/net/url#URL) package. The string must be an
absolute URL.
- `url(string) URL` converts a string to a URL or results in an error if the
string is not a valid URL.
Once parsed via the `url` function, the resulting URL object has `getScheme`,
`getHost`, `getHostname`, `getPort`, `getEscapedPath` and `getQuery` accessors.
Examples:
{{< table caption="Examples of CEL expressions using URL library functions" >}}
| CEL Expression | Purpose |
|-----------------------------------------------------------------|------------------------------------------------|
| `url('https://example.com:80/').getHost()` | Get the 'example.com:80' host part of the URL. |
| `url('https://example.com/path with spaces/').getEscapedPath()` | Returns '/path%20with%20spaces/' |
See the [Kubernetes URL library](https://pkg.go.dev/k8s.io/apiextensions-apiserver/pkg/apiserver/schema/cel/library#URLs)
godoc for more information.
## Type checking
CEL is a [gradually typed language](https://github.com/google/cel-spec/blob/master/doc/langdef.md#gradual-type-checking).
Some Kubernetes API fields contain fully type checked CEL expressions. For
example, [CustomResourceDefinitions Validation
Rules](/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#validation-rules)
are fully type checked.
Some Kubernetes API fields contain partially type checked CEL expressions. A
partially type checked expression is an experessions where some of the variables
are statically typed but others are dynamically typed. For example, in the CEL
expressions of
[ValidatingAdmissionPolicies](/docs/reference/access-authn-authz/validating-admission-policy/)
the `request` variable is typed, but the `object` variable is dynamically typed.
As a result, an expression containing `request.namex` would fail type checking
because the `namex` field is not defined. However, `object.namex` would pass
type checking even when the `namex` field is not defined for the resource kinds
that `object` refers to, because `object` is dynamically typed.
The `has()` macro in CEL may be used in CEL expressions to check if a field of a
dynamically typed variable is accessable before attempting to access the field's
value. For example:
```cel
has(object.namex) ? object.namex == 'special' : request.name == 'special'
```
## Type system integration
{{< table caption="Table showing the relationship between OpenAPIv3 types and CEL types" >}}
| OpenAPIv3 type | CEL type |
|----------------------------------------------------|------------------------------------------------------------------------------------------------------------------------------|
| 'object' with Properties | object / "message type" (`type(<object>)` evaluates to `selfType<uniqueNumber>.path.to.object.from.self` |
| 'object' with AdditionalProperties | map |
| 'object' with x-kubernetes-embedded-type | object / "message type", 'apiVersion', 'kind', 'metadata.name' and 'metadata.generateName' are implicitly included in schema |
| 'object' with x-kubernetes-preserve-unknown-fields | object / "message type", unknown fields are NOT accessible in CEL expression |
| x-kubernetes-int-or-string | union of int or string, `self.intOrString < 100 \|\| self.intOrString == '50%'` evaluates to true for both `50` and `"50%"` |
| 'array | list |
| 'array' with x-kubernetes-list-type=map | list with map based Equality & unique key guarantees |
| 'array' with x-kubernetes-list-type=set | list with set based Equality & unique entry guarantees |
| 'boolean' | boolean |
| 'number' (all formats) | double |
| 'integer' (all formats) | int (64) |
| _no equivalent_ | uint (64) |
| 'null' | null_type |
| 'string' | string |
| 'string' with format=byte (base64 encoded) | bytes |
| 'string' with format=date | timestamp (google.protobuf.Timestamp) |
| 'string' with format=datetime | timestamp (google.protobuf.Timestamp) |
| 'string' with format=duration | duration (google.protobuf.Duration) |
Also see: [CEL types](https://github.com/google/cel-spec/blob/v0.6.0/doc/langdef.md#values),
[OpenAPI types](https://swagger.io/specification/#data-types),
[Kubernetes Structural Schemas](/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#specifying-a-structural-schema).
Equality comparison for arrays with `x-kubernetes-list-type` of `set` or `map` ignores element
order. For example `[1, 2] == [2, 1]` if the arrays represent Kubernetes `set` values.
Concatenation on arrays with `x-kubernetes-list-type` use the semantics of the
list type:
- `set`: `X + Y` performs a union where the array positions of all elements in
`X` are preserved and non-intersecting elements in `Y` are appended, retaining
their partial order.
- `map`: `X + Y` performs a merge where the array positions of all keys in `X`
are preserved but the values are overwritten by values in `Y` when the key
sets of `X` and `Y` intersect. Elements in `Y` with non-intersecting keys are
appended, retaining their partial order.
## Escaping
Only Kubernetes resource property names of the form
`[a-zA-Z_.-/][a-zA-Z0-9_.-/]*` are accessible from CEL. Accessible property
names are escaped according to the following rules when accessed in the
expression:
{{< table caption="Table of CEL identifier escaping rules" >}}
| escape sequence | property name equivalent |
|-------------------|----------------------------------------------------------------------------------------------|
| `__underscores__` | `__` |
| `__dot__` | `.` |
| `__dash__` | `-` |
| `__slash__` | `/` |
| `__{keyword}__` | [CEL **RESERVED** keyword](https://github.com/google/cel-spec/blob/v0.6.0/doc/langdef.md#syntax) |
When you escape any of CEL's **RESERVED** keywords you need to match the exact property name
use the underscore escaping
(for example, `int` in the word `sprint` would not be escaped and nor would it need to be).
Examples on escaping:
{{< table caption="Examples escaped CEL identifiers" >}}
| property name | rule with escaped property name |
|---------------|-----------------------------------|
| `namespace` | `self.__namespace__ > 0` |
| `x-prop` | `self.x__dash__prop > 0` |
| `redact__d` | `self.redact__underscores__d > 0` |
| `string` | `self.startsWith('kube')` |
## Resource constraints
CEL is non-Turing complete and offers a variety of production safety controls to
limit execution time. CEL's _resource constraint_ features provide feedback to
developers about expression complexity and help protect the API server from
excessive resource consumption during evaluation. CEL's resource constraint
features are used to prevent CEL evaluation from consuming excessive API server
resources.
A key element of the resource constraint features is a _cost unit_ that CEL
defines as a way of tracking CPU utilization. Cost units are independant of
system load and hardware. Cost units are also deterministic; for any given CEL
expression and input data, evaluation of the expression by the CEL interpreter
will always result in the same cost.
Many of CEL's core operations have fixed costs. The simplest operations, such as
comparisons (e.g. `<`) have a cost of 1. Some have a higher fixed cost, for
example list literal declarations have a fixed base cost of 40 cost units.
Calls to functions implemented in native code approximate cost based on the time
complexity of the operation. For example: operations that use regular
expressions, such as `match` and `find`, are estimated using an approximated
cost of `length(regexString)*length(inputString)`. The approximated cost
reflects the worst case time complexity of Go's RE2 implementation.
### Runtime cost budget
All CEL expressions evaluated by Kubernetes are constrained by a runtime cost
budget. The runtime cost budget is an estimate of actual CPU utilization
computed by incrementing a cost unit counter while interpreting a CEL
expression. If the CEL interpreter executes too many instructions, the runtime
cost budget will be exceeded, execution of the expressions will be halted, and
an error will result.
Some Kubernetes resources define an additional runtime cost budget that bounds
the execution of multiple expressions. If the sum total of the cost of
expressions exceed the budget, execution of the expressions will be halted, and
an error will result. For example the validation of a custom resource has a
_per-validation_ runtime cost budget for all [Validation
Rules](https://kubernetes.io/docs/tasks/extend-kubernetes/custom-resources/custom-resource-definitions/#validation-rules)
evaluated to validate the custom resource.
### Estimated cost limits
For some Kubernetes resources, the API server may also check if worst case
estimated running time of CEL expressions would be prohibitively expensive to
execute. If so, the API server prevent the CEL expression from being written to
API resources by rejecting create or update operations containing the CEL
expression to the API resources. This feature offers a stronger assurance that
CEL expressions written to the API resource will be evaluate at runtime without
exceeding the runtime cost budget.

View File

@ -41,12 +41,12 @@ cluster's API server.
## Define clusters, users, and contexts
Suppose you have two clusters, one for development work and one for scratch work.
Suppose you have two clusters, one for development work and one for test work.
In the `development` cluster, your frontend developers work in a namespace called `frontend`,
and your storage developers work in a namespace called `storage`. In your `scratch` cluster,
and your storage developers work in a namespace called `storage`. In your `test` cluster,
developers work in the default namespace, or they create auxiliary namespaces as they
see fit. Access to the development cluster requires authentication by certificate. Access
to the scratch cluster requires authentication by username and password.
to the test cluster requires authentication by username and password.
Create a directory named `config-exercise`. In your
`config-exercise` directory, create a file named `config-demo` with this content:
@ -60,7 +60,7 @@ clusters:
- cluster:
name: development
- cluster:
name: scratch
name: test
users:
- name: developer
@ -72,7 +72,7 @@ contexts:
- context:
name: dev-storage
- context:
name: exp-scratch
name: exp-test
```
A configuration file describes clusters, users, and contexts. Your `config-demo` file
@ -83,7 +83,7 @@ your configuration file:
```shell
kubectl config --kubeconfig=config-demo set-cluster development --server=https://1.2.3.4 --certificate-authority=fake-ca-file
kubectl config --kubeconfig=config-demo set-cluster scratch --server=https://5.6.7.8 --insecure-skip-tls-verify
kubectl config --kubeconfig=config-demo set-cluster test --server=https://5.6.7.8 --insecure-skip-tls-verify
```
Add user details to your configuration file:
@ -108,7 +108,7 @@ Add context details to your configuration file:
```shell
kubectl config --kubeconfig=config-demo set-context dev-frontend --cluster=development --namespace=frontend --user=developer
kubectl config --kubeconfig=config-demo set-context dev-storage --cluster=development --namespace=storage --user=developer
kubectl config --kubeconfig=config-demo set-context exp-scratch --cluster=scratch --namespace=default --user=experimenter
kubectl config --kubeconfig=config-demo set-context exp-test --cluster=test --namespace=default --user=experimenter
```
Open your `config-demo` file to see the added details. As an alternative to opening the
@ -130,7 +130,7 @@ clusters:
- cluster:
insecure-skip-tls-verify: true
server: https://5.6.7.8
name: scratch
name: test
contexts:
- context:
cluster: development
@ -143,10 +143,10 @@ contexts:
user: developer
name: dev-storage
- context:
cluster: scratch
cluster: test
namespace: default
user: experimenter
name: exp-scratch
name: exp-test
current-context: ""
kind: Config
preferences: {}
@ -220,19 +220,19 @@ users:
client-key: fake-key-file
```
Now suppose you want to work for a while in the scratch cluster.
Now suppose you want to work for a while in the test cluster.
Change the current context to `exp-scratch`:
Change the current context to `exp-test`:
```shell
kubectl config --kubeconfig=config-demo use-context exp-scratch
kubectl config --kubeconfig=config-demo use-context exp-test
```
Now any `kubectl` command you give will apply to the default namespace of
the `scratch` cluster. And the command will use the credentials of the user
listed in the `exp-scratch` context.
the `test` cluster. And the command will use the credentials of the user
listed in the `exp-test` context.
View configuration associated with the new current context, `exp-scratch`.
View configuration associated with the new current context, `exp-test`.
```shell
kubectl config --kubeconfig=config-demo view --minify
@ -338,10 +338,10 @@ contexts:
user: developer
name: dev-storage
- context:
cluster: scratch
cluster: test
namespace: default
user: experimenter
name: exp-scratch
name: exp-test
```
For more information about how kubeconfig files are merged, see

View File

@ -8,7 +8,7 @@ weight: 50
<!-- overview -->
The `dockershim` component of Kubernetes allows to use Docker as a Kubernetes's
The `dockershim` component of Kubernetes allows the use of Docker as a Kubernetes's
{{< glossary_tooltip text="container runtime" term_id="container-runtime" >}}.
Kubernetes' built-in `dockershim` component was removed in release v1.24.
@ -40,11 +40,11 @@ dependency on Docker:
1. Third-party tools that perform above mentioned privileged operations. See
[Migrating telemetry and security agents from dockershim](/docs/tasks/administer-cluster/migrating-from-dockershim/migrating-telemetry-and-security-agents)
for more information.
1. Make sure there is no indirect dependencies on dockershim behavior.
1. Make sure there are no indirect dependencies on dockershim behavior.
This is an edge case and unlikely to affect your application. Some tooling may be configured
to react to Docker-specific behaviors, for example, raise alert on specific metrics or search for
a specific log message as part of troubleshooting instructions.
If you have such tooling configured, test the behavior on test
If you have such tooling configured, test the behavior on a test
cluster before migration.
## Dependency on Docker explained {#role-of-dockershim}
@ -74,7 +74,7 @@ before to check on these containers is no longer available.
You cannot get container information using `docker ps` or `docker inspect`
commands. As you cannot list containers, you cannot get logs, stop containers,
or execute something inside container using `docker exec`.
or execute something inside a container using `docker exec`.
{{< note >}}

View File

@ -67,6 +67,7 @@ cat /mnt/data/index.html
```
The output should be:
```
Hello from Kubernetes storage
```
@ -247,8 +248,8 @@ You can now close the shell to your Node.
You can perform 2 volume mounts on your nginx container:
`/usr/share/nginx/html` for the static website
`/etc/nginx/nginx.conf` for the default config
- `/usr/share/nginx/html` for the static website
- `/etc/nginx/nginx.conf` for the default config
<!-- discussion -->
@ -261,6 +262,7 @@ with a GID. Then the GID is automatically added to any Pod that uses the
PersistentVolume.
Use the `pv.beta.kubernetes.io/gid` annotation as follows:
```yaml
apiVersion: v1
kind: PersistentVolume
@ -269,6 +271,7 @@ metadata:
annotations:
pv.beta.kubernetes.io/gid: "1234"
```
When a Pod consumes a PersistentVolume that has a GID annotation, the annotated GID
is applied to all containers in the Pod in the same way that GIDs specified in the
Pod's security context are. Every GID, whether it originates from a PersistentVolume

View File

@ -30,6 +30,11 @@ Install the following on your workstation:
- [KinD](https://kind.sigs.k8s.io/docs/user/quick-start/#installation)
- [kubectl](/docs/tasks/tools/)
This tutorial demonstrates what you can configure for a Kubernetes cluster that you fully
control. If you are learning how to configure Pod Security Admission for a managed cluster
where you are not able to configure the control plane, read
[Apply Pod Security Standards at the namespace level](/docs/tutorials/security/ns-level-pss).
## Choose the right Pod Security Standard to apply
[Pod Security Admission](/docs/concepts/security/pod-security-admission/)
@ -42,22 +47,22 @@ that are most appropriate for your configuration, do the following:
1. Create a cluster with no Pod Security Standards applied:
```shell
kind create cluster --name psa-wo-cluster-pss --image kindest/node:v1.24.0
kind create cluster --name psa-wo-cluster-pss
```
The output is similar to this:
The output is similar to:
```
Creating cluster "psa-wo-cluster-pss" ...
✓ Ensuring node image (kindest/node:v1.24.0) 🖼
✓ Preparing nodes 📦
✓ Ensuring node image (kindest/node:v{{< skew currentVersion >}}.0) 🖼
✓ Preparing nodes 📦
✓ Writing configuration 📜
✓ Starting control-plane 🕹️
✓ Installing CNI 🔌
✓ Installing StorageClass 💾
Set kubectl context to "kind-psa-wo-cluster-pss"
You can now use your cluster with:
kubectl cluster-info --context kind-psa-wo-cluster-pss
Thanks for using kind! 😊
```
@ -72,7 +77,7 @@ that are most appropriate for your configuration, do the following:
Kubernetes control plane is running at https://127.0.0.1:61350
CoreDNS is running at https://127.0.0.1:61350/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
```
@ -82,7 +87,7 @@ that are most appropriate for your configuration, do the following:
kubectl get ns
```
The output is similar to this:
```
```
NAME STATUS AGE
default Active 9m30s
kube-node-lease Active 9m32s
@ -99,8 +104,9 @@ that are most appropriate for your configuration, do the following:
kubectl label --dry-run=server --overwrite ns --all \
pod-security.kubernetes.io/enforce=privileged
```
The output is similar to this:
```
The output is similar to:
```
namespace/default labeled
namespace/kube-node-lease labeled
namespace/kube-public labeled
@ -108,12 +114,13 @@ that are most appropriate for your configuration, do the following:
namespace/local-path-storage labeled
```
2. Baseline
```shell
```shell
kubectl label --dry-run=server --overwrite ns --all \
pod-security.kubernetes.io/enforce=baseline
```
The output is similar to this:
```
The output is similar to:
```
namespace/default labeled
namespace/kube-node-lease labeled
namespace/kube-public labeled
@ -123,15 +130,16 @@ that are most appropriate for your configuration, do the following:
Warning: kube-proxy-m6hwf: host namespaces, hostPath volumes, privileged
namespace/kube-system labeled
namespace/local-path-storage labeled
```
```
3. Restricted
```shell
kubectl label --dry-run=server --overwrite ns --all \
pod-security.kubernetes.io/enforce=restricted
```
The output is similar to this:
```
The output is similar to:
```
namespace/default labeled
namespace/kube-node-lease labeled
namespace/kube-public labeled
@ -180,7 +188,7 @@ following:
```
mkdir -p /tmp/pss
cat <<EOF > /tmp/pss/cluster-level-pss.yaml
cat <<EOF > /tmp/pss/cluster-level-pss.yaml
apiVersion: apiserver.config.k8s.io/v1
kind: AdmissionConfiguration
plugins:
@ -212,7 +220,7 @@ following:
1. Configure the API server to consume this file during cluster creation:
```
cat <<EOF > /tmp/pss/cluster-config.yaml
cat <<EOF > /tmp/pss/cluster-config.yaml
kind: Cluster
apiVersion: kind.x-k8s.io/v1alpha4
nodes:
@ -255,22 +263,22 @@ following:
these Pod Security Standards:
```shell
kind create cluster --name psa-with-cluster-pss --image kindest/node:v1.24.0 --config /tmp/pss/cluster-config.yaml
kind create cluster --name psa-with-cluster-pss --config /tmp/pss/cluster-config.yaml
```
The output is similar to this:
```
Creating cluster "psa-with-cluster-pss" ...
✓ Ensuring node image (kindest/node:v1.24.0) 🖼
✓ Preparing nodes 📦
✓ Writing configuration 📜
✓ Starting control-plane 🕹️
✓ Installing CNI 🔌
✓ Installing StorageClass 💾
✓ Ensuring node image (kindest/node:v{{< skew currentVersion >}}.0) 🖼
✓ Preparing nodes 📦
✓ Writing configuration 📜
✓ Starting control-plane 🕹️
✓ Installing CNI 🔌
✓ Installing StorageClass 💾
Set kubectl context to "kind-psa-with-cluster-pss"
You can now use your cluster with:
kubectl cluster-info --context kind-psa-with-cluster-pss
Have a question, bug, or feature request? Let us know! https://kind.sigs.k8s.io/#community 🙂
```
@ -281,36 +289,21 @@ following:
The output is similar to this:
```
Kubernetes control plane is running at https://127.0.0.1:63855
CoreDNS is running at https://127.0.0.1:63855/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy
To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
```
1. Create the following Pod specification for a minimal configuration in the default namespace:
```
cat <<EOF > /tmp/pss/nginx-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
containers:
- image: nginx
name: nginx
ports:
- containerPort: 80
EOF
```
1. Create the Pod in the cluster:
1. Create a Pod in the default namespace:
```shell
kubectl apply -f /tmp/pss/nginx-pod.yaml
kubectl apply -f https://k8s.io/examples/security/example-baseline-pod.yaml
```
The output is similar to this:
The pod is started normally, but the output includes a warning:
```
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "nginx" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "nginx" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "nginx" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "nginx" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
pod/nginx created
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "nginx" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "nginx" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "nginx" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "nginx" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
pod/nginx created
```
## Clean up

View File

@ -31,14 +31,14 @@ Install the following on your workstation:
1. Create a `KinD` cluster as follows:
```shell
kind create cluster --name psa-ns-level --image kindest/node:v1.23.0
kind create cluster --name psa-ns-level
```
The output is similar to this:
```
Creating cluster "psa-ns-level" ...
✓ Ensuring node image (kindest/node:v1.23.0) 🖼
✓ Ensuring node image (kindest/node:v{{< skew currentVersion >}}.0) 🖼
✓ Preparing nodes 📦
✓ Writing configuration 📜
✓ Starting control-plane 🕹️
@ -80,11 +80,12 @@ The output is similar to this:
namespace/example created
```
## Apply Pod Security Standards
## Enable Pod Security Standards checking for that namespace
1. Enable Pod Security Standards on this namespace using labels supported by
built-in Pod Security Admission. In this step we will warn on baseline pod
security standard as per the latest version (default value)
built-in Pod Security Admission. In this step you will configure a check to
warn on Pods that don't meet the latest version of the _baseline_ pod
security standard.
```shell
kubectl label --overwrite ns example \
@ -92,8 +93,8 @@ namespace/example created
pod-security.kubernetes.io/warn-version=latest
```
2. Multiple pod security standards can be enabled on any namespace, using labels.
Following command will `enforce` the `baseline` Pod Security Standard, but
2. You can configure multiple pod security standard checks on any namespace, using labels.
The following command will `enforce` the `baseline` Pod Security Standard, but
`warn` and `audit` for `restricted` Pod Security Standards as per the latest
version (default value)
@ -107,41 +108,24 @@ namespace/example created
pod-security.kubernetes.io/audit-version=latest
```
## Verify the Pod Security Standards
## Verify the Pod Security Standard enforcement
1. Create a minimal pod in `example` namespace:
1. Create a baseline Pod in the `example` namespace:
```shell
cat <<EOF > /tmp/pss/nginx-pod.yaml
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
containers:
- image: nginx
name: nginx
ports:
- containerPort: 80
EOF
kubectl apply -n example -f https://k8s.io/examples/security/example-baseline-pod.yaml
```
1. Apply the pod spec to the cluster in `example` namespace:
```shell
kubectl apply -n example -f /tmp/pss/nginx-pod.yaml
```
The output is similar to this:
The Pod does start OK; the output includes a warning. For example:
```
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "nginx" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "nginx" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "nginx" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "nginx" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost")
pod/nginx created
```
1. Apply the pod spec to the cluster in `default` namespace:
1. Create a baseline Pod in the `default` namespace:
```shell
kubectl apply -n default -f /tmp/pss/nginx-pod.yaml
kubectl apply -n default -f https://k8s.io/examples/security/example-baseline-pod.yaml
```
Output is similar to this:
@ -149,9 +133,9 @@ namespace/example created
pod/nginx created
```
The Pod Security Standards were applied only to the `example`
namespace. You could create the same Pod in the `default` namespace
with no warnings.
The Pod Security Standards enforcement and warning settings were applied only
to the `example` namespace. You could create the same Pod in the `default`
namespace with no warnings.
## Clean up

View File

@ -0,0 +1,10 @@
apiVersion: v1
kind: Pod
metadata:
name: nginx
spec:
containers:
- image: nginx
name: nginx
ports:
- containerPort: 80

View File

@ -51,11 +51,12 @@ nodes:
# default None
propagation: None
EOF
kind create cluster --name psa-with-cluster-pss --image kindest/node:v1.23.0 --config /tmp/pss/cluster-config.yaml
kind create cluster --name psa-with-cluster-pss --config /tmp/pss/cluster-config.yaml
kubectl cluster-info --context kind-psa-with-cluster-pss
# Wait for 15 seconds (arbitrary) ServiceAccount Admission Controller to be available
sleep 15
cat <<EOF > /tmp/pss/nginx-pod.yaml
cat <<EOF |
apiVersion: v1
kind: Pod
metadata:
@ -67,4 +68,17 @@ spec:
ports:
- containerPort: 80
EOF
kubectl apply -f /tmp/pss/nginx-pod.yaml
kubectl apply -f -
# Await input
sleep 1
( bash -c 'true' 2>/dev/null && bash -c 'read -p "Press any key to continue... " -n1 -s' ) || \
( printf "Press Enter to continue... " && read ) 1>&2
# Clean up
printf "\n\nCleaning up:\n" 1>&2
set -e
kubectl delete pod --all -n example --now
kubectl delete ns example
kind delete cluster --name psa-with-cluster-pss
rm -f /tmp/pss/cluster-config.yaml

View File

@ -1,11 +1,11 @@
#!/bin/sh
# Until v1.23 is released, kind node image needs to be built from k/k master branch
# Ref: https://kind.sigs.k8s.io/docs/user/quick-start/#building-images
kind create cluster --name psa-ns-level --image kindest/node:v1.23.0
kind create cluster --name psa-ns-level
kubectl cluster-info --context kind-psa-ns-level
# Wait for 15 seconds (arbitrary) ServiceAccount Admission Controller to be available
# Wait for 15 seconds (arbitrary) for ServiceAccount Admission Controller to be available
sleep 15
kubectl create ns example
# Create and label the namespace
kubectl create ns example || exit 1 # if namespace exists, don't do the next steps
kubectl label --overwrite ns example \
pod-security.kubernetes.io/enforce=baseline \
pod-security.kubernetes.io/enforce-version=latest \
@ -13,7 +13,9 @@ kubectl label --overwrite ns example \
pod-security.kubernetes.io/warn-version=latest \
pod-security.kubernetes.io/audit=restricted \
pod-security.kubernetes.io/audit-version=latest
cat <<EOF > /tmp/pss/nginx-pod.yaml
# Try running a Pod
cat <<EOF |
apiVersion: v1
kind: Pod
metadata:
@ -25,4 +27,16 @@ spec:
ports:
- containerPort: 80
EOF
kubectl apply -n example -f /tmp/pss/nginx-pod.yaml
kubectl apply -n example -f -
# Await input
sleep 1
( bash -c 'true' 2>/dev/null && bash -c 'read -p "Press any key to continue... " -n1 -s' ) || \
( printf "Press Enter to continue... " && read ) 1>&2
# Clean up
printf "\n\nCleaning up:\n" 1>&2
set -e
kubectl delete pod --all -n example --now
kubectl delete ns example
kind delete cluster --name psa-ns-level

View File

@ -78,9 +78,10 @@ releases may also occur in between these.
| Monthly Patch Release | Cherry Pick Deadline | Target date |
| --------------------- | -------------------- | ----------- |
| February 2023 | 2023-02-10 | 2023-02-15 |
| March 2023 | 2023-03-10 | 2023-03-15 |
| April 2023 | 2023-04-07 | 2023-04-12 |
| May 2023 | 2023-05-12 | 2023-05-17 |
| June 2023 | 2023-06-09 | 2023-06-14 |
## Detailed Release History for Active Branches

View File

@ -722,7 +722,7 @@ Conditions:
Events:
FirstSeen LastSeen Count From SubobjectPath Reason Message
Tue, 07 Jul 2015 12:53:51 -0700 Tue, 07 Jul 2015 12:53:51 -0700 1 {scheduler } scheduled Successfully assigned simmemleak-hra99 to kubernetes-node-tf0f
Tue, 07 Jul 2015 12:53:51 -0700 Tue, 07 Jul 2015 12:53:51 -0700 1 {kubelet kubernetes-node-tf0f} implicitly required container POD pulled Pod container image "k8s.gcr.io/pause:0.8.0" already present on machine
Tue, 07 Jul 2015 12:53:51 -0700 Tue, 07 Jul 2015 12:53:51 -0700 1 {kubelet kubernetes-node-tf0f} implicitly required container POD pulled Pod container image "registry.k8s.io/pause:0.8.0" already present on machine
Tue, 07 Jul 2015 12:53:51 -0700 Tue, 07 Jul 2015 12:53:51 -0700 1 {kubelet kubernetes-node-tf0f} implicitly required container POD created Created with docker id 6a41280f516d
Tue, 07 Jul 2015 12:53:51 -0700 Tue, 07 Jul 2015 12:53:51 -0700 1 {kubelet kubernetes-node-tf0f} implicitly required container POD started Started with docker id 6a41280f516d
Tue, 07 Jul 2015 12:53:51 -0700 Tue, 07 Jul 2015 12:53:51 -0700 1 {kubelet kubernetes-node-tf0f} spec.containers{simmemleak} created Created with docker id 87348f12526a

View File

@ -840,7 +840,7 @@ spec:
secretName: dotfile-secret
containers:
- name: dotfile-test-container
image: k8s.gcr.io/busybox
image: registry.k8s.io/busybox
command:
- ls
- "-l"

View File

@ -95,7 +95,7 @@ metadata:
spec:
containers:
- name: cuda-test
image: "k8s.gcr.io/cuda-vector-add:v0.1"
image: "registry.k8s.io/cuda-vector-add:v0.1"
resources:
limits:
nvidia.com/gpu: 1

View File

@ -72,7 +72,7 @@ metadata:
name: test-ebs
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /test-ebs
@ -160,7 +160,7 @@ metadata:
name: test-cinder
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-cinder-container
volumeMounts:
- mountPath: /test-cinder
@ -271,7 +271,7 @@ metadata:
name: test-pd
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /cache
@ -349,7 +349,7 @@ metadata:
name: test-pd
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /test-pd
@ -496,7 +496,7 @@ metadata:
name: test-pd
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /test-pd
@ -526,7 +526,7 @@ metadata:
spec:
containers:
- name: test-webserver
image: k8s.gcr.io/test-webserver:latest
image: registry.k8s.io/test-webserver:latest
volumeMounts:
- mountPath: /var/local/aaa
name: mydir
@ -657,7 +657,7 @@ metadata:
name: test-portworx-volume-pod
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /mnt
@ -847,7 +847,7 @@ metadata:
name: pod-0
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: pod-0
volumeMounts:
- mountPath: /test-pd
@ -976,7 +976,7 @@ metadata:
name: test-vmdk
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /test-vmdk

View File

@ -85,7 +85,7 @@ spec:
terminationGracePeriodSeconds: 10
containers:
- name: nginx
image: k8s.gcr.io/nginx-slim:0.8
image: registry.k8s.io/nginx-slim:0.8
ports:
- containerPort: 80
name: web

View File

@ -41,7 +41,7 @@ En este ejercicio crearás un Pod que ejecuta un único Contenedor. Este Pod tie
La salida debería ser similar a:
```shell
```console
NAME READY STATUS RESTARTS AGE
redis 1/1 Running 0 13s
```
@ -69,7 +69,7 @@ En este ejercicio crearás un Pod que ejecuta un único Contenedor. Este Pod tie
La salida debería ser similar a:
```shell
```console
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
redis 1 0.1 0.1 33308 3828 ? Ssl 00:46 0:00 redis-server *:6379
root 12 0.0 0.0 20228 3020 ? Ss 00:47 0:00 /bin/bash
@ -86,7 +86,7 @@ En este ejercicio crearás un Pod que ejecuta un único Contenedor. Este Pod tie
1. En el terminal original, observa los cambios en el Pod de Redis. Eventualmente verás algo como lo siguiente:
```shell
```console
NAME READY STATUS RESTARTS AGE
redis 1/1 Running 0 13s
redis 0/1 Completed 0 6m

View File

@ -57,7 +57,7 @@ Existen los siguientes métodos para instalar kubectl en Windows:
- Usando PowerShell puede automatizar la verificación usando el operador `-eq` para obtener un resultado de `True` o `False`:
```powershell
$($(CertUtil -hashfile .\kubectl.exe SHA256)[1] -replace " ", "") -eq $(type .\kubectl.exe.sha256)
$(Get-FileHash -Algorithm SHA256 .\kubectl.exe).Hash -eq $(Get-Content .\kubectl.exe.sha256))
```
1. Agregue el binario a su `PATH`.

View File

@ -50,8 +50,7 @@ brew install bash-completion@2
Como se indica en el resultado de este comando, agregue lo siguiente a su archivo `~/.bash_profile`:
```bash
export BASH_COMPLETION_COMPAT_DIR="/usr/local/etc/bash_completion.d"
[[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && . "/usr/local/etc/profile.d/bash_completion.sh"
brew_etc="$(brew --prefix)/etc" && [[ -r "${brew_etc}/profile.d/bash_completion.sh" ]] && . "${brew_etc}/profile.d/bash_completion.sh"
```
Vuelva a cargar su shell y verifique que bash-complete v2 esté instalado correctamente con `type _init_completion`.

View File

@ -76,7 +76,7 @@ Un [*Deployment*](/docs/concepts/workloads/controllers/deployment/) en Kubernete
1. Ejecutar el comando `kubectl create` para crear un Deployment que maneje un Pod. El Pod ejecuta un contenedor basado en la imagen proveida por Docker.
```shell
kubectl create deployment hello-node --image=k8s.gcr.io/echoserver:1.4
kubectl create deployment hello-node --image=registry.k8s.io/echoserver:1.4
```
2. Ver el Deployment:

View File

@ -889,7 +889,7 @@ spec:
secretName: dotfile-secret
containers:
- name: dotfile-test-container
image: k8s.gcr.io/busybox
image: registry.k8s.io/busybox
command:
- ls
- "-l"

View File

@ -192,7 +192,7 @@ spec:
path: /any/path/it/will/be/replaced
containers:
- name: pv-recycler
image: "k8s.gcr.io/busybox"
image: "registry.k8s.io/busybox"
command: ["/bin/sh", "-c", "test -e /scrub && rm -rf /scrub/..?* /scrub/.[!.]* /scrub/* && test -z \"$(ls -A /scrub)\" || exit 1"]
volumeMounts:
- name: vol

View File

@ -113,7 +113,7 @@ metadata:
name: test-ebs
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /test-ebs
@ -190,7 +190,7 @@ metadata:
name: test-cinder
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-cinder-container
volumeMounts:
- mountPath: /test-cinder
@ -294,7 +294,7 @@ metadata:
name: test-pd
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /cache
@ -369,7 +369,7 @@ metadata:
name: test-pd
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /test-pd
@ -509,7 +509,7 @@ metadata:
name: test-pd
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /test-pd
@ -759,7 +759,7 @@ metadata:
name: test-portworx-volume-pod
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /mnt
@ -824,7 +824,7 @@ metadata:
name: pod-0
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: pod-0
volumeMounts:
- mountPath: /test-pd
@ -953,7 +953,7 @@ metadata:
name: test-vmdk
spec:
containers:
- image: k8s.gcr.io/test-webserver
- image: registry.k8s.io/test-webserver
name: test-container
volumeMounts:
- mountPath: /test-vmdk

View File

@ -78,7 +78,7 @@ spec:
terminationGracePeriodSeconds: 10
containers:
- name: nginx
image: k8s.gcr.io/nginx-slim:0.8
image: registry.k8s.io/nginx-slim:0.8
ports:
- containerPort: 80
name: web

View File

@ -329,7 +329,7 @@ spec:
containers:
- args:
- /server
image: k8s.gcr.io/liveness
image: registry.k8s.io/liveness
livenessProbe:
httpGet:
# lorsque "host" n'est pas défini, "PodIP" sera utilisé

View File

@ -48,7 +48,7 @@ cd <fed-base>
hack/update-federation-api-reference-docs.sh
```
Le script exécute le [k8s.gcr.io/gen-swagger-docs](https://console.cloud.google.com/gcr/images/google-containers/GLOBAL/gen-swagger-docs?gcrImageListquery=%255B%255D&gcrImageListpage=%257B%2522t%2522%253A%2522%2522%252C%2522i%2522%253A0%257D&gcrImageListsize=50&gcrImageListsort=%255B%257B%2522p%2522%253A%2522uploaded%2522%252C%2522s%2522%253Afalse%257D%255D) image pour générer cet ensemble de documents de référence:
Le script exécute le [registry.k8s.io/gen-swagger-docs](https://console.cloud.google.com/gcr/images/google-containers/GLOBAL/gen-swagger-docs?gcrImageListquery=%255B%255D&gcrImageListpage=%257B%2522t%2522%253A%2522%2522%252C%2522i%2522%253A0%257D&gcrImageListsize=50&gcrImageListsort=%255B%257B%2522p%2522%253A%2522uploaded%2522%252C%2522s%2522%253Afalse%257D%255D) image pour générer cet ensemble de documents de référence:
* /docs/api-reference/extensions/v1beta1/operations.html
* /docs/api-reference/extensions/v1beta1/definitions.html

View File

@ -359,8 +359,8 @@ Exemples utilisant `-o=custom-columns` :
# Toutes les images s'exécutant dans un cluster
kubectl get pods -A -o=custom-columns='DATA:spec.containers[*].image'
# Toutes les images excepté "k8s.gcr.io/coredns:1.6.2"
kubectl get pods -A -o=custom-columns='DATA:spec.containers[?(@.image!="k8s.gcr.io/coredns:1.6.2")].image'
# Toutes les images excepté "registry.k8s.io/coredns:1.6.2"
kubectl get pods -A -o=custom-columns='DATA:spec.containers[?(@.image!="registry.k8s.io/coredns:1.6.2")].image'
# Tous les champs dans metadata quel que soit leur nom
kubectl get pods -A -o=custom-columns='DATA:metadata.*'

View File

@ -62,7 +62,7 @@ kubeadm init [flags]
--feature-gates string Un ensemble de paires clef=valeur qui décrivent l'entrée de configuration pour des fonctionnalités diverses. Il n'y en a aucune dans cette version.
-h, --help aide pour l'initialisation (init)
--ignore-preflight-errors strings Une liste de contrôles dont les erreurs seront catégorisées comme "warnings" (avertissements). Par exemple : 'IsPrivilegedUser,Swap'. La valeur 'all' ignore les erreurs de tous les contrôles.
--image-repository string Choisis un container registry d'où télécharger les images du control plane. (par défaut "k8s.gcr.io")
--image-repository string Choisis un container registry d'où télécharger les images du control plane. (par défaut "registry.k8s.io")
--kubernetes-version string Choisis une version Kubernetes spécifique pour le control plane. (par défaut "stable-1")
--node-name string Spécifie le nom du noeud.
--pod-network-cidr string Spécifie l'intervalle des adresses IP pour le réseau des pods. Si fournie, le control plane allouera automatiquement les CIDRs pour chacun des noeuds.

View File

@ -131,12 +131,12 @@ Pour de l'information sur comment passer des options aux composants du control p
### Utiliser des images personnalisées {#custom-images}
Par défaut, kubeadm télécharge les images depuis `k8s.gcr.io`, à moins que la version demandée de Kubernetes soit une version Intégration Continue (CI). Dans ce cas, `gcr.io/k8s-staging-ci-images` est utilisé.
Par défaut, kubeadm télécharge les images depuis `registry.k8s.io`, à moins que la version demandée de Kubernetes soit une version Intégration Continue (CI). Dans ce cas, `gcr.io/k8s-staging-ci-images` est utilisé.
Vous pouvez outrepasser ce comportement en utilisant [kubeadm avec un fichier de configuration](#config-file).
Les personnalisations permises sont :
* fournir un `imageRepository` à utiliser à la place de `k8s.gcr.io`.
* fournir un `imageRepository` à utiliser à la place de `registry.k8s.io`.
* régler `useHyperKubeImage` à `true` pour utiliser l'image HyperKube.
* fournir un `imageRepository` et un `imageTag` pour etcd et l'extension (add-on) DNS.
@ -264,7 +264,7 @@ kubeadm config images list
kubeadm config images pull
```
A partir de Kubernetes 1.12, les images prefixées par `k8s.gcr.io/kube-*`, `k8s.gcr.io/etcd` et `k8s.gcr.io/pause`
A partir de Kubernetes 1.12, les images prefixées par `registry.k8s.io/kube-*`, `registry.k8s.io/etcd` et `registry.k8s.io/pause`
ne nécessitent pas un suffix `-${ARCH}`.
### Automatiser kubeadm

View File

@ -56,7 +56,7 @@ Suivez les étapes ci-dessous pour commencer et explorer Minikube.
Créons un déploiement Kubernetes en utilisant une image existante nommée `echoserver`, qui est un serveur HTTP, et exposez-la sur le port 8080 à laide de `--port`.
```shell
kubectl create deployment hello-minikube --image=k8s.gcr.io/echoserver:1.10
kubectl create deployment hello-minikube --image=registry.k8s.io/echoserver:1.10
```
Le résultat est similaire à ceci:

View File

@ -29,7 +29,7 @@ L'interface utilisateur du tableau de bord n'est pas déployée par défaut.
Pour le déployer, exécutez la commande suivante:
```text
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/master/aio/deploy/recommended.yaml
kubectl apply -f https://raw.githubusercontent.com/kubernetes/dashboard/master/charts/recommended.yaml
```
## Accès à l'interface utilisateur du tableau de bord

View File

@ -27,7 +27,7 @@ Cela peut être utilisé dans le cas des liveness checks sur les conteneurs à d
De nombreuses applications fonctionnant pour des longues périodes finissent par passer à des états de rupture et ne peuvent pas se rétablir, sauf en étant redémarrées. Kubernetes fournit des liveness probes pour détecter et remédier à ces situations.
Dans cet exercice, vous allez créer un Pod qui exécute un conteneur basé sur l'image `k8s.gcr.io/busybox`. Voici le fichier de configuration pour le Pod :
Dans cet exercice, vous allez créer un Pod qui exécute un conteneur basé sur l'image `registry.k8s.io/busybox`. Voici le fichier de configuration pour le Pod :
{{< codenew file="pods/probe/exec-liveness.yaml" >}}
@ -61,8 +61,8 @@ La sortie indique qu'aucune liveness probe n'a encore échoué :
FirstSeen LastSeen Count From SubobjectPath Type Reason Message
--------- -------- ----- ---- ------------- -------- ------ -------
24s 24s 1 {default-scheduler } Normal Scheduled Successfully assigned liveness-exec to worker0
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Pulling pulling image "k8s.gcr.io/busybox"
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Pulled Successfully pulled image "k8s.gcr.io/busybox"
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Pulling pulling image "registry.k8s.io/busybox"
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Pulled Successfully pulled image "registry.k8s.io/busybox"
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Created Created container with docker id 86849c15382e; Security:[seccomp=unconfined]
23s 23s 1 {kubelet worker0} spec.containers{liveness} Normal Started Started container with docker id 86849c15382e
```
@ -79,8 +79,8 @@ Au bas de la sortie, il y a des messages indiquant que les liveness probes ont
FirstSeen LastSeen Count From SubobjectPath Type Reason Message
--------- -------- ----- ---- ------------- -------- ------ -------
37s 37s 1 {default-scheduler } Normal Scheduled Successfully assigned liveness-exec to worker0
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Pulling pulling image "k8s.gcr.io/busybox"
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Pulled Successfully pulled image "k8s.gcr.io/busybox"
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Pulling pulling image "registry.k8s.io/busybox"
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Pulled Successfully pulled image "registry.k8s.io/busybox"
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Created Created container with docker id 86849c15382e; Security:[seccomp=unconfined]
36s 36s 1 {kubelet worker0} spec.containers{liveness} Normal Started Started container with docker id 86849c15382e
2s 2s 1 {kubelet worker0} spec.containers{liveness} Warning Unhealthy Liveness probe failed: cat: can't open '/tmp/healthy': No such file or directory
@ -102,7 +102,7 @@ liveness-exec 1/1 Running 1 1m
## Définir une requête HTTP de liveness
Un autre type de liveness probe utilise une requête GET HTTP. Voici la configuration
d'un Pod qui fait fonctionner un conteneur basé sur l'image `k8s.gcr.io/liveness`.
d'un Pod qui fait fonctionner un conteneur basé sur l'image `registry.k8s.io/liveness`.
{{< codenew file="pods/probe/http-liveness.yaml" >}}

View File

@ -45,7 +45,7 @@ Voici le fichier de configuration du Pod :
La sortie ressemble à ceci :
```shell
```console
NAME READY STATUS RESTARTS AGE
redis 1/1 Running 0 13s
```
@ -73,7 +73,7 @@ Voici le fichier de configuration du Pod :
La sortie ressemble à ceci :
```shell
```console
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
redis 1 0.1 0.1 33308 3828 ? Ssl 00:46 0:00 redis-server *:6379
root 12 0.0 0.0 20228 3020 ? Ss 00:47 0:00 /bin/bash
@ -91,7 +91,7 @@ Voici le fichier de configuration du Pod :
1. Dans votre terminal initial, surveillez les changements apportés au Pod de Redis. Éventuellement,
vous verrez quelque chose comme ça :
```shell
```console
NAME READY STATUS RESTARTS AGE
redis 1/1 Running 0 13s
redis 0/1 Completed 0 6m

View File

@ -100,7 +100,7 @@ En quelques étapes, nous vous emmenons de Docker Compose à Kubernetes. Tous do
services:
redis-master:
image: k8s.gcr.io/redis:e2e
image: registry.k8s.io/redis:e2e
ports:
- "6379"

View File

@ -0,0 +1,112 @@
---
title: Définir des variables d'environnement pour un Container
content_type: task
weight: 20
---
<!-- overview -->
Cette page montre comment définir des variables d'environnement pour un
container au sein d'un Pod Kubernetes.
## {{% heading "prerequisites" %}}
{{< include "task-tutorial-prereqs.md" >}}
<!-- steps -->
## Définir une variable d'environnement pour un container
Lorsque vous créez un Pod, vous pouvez définir des variables d'environnement
pour les containers qui seront exécutés au sein du Pod.
Pour les définir, utilisez le champ `env` ou `envFrom`
dans le fichier de configuration.
Dans cet exercice, vous allez créer un Pod qui exécute un container. Le fichier de configuration pour ce Pod contient une variable d'environnement s'appelant `DEMO_GREETING` et sa valeur est `"Hello from the environment"`. Voici le fichier de configuration du Pod:
{{< codenew file="pods/inject/envars.yaml" >}}
1. Créez un Pod à partir de ce fichier:
```shell
kubectl apply -f https://k8s.io/examples/pods/inject/envars.yaml
```
1. Listez les Pods:
```shell
kubectl get pods -l purpose=demonstrate-envars
```
Le résultat sera similaire à celui-ci:
```
NAME READY STATUS RESTARTS AGE
envar-demo 1/1 Running 0 9s
```
1. Listez les variables d'environnement au sein du container:
```shell
kubectl exec envar-demo -- printenv
```
Le résultat sera similaire à celui-ci:
```
NODE_VERSION=4.4.2
EXAMPLE_SERVICE_PORT_8080_TCP_ADDR=10.3.245.237
HOSTNAME=envar-demo
...
DEMO_GREETING=Hello from the environment
DEMO_FAREWELL=Such a sweet sorrow
```
{{< note >}}
Les variables d'environnement définies dans les champs `env` ou `envFrom`
écraseront les variables définies dans l'image utilisée par le container.
{{< /note >}}
{{< note >}}
Une variable d'environnement peut faire référence à une autre variable,
cependant l'ordre de déclaration est important. Une variable faisant référence
à une autre doit être déclarée après la variable référencée.
De plus, il est recommandé d'éviter les références circulaires.
{{< /note >}}
## Utilisez des variables d'environnement dans la configuration
Les variables d'environnement que vous définissez dans la configuration d'un Pod peuvent être utilisées à d'autres endroits de la configuration, comme par exemple dans les commandes et arguments pour les containers.
Dans l'exemple ci-dessous, les variables d'environnement `GREETING`, `HONORIFIC`, et
`NAME` ont des valeurs respectives de `Warm greetings to`, `The Most
Honorable`, et `Kubernetes`. Ces variables sont ensuites utilisées comme arguments
pour le container `env-print-demo`.
```yaml
apiVersion: v1
kind: Pod
metadata:
name: print-greeting
spec:
containers:
- name: env-print-demo
image: bash
env:
- name: GREETING
value: "Warm greetings to"
- name: HONORIFIC
value: "The Most Honorable"
- name: NAME
value: "Kubernetes"
command: ["echo"]
args: ["$(GREETING) $(HONORIFIC) $(NAME)"]
```
Une fois le Pod créé, la commande `echo Warm greetings to The Most Honorable Kubernetes` sera exécutée dans le container.
## {{% heading "whatsnext" %}}
* En savoir plus sur les [variables d'environnement](/docs/tasks/inject-data-application/environment-variable-expose-pod-information/).
* Apprendre à [utiliser des secrets comme variables d'environnement](/docs/concepts/configuration/secret/#using-secrets-as-environment-variables).
* Voir la documentation de référence pour [EnvVarSource](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#envvarsource-v1-core).

View File

@ -0,0 +1,355 @@
---
title: Distribuer des données sensibles de manière sécurisée avec les Secrets
content_type: task
weight: 50
min-kubernetes-server-version: v1.6
---
<!-- overview -->
Cette page montre comment injecter des données sensibles comme des mots de passe ou des clés de chiffrement dans des Pods.
## {{% heading "prerequisites" %}}
{{< include "task-tutorial-prereqs.md" >}}
### Encoder vos données en format base64
Supposons que vous avez deux données sensibles: un identifiant `my-app` et un
mot de passe
`39528$vdg7Jb`. Premièrement, utilisez un outil capable d'encoder vos données
dans un format base64. Voici un exemple en utilisant le programme base64:
```shell
echo -n 'my-app' | base64
echo -n '39528$vdg7Jb' | base64
```
Le résultat montre que la représentation base64 de l'utilisateur est `bXktYXBw`,
et que la représentation base64 du mot de passe est `Mzk1MjgkdmRnN0pi`.
{{< caution >}}
Utilisez un outil local approuvé par votre système d'exploitation
afin de réduire les risques de sécurité liés à l'utilisation d'un outil externe.
{{< /caution >}}
<!-- steps -->
## Créer un Secret
Voici un fichier de configuration que vous pouvez utiliser pour créer un Secret
qui contiendra votre identifiant et mot de passe:
{{< codenew file="pods/inject/secret.yaml" >}}
1. Créez le Secret:
```shell
kubectl apply -f https://k8s.io/examples/pods/inject/secret.yaml
```
1. Listez les informations du Secret:
```shell
kubectl get secret test-secret
```
Résultat:
```
NAME TYPE DATA AGE
test-secret Opaque 2 1m
```
1. Affichez les informations détaillées du Secret:
```shell
kubectl describe secret test-secret
```
Résultat:
```
Name: test-secret
Namespace: default
Labels: <none>
Annotations: <none>
Type: Opaque
Data
====
password: 13 bytes
username: 7 bytes
```
### Créer un Secret en utilisant kubectl
Si vous voulez sauter l'étape d'encodage, vous pouvez créer le même Secret
en utilisant la commande `kubectl create secret`. Par exemple:
```shell
kubectl create secret generic test-secret --from-literal='username=my-app' --from-literal='password=39528$vdg7Jb'
```
Cette approche est plus pratique. La façon de faire plus explicite
montrée précédemment permet de démontrer et comprendre le fonctionnement des Secrets.
## Créer un Pod qui a accès aux données sensibles à travers un Volume
Voici un fichier de configuration qui permet de créer un Pod:
{{< codenew file="pods/inject/secret-pod.yaml" >}}
1. Créez le Pod:
```shell
kubectl apply -f https://k8s.io/examples/pods/inject/secret-pod.yaml
```
1. Vérifiez que le Pod est opérationnel:
```shell
kubectl get pod secret-test-pod
```
Résultat:
```
NAME READY STATUS RESTARTS AGE
secret-test-pod 1/1 Running 0 42m
```
1. Exécutez une session shell dans le Container qui est dans votre Pod:
```shell
kubectl exec -i -t secret-test-pod -- /bin/bash
```
1. Les données sont exposées au container à travers un Volume monté sur
`/etc/secret-volume`.
Dans votre shell, listez les fichiers du dossier `/etc/secret-volume`:
```shell
# À exécuter à l'intérieur du container
ls /etc/secret-volume
```
Le résultat montre deux fichiers, un pour chaque donnée du Secret:
```
password username
```
1. Toujours dans le shell, affichez le contenu des fichiers
`username` et `password`:
```shell
# À exécuter à l'intérieur du container
echo "$( cat /etc/secret-volume/username )"
echo "$( cat /etc/secret-volume/password )"
```
Le résultat doit contenir votre identifiant et mot de passe:
```
my-app
39528$vdg7Jb
```
Vous pouvez alors modifier votre image ou votre ligne de commande pour que le programme
recherche les fichiers contenus dans le dossier du champ `mountPath`.
Chaque clé du Secret `data` sera exposée comme un fichier à l'intérieur de ce dossier.
### Monter les données du Secret sur des chemins spécifiques
Vous pouvez contrôler les chemins sur lesquels les données des Secrets sont montées.
Utilisez le champ `.spec.volumes[].secret.items` pour changer le
chemin cible de chaque donnée:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mypod
image: redis
volumeMounts:
- name: foo
mountPath: "/etc/foo"
readOnly: true
volumes:
- name: foo
secret:
secretName: mysecret
items:
- key: username
path: my-group/my-username
```
Voici ce qu'il se passe lorsque vous déployez ce Pod:
* La clé `username` du Secret `mysecret` est montée dans le container sur le chemin
`/etc/foo/my-group/my-username` au lieu de `/etc/foo/username`.
* La clé `password` du Secret n'est pas montée dans le container.
Si vous listez de manière explicite les clés en utilisant le champ `.spec.volumes[].secret.items`,
il est important de prendre en considération les points suivants:
* Seules les clés listées dans le champ `items` seront montées.
* Pour monter toutes les clés du Secret, toutes doivent être
définies dans le champ `items`.
* Toutes les clés définies doivent exister dans le Secret.
Sinon, le volume ne sera pas créé.
### Appliquer des permissions POSIX aux données
Vous pouvez appliquer des permissions POSIX pour une clé d'un Secret. Si vous n'en configurez pas, les permissions seront par défaut `0644`.
Vous pouvez aussi définir des permissions pour tout un Secret, et redéfinir les permissions pour chaque clé si nécessaire.
Par exemple, il est possible de définir un mode par défaut:
```yaml
apiVersion: v1
kind: Pod
metadata:
name: mypod
spec:
containers:
- name: mypod
image: redis
volumeMounts:
- name: foo
mountPath: "/etc/foo"
volumes:
- name: foo
secret:
secretName: mysecret
defaultMode: 0400
```
Le Secret sera monté sur `/etc/foo`; tous les fichiers créés par le secret
auront des permissions de type `0400`.
{{< note >}}
Si vous définissez un Pod en utilisant le format JSON, il est important de
noter que la spécification JSON ne supporte pas le système octal, et qu'elle
comprendra la valeur `0400` comme la valeur _décimale_ `400`.
En JSON, utilisez plutôt l'écriture décimale pour le champ `defaultMode`.
Si vous utilisez le format YAML, vous pouvez utiliser le système octal
pour définir `defaultMode`.
{{< /note >}}
## Définir des variables d'environnement avec des Secrets
Il est possible de monter les données des Secrets comme variables d'environnement dans vos containers.
Si un container consomme déja un Secret en variables d'environnement,
la mise à jour de ce Secret ne sera pas répercutée dans le container tant
qu'il n'aura pas été redémarré. Il existe cependant des solutions tierces
permettant de redémarrer les containers lors d'une mise à jour du Secret.
### Définir une variable d'environnement à partir d'un seul Secret
* Définissez une variable d'environnement et sa valeur à l'intérieur d'un Secret:
```shell
kubectl create secret generic backend-user --from-literal=backend-username='backend-admin'
```
* Assignez la valeur de `backend-username` définie dans le Secret
à la variable d'environnement `SECRET_USERNAME` dans la configuration du Pod.
{{< codenew file="pods/inject/pod-single-secret-env-variable.yaml" >}}
* Créez le Pod:
```shell
kubectl create -f https://k8s.io/examples/pods/inject/pod-single-secret-env-variable.yaml
```
* À l'intérieur d'une session shell, affichez le contenu de la variable
d'environnement `SECRET_USERNAME`:
```shell
kubectl exec -i -t env-single-secret -- /bin/sh -c 'echo $SECRET_USERNAME'
```
Le résultat est:
```
backend-admin
```
### Définir des variables d'environnement à partir de plusieurs Secrets
* Comme précédemment, créez d'abord les Secrets:
```shell
kubectl create secret generic backend-user --from-literal=backend-username='backend-admin'
kubectl create secret generic db-user --from-literal=db-username='db-admin'
```
* Définissez les variables d'environnement dans la configuration du Pod.
{{< codenew file="pods/inject/pod-multiple-secret-env-variable.yaml" >}}
* Créez le Pod:
```shell
kubectl create -f https://k8s.io/examples/pods/inject/pod-multiple-secret-env-variable.yaml
```
* Dans un shell, listez les variables d'environnement du container:
```shell
kubectl exec -i -t envvars-multiple-secrets -- /bin/sh -c 'env | grep _USERNAME'
```
Le résultat est:
```
DB_USERNAME=db-admin
BACKEND_USERNAME=backend-admin
```
## Configurez toutes les paires de clé-valeur d'un Secret comme variables d'environnement
{{< note >}}
Cette fonctionnalité n'est disponible que dans les versions de Kubernetes
égales ou supérieures à v1.6.
{{< /note >}}
* Créez un Secret contenant plusieurs paires de clé-valeur:
```shell
kubectl create secret generic test-secret --from-literal=username='my-app' --from-literal=password='39528$vdg7Jb'
```
* Utilisez `envFrom` pour définir toutes les données du Secret comme variables
d'environnement. Les clés du Secret deviendront les noms des variables
d'environnement à l'intérieur du Pod.
{{< codenew file="pods/inject/pod-secret-envFrom.yaml" >}}
* Créez le Pod:
```shell
kubectl create -f https://k8s.io/examples/pods/inject/pod-secret-envFrom.yaml
```
* Dans votre shell, affichez les variables d'environnement `username` et `password`:
```shell
kubectl exec -i -t envfrom-secret -- /bin/sh -c 'echo "username: $username\npassword: $password\n"'
```
Le résultat est:
```
username: my-app
password: 39528$vdg7Jb
```
### Références
* [Secret](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#secret-v1-core)
* [Volume](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#volume-v1-core)
* [Pod](/docs/reference/generated/kubernetes-api/{{< param "version" >}}/#pod-v1-core)
## {{% heading "whatsnext" %}}
* En savoir plus sur les [Secrets](/docs/concepts/configuration/secret/).
* En savoir plus sur les [Volumes](/docs/concepts/storage/volumes/).

View File

@ -78,7 +78,7 @@ Les déploiements sont le moyen recommandé pour gérer la création et la mise
Pod utilise un conteneur basé sur l'image Docker fournie.
```shell
kubectl create deployment hello-node --image=k8s.gcr.io/echoserver:1.4
kubectl create deployment hello-node --image=registry.k8s.io/echoserver:1.4
```
2. Affichez le déploiement :

View File

@ -41,9 +41,9 @@ spec:
serviceAccountName: cloud-controller-manager
containers:
- name: cloud-controller-manager
# pour les fournisseurs in-tree, nous utilisons k8s.gcr.io/cloud-controller-manager
# pour les fournisseurs in-tree, nous utilisons registry.k8s.io/cloud-controller-manager
# cela peut être remplacé par n'importe quelle autre image pour les fournisseurs out-of-tree
image: k8s.gcr.io/cloud-controller-manager:v1.8.0
image: registry.k8s.io/cloud-controller-manager:v1.8.0
command:
- /usr/local/bin/cloud-controller-manager
- --cloud-provider=<YOUR_CLOUD_PROVIDER> # Ajoutez votre propre fournisseur de cloud ici!

View File

@ -22,7 +22,7 @@ spec:
- name: varlog
mountPath: /var/log
- name: count-agent
image: k8s.gcr.io/fluentd-gcp:1.30
image: registry.k8s.io/fluentd-gcp:1.30
env:
- name: FLUENTD_ARGS
value: -c /etc/fluentd-config/fluentd.conf

View File

@ -20,7 +20,7 @@ spec:
spec:
containers:
- name: master
image: k8s.gcr.io/redis:e2e # or just image: redis
image: registry.k8s.io/redis:e2e # or just image: redis
resources:
requests:
cpu: 100m

View File

@ -0,0 +1,15 @@
apiVersion: v1
kind: Pod
metadata:
name: envar-demo
labels:
purpose: demonstrate-envars
spec:
containers:
- name: envar-demo-container
image: gcr.io/google-samples/node-hello:1.0
env:
- name: DEMO_GREETING
value: "Hello from the environment"
- name: DEMO_FAREWELL
value: "Such a sweet sorrow"

View File

@ -0,0 +1,19 @@
apiVersion: v1
kind: Pod
metadata:
name: envvars-multiple-secrets
spec:
containers:
- name: envars-test-container
image: nginx
env:
- name: BACKEND_USERNAME
valueFrom:
secretKeyRef:
name: backend-user
key: backend-username
- name: DB_USERNAME
valueFrom:
secretKeyRef:
name: db-user
key: db-username

View File

@ -0,0 +1,11 @@
apiVersion: v1
kind: Pod
metadata:
name: envfrom-secret
spec:
containers:
- name: envars-test-container
image: nginx
envFrom:
- secretRef:
name: test-secret

View File

@ -0,0 +1,14 @@
apiVersion: v1
kind: Pod
metadata:
name: env-single-secret
spec:
containers:
- name: envars-test-container
image: nginx
env:
- name: SECRET_USERNAME
valueFrom:
secretKeyRef:
name: backend-user
key: backend-username

View File

@ -0,0 +1,19 @@
apiVersion: v1
kind: Pod
metadata:
name: secret-envars-test-pod
spec:
containers:
- name: envars-test-container
image: nginx
env:
- name: SECRET_USERNAME
valueFrom:
secretKeyRef:
name: test-secret
key: username
- name: SECRET_PASSWORD
valueFrom:
secretKeyRef:
name: test-secret
key: password

View File

@ -0,0 +1,18 @@
apiVersion: v1
kind: Pod
metadata:
name: secret-test-pod
spec:
containers:
- name: test-container
image: nginx
volumeMounts:
# name must match the volume name below
- name: secret-volume
mountPath: /etc/secret-volume
readOnly: true
# The secret data is exposed to Containers in the Pod through a Volume.
volumes:
- name: secret-volume
secret:
secretName: test-secret

View File

@ -0,0 +1,7 @@
apiVersion: v1
kind: Secret
metadata:
name: test-secret
data:
username: bXktYXBw
password: Mzk1MjgkdmRnN0pi

View File

@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
image: registry.k8s.io/busybox
command: [ "/bin/echo", "$(SPECIAL_LEVEL_KEY) $(SPECIAL_TYPE_KEY)" ]
env:
- name: SPECIAL_LEVEL_KEY

View File

@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
image: registry.k8s.io/busybox
command: [ "/bin/sh", "-c", "env" ]
envFrom:
- configMapRef:

View File

@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
image: registry.k8s.io/busybox
command: [ "/bin/sh","-c","cat /etc/config/keys" ]
volumeMounts:
- name: config-volume

View File

@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
image: registry.k8s.io/busybox
command: [ "/bin/sh", "-c", "ls /etc/config/" ]
volumeMounts:
- name: config-volume

View File

@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
image: registry.k8s.io/busybox
command: [ "/bin/sh", "-c", "env" ]
env:
- name: SPECIAL_LEVEL_KEY

View File

@ -5,7 +5,7 @@ metadata:
spec:
containers:
- name: test-container
image: k8s.gcr.io/busybox
image: registry.k8s.io/busybox
command: [ "/bin/sh", "-c", "env" ]
env:
# Définie la variable d'environnement

View File

@ -7,7 +7,7 @@ metadata:
spec:
containers:
- name: liveness
image: k8s.gcr.io/busybox
image: registry.k8s.io/busybox
args:
- /bin/sh
- -c

View File

@ -7,7 +7,7 @@ metadata:
spec:
containers:
- name: liveness
image: k8s.gcr.io/liveness
image: registry.k8s.io/liveness
args:
- /server
livenessProbe:

View File

@ -7,7 +7,7 @@ metadata:
spec:
containers:
- name: goproxy
image: k8s.gcr.io/goproxy:0.1
image: registry.k8s.io/goproxy:0.1
ports:
- containerPort: 8080
readinessProbe:

View File

@ -23,4 +23,4 @@ spec:
- zoneC
containers:
- name: pause
image: k8s.gcr.io/pause:3.1
image: registry.k8s.io/pause:3.1

View File

@ -14,4 +14,4 @@ spec:
foo: bar
containers:
- name: pause
image: k8s.gcr.io/pause:3.1
image: registry.k8s.io/pause:3.1

View File

@ -20,4 +20,4 @@ spec:
foo: bar
containers:
- name: pause
image: k8s.gcr.io/pause:3.1
image: registry.k8s.io/pause:3.1

View File

@ -43,12 +43,12 @@ sitemap:
<button id="desktopShowVideoButton" onclick="kub.showVideo()">वीडियो देखें</button>
<br>
<br>
<a href="https://events.linuxfoundation.org/kubecon-cloudnativecon-north-america/?utm_source=kubernetes.io&utm_medium=nav&utm_campaign=kccncna21" button id="desktopKCButton">अक्टूबर 11-15, 2021 को KubeCon North America में भाग लें</a>
<a href="https://events.linuxfoundation.org/kubecon-cloudnativecon-europe/" button id="desktopKCButton">अप्रैल 18-21, 2023 KubeCon + CloudNativeCon Europe में भाग लें</a>
<br>
<br>
<br>
<br>
<a href="https://events.linuxfoundation.org/kubecon-cloudnativecon-europe-2022/?utm_source=kubernetes.io&utm_medium=nav&utm_campaign=kccnceu22" button id="desktopKCButton">मई 17-20, 2022 को KubeCon Europe में भाग लें</a>
<a href="https://events.linuxfoundation.org/kubecon-cloudnativecon-north-america/" button id="desktopKCButton">6-9 नवंबर, 2023 को KubeCon + CloudNativeCon North America में भाग लें</a>
</div>
<div id="videoPlayer">
<iframe data-url="https://www.youtube.com/embed/H06qrNmGqyE?autoplay=1" frameborder="0" allowfullscreen></iframe>

View File

@ -54,7 +54,7 @@ Windows पर kubectl संस्थापित करने के लिए
- `True` या `False` परिणाम प्राप्त करने के लिए `-eq` ऑपरेटर का उपयोग करके सत्यापन को ऑटोमेट करने के लिए powershell का उपयोग करें:
```powershell
$($(CertUtil -hashfile .\kubectl.exe SHA256)[1] -replace " ", "") -eq $(type .\kubectl.exe.sha256)
$(Get-FileHash -Algorithm SHA256 .\kubectl.exe).Hash -eq $(Get-Content .\kubectl.exe.sha256)
```
1. अपने `PATH` में बाइनरी जोड़ें।

View File

@ -41,7 +41,7 @@ yang tetap bertahan, meski Container berakhir dan dimulai ulang. Berikut berkas
Hasil keluaran seperti ini:
```shell
```console
NAME READY STATUS RESTARTS AGE
redis 1/1 Running 0 13s
```
@ -69,7 +69,7 @@ yang tetap bertahan, meski Container berakhir dan dimulai ulang. Berikut berkas
Keluarannya mirip seperti ini:
```shell
```console
USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND
redis 1 0.1 0.1 33308 3828 ? Ssl 00:46 0:00 redis-server *:6379
root 12 0.0 0.0 20228 3020 ? Ss 00:47 0:00 /bin/bash
@ -86,7 +86,7 @@ yang tetap bertahan, meski Container berakhir dan dimulai ulang. Berikut berkas
2. Di dalam terminal awal, amati perubahan terhadap Pod Redis. Sampai akhirnya kamu akan melihat hal seperti ini:
```shell
```console
NAME READY STATUS RESTARTS AGE
redis 1/1 Running 0 13s
redis 0/1 Completed 0 6m

16
content/ja/blog/_index.md Normal file
View File

@ -0,0 +1,16 @@
---
title: Kubernetesブログ
linkTitle: ブログ
menu:
main:
title: "ブログ"
weight: 40
post: >
<p>Kubernetesやコンテナ全般に関する最新ニュースを読んで、技術的なハウツーをいち早く入手しましょう。</p>
---
{{< comment >}}
ブログへの寄稿についての情報は、以下を参照してください
https://kubernetes.io/docs/contribute/new-content/blogs-case-studies/#write-a-blog-post
{{< /comment >}}

View File

@ -49,7 +49,7 @@ Kubernetesクラスターの計画、セットアップ、設定の例を知る
* [Kubernetesクラスターでのsysctlの使用](/docs/concepts/cluster-administration/sysctl-cluster/)では、管理者向けにカーネルパラメーターを設定するため`sysctl`コマンドラインツールの使用方法について解説します。
* [クラスターの監査](/docs/tasks/debug-application-cluster/audit/)では、Kubernetesの監査ログの扱い方について解説します。
* [クラスターの監査](/ja/docs/tasks/debug/debug-cluster/audit/)では、Kubernetesの監査ログの扱い方について解説します。
### kubeletをセキュアにする
* [マスターとノードのコミュニケーション](/ja/docs/concepts/architecture/master-node-communication/)
@ -61,7 +61,3 @@ Kubernetesクラスターの計画、セットアップ、設定の例を知る
* [DNSのインテグレーション](/ja/docs/concepts/services-networking/dns-pod-service/)では、DNS名をKubernetes Serviceに直接名前解決する方法を解説します。
* [クラスターアクティビィのロギングと監視](/docs/concepts/cluster-administration/logging/)では、Kubernetesにおけるロギングがどのように行われ、どう実装されているかについて解説します。

View File

@ -1,6 +1,6 @@
---
reviewers:
-
-
title: リソースの管理
content_type: concept
weight: 40
@ -157,7 +157,7 @@ deployment.apps/my-deployment created
persistentvolumeclaim/my-pvc created
```
`kubectl`についてさらに知りたい場合は、[kubectlの概要](/ja/docs/reference/kubectl/overview/)を参照してください。
`kubectl`についてさらに知りたい場合は、[コマンドラインツール(kubectl)](/ja/docs/reference/kubectl/)を参照してください。
## ラベルを有効に使う
@ -449,6 +449,5 @@ kubectl edit deployment/my-nginx
## {{% heading "whatsnext" %}}
- [アプリケーションの調査とデバッグのための`kubectl`の使用方法](/docs/tasks/debug-application-cluster/debug-application-introspection/)について学んでください。
- [アプリケーションの調査とデバッグのための`kubectl`の使用方法](/ja/docs/tasks/debug/debug-application/debug-running-pod/)について学んでください。
- [設定のベストプラクティスとTIPS](/ja/docs/concepts/configuration/overview/)を参照してください。

View File

@ -170,7 +170,7 @@ Dockerを使用する場合:
Podのリソース使用量は、Podのステータスの一部として報告されます。
オプションの[監視ツール](/docs/tasks/debug-application-cluster/resource-usage-monitoring/)がクラスターにおいて利用可能な場合、Podのリソース使用量は[メトリクスAPI](/docs/tasks/debug-application-cluster/resource-metrics-pipeline/#the-metrics-api)から直接、もしくは監視ツールから取得できます。
オプションの[監視ツール](/ja/docs/tasks/debug/debug-cluster/resource-usage-monitoring/)がクラスターにおいて利用可能な場合、Podのリソース使用量は[メトリクスAPI](/ja/docs/tasks/debug/debug-cluster/resource-metrics-pipeline/#the-metrics-api)から直接、もしくは監視ツールから取得できます。
## ローカルのエフェメラルストレージ {#local-ephemeral-storage}

View File

@ -18,7 +18,7 @@ weight: 10
*カスタムリソース* は、Kubernetes APIの拡張で、デフォルトのKubernetesインストールでは、必ずしも利用できるとは限りません。つまりそれは、特定のKubernetesインストールのカスタマイズを表します。しかし、今現在、多数のKubernetesのコア機能は、カスタムリソースを用いて作られており、Kubernetesをモジュール化しています。
カスタムリソースは、稼働しているクラスターに動的に登録され、現れたり、消えたりし、クラスター管理者はクラスター自体とは無関係にカスタムリソースを更新できます。一度、カスタムリソースがインストールされると、ユーザーは[kubectl](/ja/docs/reference/kubectl/overview/)を使い、ビルトインのリソースである *Pods* と同じように、オブジェクトを作成、アクセスすることが可能です。
カスタムリソースは、稼働しているクラスターに動的に登録され、現れたり、消えたりし、クラスター管理者はクラスター自体とは無関係にカスタムリソースを更新できます。一度、カスタムリソースがインストールされると、ユーザーは[kubectl](/ja/docs/reference/kubectl/)を使い、ビルトインのリソースである *Pods* と同じように、オブジェクトを作成、アクセスすることが可能です。
## カスタムコントローラー

View File

@ -18,7 +18,7 @@ APIサーバーは、エンドユーザー、クラスターのさまざまな
Kubernetes APIを使用すると、Kubernetes API内のオブジェクトの状態をクエリで操作できますPod、Namespace、ConfigMap、Events
ほとんどの操作は、APIを使用している[kubectl](/docs/reference/kubectl/overview/)コマンドラインインターフェースもしくは[kubeadm](/docs/reference/setup-tools/kubeadm/)のような別のコマンドラインツールを通して実行できます。
ほとんどの操作は、APIを使用している[kubectl](/ja/docs/reference/kubectl/)コマンドラインインターフェースもしくは[kubeadm](/docs/reference/setup-tools/kubeadm/)のような別のコマンドラインツールを通して実行できます。
RESTコールを利用して直接APIにアクセスすることも可能です。
Kubernetes APIを利用してアプリケーションを書いているのであれば、[client libraries](/docs/reference/using-api/client-libraries/)の利用を考えてみてください。

View File

@ -22,9 +22,9 @@ DaemonSetのいくつかの典型的な使用例は以下の通りです。
<!-- body -->
## DaemonSet Specの記述
## DaemonSet Specの記述 {#writing-a-daemonset-spec}
### DaemonSetの作成
### DaemonSetの作成 {#create-a-daemonset}
ユーザーはYAMLファイル内でDaemonSetの設定を記述することができます。例えば、下記の`daemonset.yaml`ファイルでは`fluentd-elasticsearch`というDockerイメージを稼働させるDaemonSetの設定を記述します。
@ -36,7 +36,7 @@ YAMLファイルに基づいてDaemonSetを作成します。
kubectl apply -f https://k8s.io/examples/controllers/daemonset.yaml
```
### 必須のフィールド
### 必須のフィールド {#required-fields}
他の全てのKubernetesの設定と同様に、DaemonSetは`apiVersion`、`kind`と`metadata`フィールドが必須となります。設定ファイルの活用法に関する一般的な情報は、[ステートレスアプリケーションの稼働](/ja/docs/tasks/run-application/run-stateless-application-deployment/)、[コンテナの設定](/ja/docs/tasks/)、[kubectlを用いたオブジェクトの管理](/ja/docs/concepts/overview/working-with-objects/object-management/)といったドキュメントを参照ください。
@ -45,7 +45,7 @@ DaemonSetオブジェクトの名前は、有効な
また、DaemonSetにおいて[`.spec`](https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#spec-and-status)セクションも必須となります。
### Podテンプレート
### Podテンプレート {#pod-template}
`.spec.template`は`.spec`内での必須のフィールドの1つです。
@ -55,7 +55,7 @@ Podに対する必須のフィールドに加えて、DaemonSet内のPodテン
DaemonSet内のPodテンプレートでは、[`RestartPolicy`](/ja/docs/concepts/workloads/pods/pod-lifecycle/#restart-policy)フィールドを指定せずにデフォルトの`Always`を使用するか、明示的に`Always`を設定するかのどちらかである必要があります。
### Podセレクター
### Podセレクター {#pod-selector}
`.spec.selector`フィールドはPodセレクターとなります。これは[Job](/docs/concepts/workloads/controllers/job/)の`.spec.selector`と同じものです。
@ -70,14 +70,14 @@ Kubernetes1.8のように、ユーザーは`.spec.template`のラベルにマッ
もし`spec.selector`が指定されたとき、`.spec.template.metadata.labels`とマッチしなければなりません。この2つの値がマッチしない設定をした場合、APIによってリジェクトされます。
### 選択したNode上でPodを稼働させる
### 選択したNode上でPodを稼働させる {#running-pods-on-select-nodes}
もしユーザーが`.spec.template.spec.nodeSelector`を指定したとき、DaemonSetコントローラーは、その[node selector](/ja/docs/concepts/scheduling-eviction/assign-pod-node/)にマッチするNode上にPodを作成します。同様に、もし`.spec.template.spec.affinity`を指定したとき、DaemonSetコントローラーは[node affinity](/ja/docs/concepts/scheduling-eviction/assign-pod-node/)にマッチするNode上にPodを作成します。
もしユーザーがどちらも指定しないとき、DaemonSetコントローラーは全てのNode上にPodを作成します。
## Daemon Podがどのようにスケジューリングされるか
## Daemon Podがどのようにスケジューリングされるか {#how-daemon-pods-are-scheduled}
### デフォルトスケジューラーによってスケジューリングされる場合
### デフォルトスケジューラーによってスケジューリングされる場合 {#scheduled-by-default-scheduler}
{{< feature-state for_k8s_version="1.17" state="stable" >}}
@ -102,7 +102,7 @@ nodeAffinity:
さらに、`node.kubernetes.io/unschedulable:NoSchedule`というtolarationがDaemonSetのPodに自動的に追加されます。デフォルトスケジューラーは、DaemonSetのPodのスケジューリングのときに、`unschedulable`なNodeを無視します。
### TaintsとTolerations
### TaintsとTolerations {#taints-and-tolerations}
DaemonSetのPodは[TaintsとTolerations](/ja/docs/concepts/scheduling-eviction/taint-and-toleration/)の設定を尊重します。下記のTolerationsは、関連する機能によって自動的にDaemonSetのPodに追加されます。
@ -115,7 +115,7 @@ DaemonSetのPodは[TaintsとTolerations](/ja/docs/concepts/scheduling-eviction/t
| `node.kubernetes.io/unschedulable` | NoSchedule | 1.12+ | DaemonSetのPodはデフォルトスケジューラーによってスケジュール不可能な属性を許容(tolerate)します。 |
| `node.kubernetes.io/network-unavailable` | NoSchedule | 1.12+ | ホストネットワークを使うDaemonSetのPodはデフォルトスケジューラーによってネットワーク利用不可能な属性を許容(tolerate)します。 |
## Daemon Podとのコミュニケーション
## Daemon Podとのコミュニケーション {#communicating-with-daemon-pods}
DaemonSet内のPodとのコミュニケーションをする際に考えられるパターンは以下の通りです。:
@ -124,7 +124,7 @@ DaemonSet内のPodとのコミュニケーションをする際に考えられ
- **DNS**: 同じPodセレクターを持つ[HeadlessService](/ja/docs/concepts/services-networking/service/#headless-service)を作成し、`endpoints`リソースを使ってDaemonSetを探すか、DNSから複数のAレコードを取得します。
- **Service**: 同じPodセレクターを持つServiceを作成し、複数のうちのいずれかのNode上のDaemonに疎通させるためにそのServiceを使います。
## DaemonSetの更新
## DaemonSetの更新 {#updating-a-daemonset}
もしNodeラベルが変更されたとき、そのDaemonSetは直ちに新しくマッチしたNodeにPodを追加し、マッチしなくなったNodeからPodを削除します。
@ -134,9 +134,9 @@ DaemonSet内のPodとのコミュニケーションをする際に考えられ
ユーザーはDaemonSet上で[ローリングアップデートの実施](/docs/tasks/manage-daemon/update-daemon-set/)が可能です。
## DaemonSetの代替案
## DaemonSetの代替案 {#alternatives-to-daemonset}
### Initスクリプト
### Initスクリプト {#init-scripts}
Node上で直接起動することにより(例: `init`、`upstartd`、`systemd`を使用する)、デーモンプロセスを稼働することが可能です。この方法は非常に良いですが、このようなプロセスをDaemonSetを介して起動することはいくつかの利点があります。
@ -144,15 +144,15 @@ Node上で直接起動することにより(例: `init`、`upstartd`、`systemd`
- デーモンとアプリケーションで同じ設定用の言語とツール(例: Podテンプレート、`kubectl`)を使える。
- リソースリミットを使ったコンテナ内でデーモンを稼働させることにより、デーモンとアプリケーションコンテナの分離を促進します。しかし、これはPod内でなく、コンテナ内でデーモンを稼働させることにより可能です(Dockerを介して直接起動する)。
### ベアPod
### ベアPod {#bare-pods}
特定のNode上で稼働するように指定したPodを直接作成することは可能です。しかし、DaemonSetはNodeの故障やNodeの破壊的なメンテナンスやカーネルのアップグレードなど、どのような理由に限らず、削除されたもしくは停止されたPodを置き換えます。このような理由で、ユーザーはPod単体を作成するよりもむしろDaemonSetを使うべきです。
### 静的Pod Pods
### 静的Pod Pods {#static-pods}
Kubeletによって監視されているディレクトリに対してファイルを書き込むことによって、Podを作成することが可能です。これは[静的Pod](/ja/docs/tasks/configure-pod-container/static-pod/)と呼ばれます。DaemonSetと違い、静的Podはkubectlや他のKubernetes APIクライアントで管理できません。静的PodはApiServerに依存しておらず、クラスターの自立起動時に最適です。また、静的Podは将来的には廃止される予定です。
### Deployment
### Deployment {#deployments}
DaemonSetは、Podの作成し、そのPodが停止されることのないプロセスを持つことにおいて[Deployment](/ja/docs/concepts/workloads/controllers/deployment/)と同様です(例: webサーバー、ストレージサーバー)。

View File

@ -30,7 +30,7 @@ content_type: concept
## CLIリファレンス
* [kubectl](/ja/docs/reference/kubectl/overview/) - コマンドの実行やKubernetesクラスターの管理に使う主要なCLIツールです。
* [kubectl](/ja/docs/reference/kubectl/) - コマンドの実行やKubernetesクラスターの管理に使う主要なCLIツールです。
* [JSONPath](/ja/docs/reference/kubectl/jsonpath/) - kubectlで[JSONPath記法](https://goessner.net/articles/JsonPath/)を使うための構文ガイドです。
* [kubeadm](/ja/docs/reference/setup-tools/kubeadm/) - セキュアなKubernetesクラスターを簡単にプロビジョニングするためのCLIツールです。

View File

@ -1,5 +1,5 @@
---
title: コマンドラインツールのリファレンス
weight: 60
weight: 120
toc-hide: true
---

View File

@ -346,7 +346,7 @@ GAになってからさらなる変更を加えることは現実的ではない
各フィーチャーゲートは特定の機能を有効/無効にするように設計されています。
- `Accelerators`: DockerでのNvidia GPUのサポートを有効にします。
- `AdvancedAuditing`: [高度な監査機能](/docs/tasks/debug-application-cluster/audit/#advanced-audit)を有効にします。
- `AdvancedAuditing`: [高度な監査機能](/ja/docs/tasks/debug/debug-cluster/audit/#advanced-audit)を有効にします。
- `AffinityInAnnotations`(*非推奨*): [Podのアフィニティまたはアンチアフィニティ](/ja/docs/concepts/scheduling-eviction/assign-pod-node/#affinity-and-anti-affinity)を有効にします。
- `AnyVolumeDataSource`: {{< glossary_tooltip text="PVC" term_id="persistent-volume-claim" >}}の`DataSource`としてカスタムリソースの使用を有効にします。
- `AllowExtTrafficLocalEndpoints`: サービスが外部へのリクエストをノードのローカルエンドポイントにルーティングできるようにします。
@ -387,7 +387,6 @@ GAになってからさらなる変更を加えることは現実的ではない
- `CustomResourceWebhookConversion`: [CustomResourceDefinition](/docs/concepts/extend-kubernetes/api-extension/custom-resources/)から作成されたリソースのWebhookベースの変換を有効にします。
- `DevicePlugins`: [device-plugins](/docs/concepts/cluster-administration/device-plugins/)によるノードでのリソースプロビジョニングを有効にします。
- `DryRun`: サーバーサイドでの[dry run](/docs/reference/using-api/api-concepts/#dry-run)リクエストを有効にします。
- `DynamicAuditing`: [動的監査](/docs/tasks/debug-application-cluster/audit/#dynamic-backend)を有効にします。
- `DynamicKubeletConfig`: kubeletの動的構成を有効にします。[kubeletの再設定](/docs/tasks/administer-cluster/reconfigure-kubelet/)を参照してください。
- `DynamicProvisioningScheduling`: デフォルトのスケジューラーを拡張してボリュームトポロジーを認識しPVプロビジョニングを処理します。この機能は、v1.12の`VolumeScheduling`機能に完全に置き換えられました。
- `DynamicVolumeProvisioning`(*非推奨*): Podへの永続ボリュームの[動的プロビジョニング](/ja/docs/concepts/storage/dynamic-provisioning/)を有効にします。

View File

@ -0,0 +1,19 @@
---
title: Kubectl
id: kubectl
date: 2018-04-12
full_link: /docs/reference/kubectl/
short_description: >
Kubernetesクラスターと通信するためのコマンドラインツールです。
aka:
- kubectl
tags:
- tool
- fundamental
---
Kubernetes APIを使用してKubernetesクラスターの{{< glossary_tooltip text="コントロールプレーン" term_id="control-plane" >}}と通信するためのコマンドラインツールです。
<!--more-->
Kubernetesオブジェクトの作成、検査、更新、削除には `kubectl` を使用することができます。

View File

@ -1,5 +1,495 @@
---
title: "kubectl CLI"
weight: 60
title: コマンドラインツール(kubectl)
content_type: reference
weight: 110
no_list: true
card:
name: reference
weight: 20
---
<!-- overview -->
{{< glossary_definition prepend="Kubernetesが提供する、" term_id="kubectl" length="short" >}}
このツールの名前は、`kubectl` です。
`kubectl`コマンドラインツールを使うと、Kubernetesクラスターを制御できます。環境設定のために、`kubectl`は、`$HOME/.kube`ディレクトリにある`config`という名前のファイルを探します。他の[kubeconfig](/ja/docs/concepts/configuration/organize-cluster-access-kubeconfig/)ファイルは、`KUBECONFIG`環境変数を設定するか、[`--kubeconfig`](/docs/concepts/configuration/organize-cluster-access-kubeconfig/)フラグを設定することで指定できます。
この概要では、`kubectl`の構文を扱い、コマンド操作を説明し、一般的な例を示します。サポートされているすべてのフラグやサブコマンドを含め、各コマンドの詳細については、[kubectl](/docs/reference/generated/kubectl/kubectl-commands/)リファレンスドキュメントを参照してください。
インストール方法については、[kubectlのインストールおよびセットアップ](/ja/docs/tasks/tools/install-kubectl/)をご覧ください。クイックガイドは、[cheat sheet](/docs/reference/kubectl/cheatsheet/) をご覧ください。`docker`コマンドラインツールに慣れている方は、[`kubectl` for Docker Users](/docs/reference/kubectl/docker-cli-to-kubectl/) でKubernetesの同等のコマンドを説明しています。
<!-- body -->
## 構文
ターミナルウィンドウから`kubectl`コマンドを実行するには、以下の構文を使用します。
```shell
kubectl [command] [TYPE] [NAME] [flags]
```
ここで、`command`、`TYPE`、`NAME`、`flags`は、以下を表します。
* `command`: 1つ以上のリソースに対して実行したい操作を指定します。例えば、`create`、`get`、`describe`、`delete`です。
* `TYPE`: [リソースタイプ](#resource-types)を指定します。リソースタイプは大文字と小文字を区別せず、単数形や複数形、省略形を指定できます。例えば、以下のコマンドは同じ出力を生成します。
```shell
kubectl get pod pod1
kubectl get pods pod1
kubectl get po pod1
```
* `NAME`: リソースの名前を指定します。名前は大文字と小文字を区別します。`kubectl get pods`のように名前が省略された場合は、すべてのリソースの詳細が表示されます。
複数のリソースに対して操作を行う場合は、各リソースをタイプと名前で指定するか、1つまたは複数のファイルを指定することができます。
* リソースをタイプと名前で指定する場合
* タイプがすべて同じとき、リソースをグループ化するには`TYPE1 name1 name2 name<#>`とします。<br/>
例: `kubectl get pod example-pod1 example-pod2`
* 複数のリソースタイプを個別に指定するには、`TYPE1/name1 TYPE1/name2 TYPE2/name3 TYPE<#>/name<#>`とします。<br/>
例: `kubectl get pod/example-pod1 replicationcontroller/example-rc1`
* リソースを1つ以上のファイルで指定する場合は、`-f file1 -f file2 -f file<#>`とします。
* 特に設定ファイルについては、YAMLの方がより使いやすいため、[JSONではなくYAMLを使用してください](/ja/docs/concepts/configuration/overview/#一般的な設定のtips)。<br/>
例: `kubectl get pod -f ./pod.yaml`
* `flags`: オプションのフラグを指定します。例えば、`-s`または`--server`フラグを使って、Kubernetes APIサーバーのアドレスやポートを指定できます。<br/>
{{< caution >}}
コマンドラインから指定したフラグは、デフォルト値および対応する任意の環境変数を上書きします。
{{< /caution >}}
ヘルプが必要な場合は、ターミナルウィンドウから`kubectl help`を実行してください。
## 操作
以下の表に、`kubectl`のすべての操作の簡単な説明と一般的な構文を示します。
操作&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | 構文 | 説明
-------------------- | -------------------- | --------------------
`alpha`| `kubectl alpha SUBCOMMAND [flags]` | アルファ機能に該当する利用可能なコマンドを一覧表示します。これらの機能は、デフォルトではKubernetesクラスターで有効になっていません。
`annotate` | <code>kubectl annotate (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]</code> | 1つ以上のリソースのアテーションを、追加または更新します。
`api-resources` | `kubectl api-resources [flags]` | 利用可能なAPIリソースを一覧表示します。
`api-versions` | `kubectl api-versions [flags]` | 利用可能なAPIバージョンを一覧表示します。
`apply` | `kubectl apply -f FILENAME [flags]`| ファイルまたは標準出力から、リソースの設定変更を適用します。
`attach` | `kubectl attach POD -c CONTAINER [-i] [-t] [flags]` | 実行中のコンテナにアタッチして、出力ストリームを表示するか、コンテナ(標準入力)と対話します。
`auth` | `kubectl auth [flags] [options]` | 認可を検査します。
`autoscale` | <code>kubectl autoscale (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]</code> | ReplicationControllerで管理されているPodのセットを、自動的にスケールします。
`certificate` | `kubectl certificate SUBCOMMAND [options]` | 証明書のリソースを変更します。
`cluster-info` | `kubectl cluster-info [flags]` | クラスター内のマスターとサービスに関するエンドポイント情報を表示します。
`completion` | `kubectl completion SHELL [options]` | 指定されたシェル(bashまたはzsh)のシェル補完コードを出力します。
`config` | `kubectl config SUBCOMMAND [flags]` | kubeconfigファイルを変更します。詳細は、個々のサブコマンドを参照してください。
`convert` | `kubectl convert -f FILENAME [options]` | 異なるAPIバージョン間で設定ファイルを変換します。YAMLとJSONに対応しています。
`cordon` | `kubectl cordon NODE [options]` | Nodeをスケジュール不可に設定します。
`cp` | `kubectl cp <file-spec-src> <file-spec-dest> [options]` | コンテナとの間でファイルやディレクトリをコピーします。
`create` | `kubectl create -f FILENAME [flags]` | ファイルまたは標準出力から、1つ以上のリソースを作成します。
`delete` | <code>kubectl delete (-f FILENAME &#124; TYPE [NAME &#124; /NAME &#124; -l label &#124; --all]) [flags]</code> | ファイル、標準出力、またはラベルセレクター、リソースセレクター、リソースを指定して、リソースを削除します。
`describe` | <code>kubectl describe (-f FILENAME &#124; TYPE [NAME_PREFIX &#124; /NAME &#124; -l label]) [flags]</code> | 1つ以上のリソースの詳細な状態を表示します。
`diff` | `kubectl diff -f FILENAME [flags]`| ファイルまたは標準出力と、現在の設定との差分を表示します。
`drain` | `kubectl drain NODE [options]` | メンテナンスの準備のためにNodeをdrainします。
`edit` | <code>kubectl edit (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) [flags]</code> | デファルトのエディタを使い、サーバー上の1つ以上のリソースリソースの定義を編集し、更新します。
`exec` | `kubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]]` | Pod内のコンテナに対して、コマンドを実行します。
`explain` | `kubectl explain [--recursive=false] [flags]` | 様々なリソースのドキュメントを取得します。例えば、Pod、Node、Serviceなどです。
`expose` | <code>kubectl expose (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) [--port=port] [--protocol=TCP&#124;UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type] [flags]</code> | ReplicationController、Service、Podを、新しいKubernetesサービスとして公開します。
`get` | <code>kubectl get (-f FILENAME &#124; TYPE [NAME &#124; /NAME &#124; -l label]) [--watch] [--sort-by=FIELD] [[-o &#124; --output]=OUTPUT_FORMAT] [flags]</code> | 1つ以上のリソースを表示します。
`kustomize` | `kubectl kustomize <dir> [flags] [options]` | kustomization.yamlファイル内の指示から生成されたAPIリソースのセットを一覧表示します。引数はファイルを含むディレクトリのPathまたはリポジトリルートに対して同じ場所を示すパスサフィックス付きのgitリポジトリのURLを指定しなければなりません。
`label` | <code>kubectl label (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]</code> | 1つ以上のリソースのラベルを、追加または更新します。
`logs` | `kubectl logs POD [-c CONTAINER] [--follow] [flags]` | Pod内のコンテナのログを表示します。
`options` | `kubectl options` | すべてのコマンドに適用されるグローバルコマンドラインオプションを一覧表示します。
`patch` | <code>kubectl patch (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) --patch PATCH [flags]</code> | Strategic Merge Patchの処理を使用して、リソースの1つ以上のフィールドを更新します。
`plugin` | `kubectl plugin [flags] [options]` | プラグインと対話するためのユーティリティを提供します。
`port-forward` | `kubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] [flags]` | 1つ以上のローカルポートを、Podに転送します。
`proxy` | `kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags]` | Kubernetes APIサーバーへのプロキシーを実行します。
`replace` | `kubectl replace -f FILENAME` | ファイルや標準出力から、リソースを置き換えます。
`rollout` | `kubectl rollout SUBCOMMAND [options]` | リソースのロールアウトを管理します。有効なリソースには、Deployment、DaemonSetとStatefulSetが含まれます。
`run` | <code>kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server&#124;client&#124;none] [--overrides=inline-json] [flags]</code> | 指定したイメージを、クラスタ上で実行します。
`scale` | <code>kubectl scale (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags]</code> | 指定したReplicationControllerのサイズを更新します。
`set` | `kubectl set SUBCOMMAND [options]` | アプリケーションリソースを設定します。
`taint` | `kubectl taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N [options]` | 1つ以上のNodeのtaintを更新します。
`top` | `kubectl top [flags] [options]` | リソース(CPU/メモリー/ストレージ)の使用量を表示します。
`uncordon` | `kubectl uncordon NODE [options]` | Nodeをスケジュール可に設定します。
`version` | `kubectl version [--client] [flags]` | クライアントとサーバーで実行中のKubernetesのバージョンを表示します。
`wait` | <code>kubectl wait ([-f FILENAME] &#124; resource.group/resource.name &#124; resource.group [(-l label &#124; --all)]) [--for=delete&#124;--for condition=available] [options]</code> | 実験中の機能: 1つ以上のリソースが特定の状態になるまで待ちます。
コマンド操作について詳しく知りたい場合は、[kubectl](/docs/reference/kubectl/kubectl/)リファレンスドキュメントを参照してください。
## リソースタイプ {#resource-types}
以下の表に、サポートされているすべてのリソースと、省略されたエイリアスの一覧を示します。
(この出力は`kubectl api-resources`から取得でき、Kubernetes 1.13.3時点で正確でした。)
| リソース名 | 短縮名 | APIグループ | 名前空間に属するか | リソースの種類 |
|---|---|---|---|---|
| `bindings` | | | true | Binding|
| `componentstatuses` | `cs` | | false | ComponentStatus |
| `configmaps` | `cm` | | true | ConfigMap |
| `endpoints` | `ep` | | true | Endpoints |
| `limitranges` | `limits` | | true | LimitRange |
| `namespaces` | `ns` | | false | Namespace |
| `nodes` | `no` | | false | Node |
| `persistentvolumeclaims` | `pvc` | | true | PersistentVolumeClaim |
| `persistentvolumes` | `pv` | | false | PersistentVolume |
| `pods` | `po` | | true | Pod |
| `podtemplates` | | | true | PodTemplate |
| `replicationcontrollers` | `rc` | | true| ReplicationController |
| `resourcequotas` | `quota` | | true | ResourceQuota |
| `secrets` | | | true | Secret |
| `serviceaccounts` | `sa` | | true | ServiceAccount |
| `services` | `svc` | | true | Service |
| `mutatingwebhookconfigurations` | | admissionregistration.k8s.io | false | MutatingWebhookConfiguration |
| `validatingwebhookconfigurations` | | admissionregistration.k8s.io | false | ValidatingWebhookConfiguration |
| `customresourcedefinitions` | `crd`, `crds` | apiextensions.k8s.io | false | CustomResourceDefinition |
| `apiservices` | | apiregistration.k8s.io | false | APIService |
| `controllerrevisions` | | apps | true | ControllerRevision |
| `daemonsets` | `ds` | apps | true | DaemonSet |
| `deployments` | `deploy` | apps | true | Deployment |
| `replicasets` | `rs` | apps | true | ReplicaSet |
| `statefulsets` | `sts` | apps | true | StatefulSet |
| `tokenreviews` | | authentication.k8s.io | false | TokenReview |
| `localsubjectaccessreviews` | | authorization.k8s.io | true | LocalSubjectAccessReview |
| `selfsubjectaccessreviews` | | authorization.k8s.io | false | SelfSubjectAccessReview |
| `selfsubjectrulesreviews` | | authorization.k8s.io | false | SelfSubjectRulesReview |
| `subjectaccessreviews` | | authorization.k8s.io | false | SubjectAccessReview |
| `horizontalpodautoscalers` | `hpa` | autoscaling | true | HorizontalPodAutoscaler |
| `cronjobs` | `cj` | batch | true | CronJob |
| `jobs` | | batch | true | Job |
| `certificatesigningrequests` | `csr` | certificates.k8s.io | false | CertificateSigningRequest |
| `leases` | | coordination.k8s.io | true | Lease |
| `events` | `ev` | events.k8s.io | true | Event |
| `ingresses` | `ing` | extensions | true | Ingress |
| `networkpolicies` | `netpol` | networking.k8s.io | true | NetworkPolicy |
| `poddisruptionbudgets` | `pdb` | policy | true | PodDisruptionBudget |
| `podsecuritypolicies` | `psp` | policy | false | PodSecurityPolicy |
| `clusterrolebindings` | | rbac.authorization.k8s.io | false | ClusterRoleBinding |
| `clusterroles` | | rbac.authorization.k8s.io | false | ClusterRole |
| `rolebindings` | | rbac.authorization.k8s.io | true | RoleBinding |
| `roles` | | rbac.authorization.k8s.io | true | Role |
| `priorityclasses` | `pc` | scheduling.k8s.io | false | PriorityClass |
| `csidrivers` | | storage.k8s.io | false | CSIDriver |
| `csinodes` | | storage.k8s.io | false | CSINode |
| `storageclasses` | `sc` | storage.k8s.io | false | StorageClass |
| `volumeattachments` | | storage.k8s.io | false | VolumeAttachment |
## 出力オプション
ある特定のコマンドの出力に対してフォーマットやソートを行う方法については、以下の節を参照してください。どのコマンドが様々な出力オプションをサポートしているかについては、[kubectl](/docs/reference/kubectl/kubectl/)リファレンスドキュメントをご覧ください。
### 出力のフォーマット
すべての`kubectl`コマンドのデフォルトの出力フォーマットは、人間が読みやすいプレーンテキスト形式です。特定のフォーマットで、詳細をターミナルウィンドウに出力するには、サポートされている`kubectl`コマンドに`-o`または`--output`フラグのいずれかを追加します。
#### 構文
```shell
kubectl [command] [TYPE] [NAME] -o <output_format>
```
`kubectl`の操作に応じて、以下の出力フォーマットがサポートされています。
出力フォーマット | 説明
--------------| -----------
`-o custom-columns=<spec>` | [カスタムカラム](#custom-columns)のコンマ区切りのリストを使用して、テーブルを表示します。
`-o custom-columns-file=<filename>` | `<filename>`ファイル内の[カスタムカラム](#custom-columns)のテンプレートを使用して、テーブルを表示します。
`-o json` | JSON形式のAPIオブジェクトを出力します。
`-o jsonpath=<template>` | [jsonpath](/ja/docs/reference/kubectl/jsonpath/)式で定義されたフィールドを表示します。
`-o jsonpath-file=<filename>` | `<filename>`ファイル内の[jsonpath](/ja/docs/reference/kubectl/jsonpath/)式で定義されたフィールドを表示します。
`-o name` | リソース名のみを表示します。
`-o wide` | 追加情報を含めて、プレーンテキスト形式で出力します。Podの場合は、Node名が含まれます。
`-o yaml` | YAML形式のAPIオブジェクトを出力します。
##### 例
この例において、以下のコマンドは1つのPodの詳細を、YAML形式のオブジェクトとして出力します。
```shell
kubectl get pod web-pod-13je7 -o yaml
```
各コマンドでサポートされている出力フォーマットの詳細については、[kubectl](/docs/reference/kubectl/kubectl/)リファレンスドキュメントを参照してください。
#### カスタムカラム {#custom-columns}
カスタムカラムを定義して、必要な詳細のみをテーブルに出力するには、`custom-columns`オプションを使います。カスタムカラムをインラインで定義するか、`-o custom-columns=<spec>`または`-o custom-columns-file=<filename>`のようにテンプレートファイルを使用するかを選択できます。
##### 例
インラインで定義する例は、以下の通りです。
```shell
kubectl get pods <pod-name> -o custom-columns=NAME:.metadata.name,RSRC:.metadata.resourceVersion
```
テンプレートファイルを使用して定義する例は、以下の通りです。
```shell
kubectl get pods <pod-name> -o custom-columns-file=template.txt
```
ここで、`template.txt`には以下の内容が含まれます。
```
NAME RSRC
metadata.name metadata.resourceVersion
```
どちらのコマンドを実行した場合でも、以下の結果を得ます。
```
NAME RSRC
submit-queue 610995
```
#### サーバーサイドカラム
`kubectl`は、サーバーからオブジェクトに関する特定のカラム情報を受け取ることをサポートしています。
つまり、与えられた任意のリソースについて、サーバーはそのリソースに関連する列や行を返し、クライアントが表示できるようにします。
これにより、サーバーが表示の詳細をカプセル化することで、同一クラスターに対して使用されているクライアント間で、一貫した人間が読みやすい出力が可能です。
この機能は、デフォルトで有効になっています。無効にするには、`kubectl get`コマンドに`--server-print=false`フラグを追加します。
##### 例
Podの状態に関する情報を表示するには、以下のようなコマンドを使用します。
```shell
kubectl get pods <pod-name> --server-print=false
```
以下のように出力されます。
```
NAME AGE
pod-name 1m
```
### オブジェクトリストのソート
ターミナルウィンドウで、オブジェクトをソートされたリストに出力するには、サポートされている`kubectl`コマンドに`--sort-by`フラグを追加します。`--sort-by`フラグで任意の数値フィールドや文字列フィールドを指定することで、オブジェクトをソートします。フィールドの指定には、[jsonpath](/ja/docs/reference/kubectl/jsonpath/)式を使用します。
#### 構文
```shell
kubectl [command] [TYPE] [NAME] --sort-by=<jsonpath_exp>
```
##### 例
名前でソートしたPodのリストを表示するには、以下のように実行します。
```shell
kubectl get pods --sort-by=.metadata.name
```
## 例: 一般的な操作
よく使われる`kubectl`の操作に慣れるために、以下の例を使用してください。
`kubectl apply` - ファイルや標準出力から、リソースの適用や更新を行います。
```shell
# example-service.yaml内の定義を使用して、Serviceを作成します。
kubectl apply -f example-service.yaml
# example-controller.yaml内の定義を使用して、ReplicationControllerを作成します。
kubectl apply -f example-controller.yaml
# <directory>ディレクトリ内の、任意の.yaml、.yml、.jsonファイルで定義されているオブジェクトを作成します。
kubectl apply -f <directory>
```
`kubectl get` - 1つ以上のリソースの一覧を表示します。
```shell
# すべてのPodの一覧をプレーンテキスト形式で表示します。
kubectl get pods
# すべてのPodの一覧を、ード名などの追加情報を含めて、プレーンテキスト形式で表示します。
kubectl get pods -o wide
# 指定した名前のReplicationControllerの一覧をプレーンテキスト形式で表示します。'replicationcontroller'リソースタイプを短縮して、エイリアス'rc'で置き換えることもできます。
kubectl get replicationcontroller <rc-name>
# すべてのReplicationControllerとServiceの一覧をまとめてプレーンテキスト形式で表示します。
kubectl get rc,services
# すべてのDaemonSetの一覧をプレーンテキスト形式で表示します。
kubectl get ds
# server01ードで実行中のPodの一覧をプレーンテキスト形式で表示します。
kubectl get pods --field-selector=spec.nodeName=server01
```
`kubectl describe` - 1つ以上のリソースの詳細な状態を、デフォルトでは初期化されないものも含めて表示します。
```shell
# Node <node-name>の詳細を表示します。
kubectl describe nodes <node-name>
# Pod <pod-name>の詳細を表示します。
kubectl describe pods/<pod-name>
# ReplicationController <rc-name>が管理しているすべてのPodの詳細を表示します。
# ReplicationControllerによって作成された任意のPodには、ReplicationControllerの名前がプレフィックスとして付与されます。
kubectl describe pods <rc-name>
# すべてのPodの詳細を表示します。
kubectl describe pods
```
{{< note >}}
`kubectl get`コマンドは通常、同じリソースタイプの1つ以上のリソースを取得するために使用します。豊富なフラグが用意されており、例えば`-o`や`--output`フラグを使って、出力フォーマットをカスタマイズできます。`-w`や`--watch`フラグを指定することで、特定のオブジェクトの更新を監視できます。`kubectl describe`コマンドは、指定されたリソースに関する多くの側面を説明することに重点を置いています。ユーザーに対してビューを構築するために、APIサーバーへ複数のAPIコールを呼び出すことができます。例えば、`kubectl describe node`コマンドは、Nodeに関する情報だけでなく、その上で動いているPodやNodeで生成されたイベントなどをまとめて表示します。
{{< /note >}}
`kubectl delete` - ファイル、標準出力、または指定したラベルセレクター、名前、リソースセレクター、リソースを指定して、リソースを削除します。
```shell
# pod.yamlファイルで指定されたタイプと名前を用いて、Podを削除します。
kubectl delete -f pod.yaml
# '<label-key>=<label-value>'というラベルを持つPodとServiceをすべて削除します。
kubectl delete pods,services -l <label-key>=<label-value>
# 初期化されていないPodを含む、すべてのPodを削除します。
kubectl delete pods --all
```
`kubectl exec` - Pod内のコンテナに対してコマンドを実行します。
```shell
# Pod <pod-name>から、'date'を実行している時の出力を取得します。デフォルトでは、最初のコンテナから出力されます。
kubectl exec <pod-name> -- date
# Pod <pod-name>のコンテナ <container-name>から、'date'を実行している時の出力を取得します。
kubectl exec <pod-name> -c <container-name> -- date
# インタラクティブな TTY を取得し、Pod <pod-name>から/bin/bashを実行します。デフォルトでは、最初のコンテナから出力されます。
kubectl exec -ti <pod-name> -- /bin/bash
```
`kubectl logs` - Pod内のコンテナのログを表示します。
```shell
# Pod <pod-name>のログのスナップショットを返します。
kubectl logs <pod-name>
# Pod <pod-name>から、ログのストリーミングを開始します。Linuxの'tail -f'コマンドと似ています。
kubectl logs -f <pod-name>
```
`kubectl diff` - 提案されたクラスタに対する更新の差分を表示します。
```shell
# pod.jsonに含まれるリソースの差分を表示します。
kubectl diff -f pod.json
# 標準出力から読み込んだファイルの差分を表示します。
cat service.yaml | kubectl diff -f -
```
## 例: プラグインの作成と使用
`kubectl`プラグインの書き方や使い方に慣れるために、以下の例を使用してください。
```shell
# 任意の言語でシンプルなプラグインを作成し、生成される実行可能なファイルに
# プレフィックス"kubectl-"で始まる名前を付けます。
cat ./kubectl-hello
```
```shell
#!/bin/sh
# このプラグインは、"hello world"という単語を表示します。
echo "hello world"
```
プラグインを書いたら、実行可能にします。
```bash
chmod a+x ./kubectl-hello
# さらに、PATH内の場所に移動させます。
sudo mv ./kubectl-hello /usr/local/bin
sudo chown root:root /usr/local/bin
# これでkubectlプラグインを作成し、"インストール"できました。
# 通常のコマンドのようにkubectlから呼び出すことで、プラグインを使用できます。
kubectl hello
```
```
hello world
```
```shell
# 配置したPATHのフォルダから削除することで、プラグインを"アンインストール"できます。
sudo rm /usr/local/bin/kubectl-hello
```
`kubectl`で利用可能なプラグインをすべて表示するには、`kubectl plugin list`サブコマンドを使用してください。
```shell
kubectl plugin list
```
出力は以下のようになります。
```
The following kubectl-compatible plugins are available:
/usr/local/bin/kubectl-hello
/usr/local/bin/kubectl-foo
/usr/local/bin/kubectl-bar
```
`kubectl plugin list`コマンドは、実行不可能なプラグインや、他のプラグインの影に隠れてしまっているプラグインなどについて、警告することもできます。例えば、以下のようになります。
```shell
sudo chmod -x /usr/local/bin/kubectl-foo # 実行権限を削除します。
kubectl plugin list
```
```
The following kubectl-compatible plugins are available:
/usr/local/bin/kubectl-hello
/usr/local/bin/kubectl-foo
- warning: /usr/local/bin/kubectl-foo identified as a plugin, but it is not executable
/usr/local/bin/kubectl-bar
error: one plugin warning was found
```
プラグインは、既存の`kubectl`コマンドの上に、より複雑な機能を構築するための手段であると考えることができます。
```shell
cat ./kubectl-whoami
```
次の例では、下記の内容を含んだ`kubectl-whoami`が既に作成済であることを前提としています。
```shell
#!/bin/bash
# このプラグインは、`kubectl config`コマンドを使って
# 現在選択されているコンテキストに基づいて、現在のユーザーに関する情報を提供します。
kubectl config view --template='{{ range .contexts }}{{ if eq .name "'$(kubectl config current-context)'" }}Current user: {{ printf "%s\n" .context.user }}{{ end }}{{ end }}'
```
上記のコマンドを実行すると、KUBECONFIGファイル内のカレントコンテキストのユーザーを含んだ出力を得られます。
```shell
# ファイルを実行可能にします。
sudo chmod +x ./kubectl-whoami
# さらに、ファイルをPATHに移動します。
sudo mv ./kubectl-whoami /usr/local/bin
kubectl whoami
Current user: plugins-user
```
## {{% heading "whatsnext" %}}
* `kubectl`リファレンスドキュメントをお読みください。
* kubectl[コマンドリファレンス](/docs/reference/kubectl/kubectl/)
* [コマンドライン引数](/docs/reference/generated/kubectl/kubectl-commands/)リファレンス
* [`kubectl`の使用規則](/ja/docs/reference/kubectl/conventions/)について学習してください。
* kubectlの[JSONPathのサポート](/ja/docs/reference/kubectl/jsonpath/)についてお読みください。
* [プラグインを使用して kubectl を拡張する](/docs/tasks/extend-kubectl/kubectl-plugins)方法についてお読みください。
* プラグインについてより詳しく知りたい場合は、[example CLI plugin](https://github.com/kubernetes/sample-cli-plugin)をご覧ください。

View File

@ -1,6 +1,7 @@
---
title: kubectlチートシート
content_type: concept
weight: 10 # highlight it
card:
name: reference
weight: 30
@ -366,7 +367,7 @@ kubectl get pods -A -o=custom-columns='DATA:spec.containers[?(@.image!="registry
kubectl get pods -A -o=custom-columns='DATA:metadata.*'
```
kubectlに関するより多くのサンプルは[カスタムカラムのリファレンス](/ja/docs/reference/kubectl/overview/#custom-columns)を参照してください。
kubectlに関するより多くのサンプルは[カスタムカラムのリファレンス](/ja/docs/reference/kubectl/#custom-columns)を参照してください。
### Kubectlのログレベルとデバッグ
kubectlのログレベルは、レベルを表す整数が後に続く`-v`または`--v`フラグで制御されます。一般的なKubernetesのログ記録規則と関連するログレベルについて、[こちら](https://github.com/kubernetes/community/blob/master/contributors/devel/sig-instrumentation/logging.md)で説明します。
@ -387,7 +388,7 @@ kubectlのログレベルは、レベルを表す整数が後に続く`-v`また
## {{% heading "whatsnext" %}}
* kubectlについてより深く学びたい方は[kubectl概要](/ja/docs/reference/kubectl/overview/)や[JsonPath](/docs/reference/kubectl/jsonpath)をご覧ください。
* kubectlについてより深く学びたい方は[コマンドラインツール(kubectl)](/ja/docs/reference/kubectl/)や[JsonPath](/docs/reference/kubectl/jsonpath)をご覧ください。
* オプションについては[kubectl](/docs/reference/kubectl/kubectl/) optionsをご覧ください。

View File

@ -1,6 +1,7 @@
---
title: kubectlの使用規則
content_type: concept
weight: 60
---
<!-- overview -->

View File

@ -1,7 +1,7 @@
---
title: JSONPathのサポート
content_type: concept
weight: 25
weight: 40
---
<!-- overview -->

View File

@ -1,485 +0,0 @@
---
title: kubectlの概要
content_type: concept
weight: 20
card:
name: reference
weight: 20
---
<!-- overview -->
`kubectl`コマンドラインツールを使うと、Kubernetesクラスターを制御できます。環境設定のために、`kubectl`は、`$HOME/.kube`ディレクトリにある`config`という名前のファイルを探します。他の[kubeconfig](/ja/docs/concepts/configuration/organize-cluster-access-kubeconfig/)ファイルは、`KUBECONFIG`環境変数を設定するか、[`--kubeconfig`](/docs/concepts/configuration/organize-cluster-access-kubeconfig/)フラグを設定することで指定できます。
この概要では、`kubectl`の構文を扱い、コマンド操作を説明し、一般的な例を示します。サポートされているすべてのフラグやサブコマンドを含め、各コマンドの詳細については、[kubectl](/docs/reference/generated/kubectl/kubectl-commands/)リファレンスドキュメントを参照してください。インストール方法については、[kubectlのインストールおよびセットアップ](/ja/docs/tasks/tools/install-kubectl/)をご覧ください。
<!-- body -->
## 構文
ターミナルウィンドウから`kubectl`コマンドを実行するには、以下の構文を使用します。
```shell
kubectl [command] [TYPE] [NAME] [flags]
```
ここで、`command`、`TYPE`、`NAME`、`flags`は、以下を表します。
* `command`: 1つ以上のリソースに対して実行したい操作を指定します。例えば、`create`、`get`、`describe`、`delete`です。
* `TYPE`: [リソースタイプ](#resource-types)を指定します。リソースタイプは大文字と小文字を区別せず、単数形や複数形、省略形を指定できます。例えば、以下のコマンドは同じ出力を生成します。
```shell
kubectl get pod pod1
kubectl get pods pod1
kubectl get po pod1
```
* `NAME`: リソースの名前を指定します。名前は大文字と小文字を区別します。`kubectl get pods`のように名前が省略された場合は、すべてのリソースの詳細が表示されます。
複数のリソースに対して操作を行う場合は、各リソースをタイプと名前で指定するか、1つまたは複数のファイルを指定することができます。
* リソースをタイプと名前で指定する場合
* タイプがすべて同じとき、リソースをグループ化するには`TYPE1 name1 name2 name<#>`とします。<br/>
例: `kubectl get pod example-pod1 example-pod2`
* 複数のリソースタイプを個別に指定するには、`TYPE1/name1 TYPE1/name2 TYPE2/name3 TYPE<#>/name<#>`とします。<br/>
例: `kubectl get pod/example-pod1 replicationcontroller/example-rc1`
* リソースを1つ以上のファイルで指定する場合は、`-f file1 -f file2 -f file<#>`とします。
* 特に設定ファイルについては、YAMLの方がより使いやすいため、[JSONではなくYAMLを使用してください](/ja/docs/concepts/configuration/overview/#一般的な設定のtips)。<br/>
例: `kubectl get pod -f ./pod.yaml`
* `flags`: オプションのフラグを指定します。例えば、`-s`または`--server`フラグを使って、Kubernetes APIサーバーのアドレスやポートを指定できます。<br/>
{{< caution >}}
コマンドラインから指定したフラグは、デフォルト値および対応する任意の環境変数を上書きします。
{{< /caution >}}
ヘルプが必要な場合は、ターミナルウィンドウから`kubectl help`を実行してください。
## 操作
以下の表に、`kubectl`のすべての操作の簡単な説明と一般的な構文を示します。
操作&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; | 構文 | 説明
-------------------- | -------------------- | --------------------
`alpha`| `kubectl alpha SUBCOMMAND [flags]` | アルファ機能に該当する利用可能なコマンドを一覧表示します。これらの機能は、デフォルトではKubernetesクラスターで有効になっていません。
`annotate` | <code>kubectl annotate (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]</code> | 1つ以上のリソースのアテーションを、追加または更新します。
`api-resources` | `kubectl api-resources [flags]` | 利用可能なAPIリソースを一覧表示します。
`api-versions` | `kubectl api-versions [flags]` | 利用可能なAPIバージョンを一覧表示します。
`apply` | `kubectl apply -f FILENAME [flags]`| ファイルまたは標準出力から、リソースの設定変更を適用します。
`attach` | `kubectl attach POD -c CONTAINER [-i] [-t] [flags]` | 実行中のコンテナにアタッチして、出力ストリームを表示するか、コンテナ(標準入力)と対話します。
`auth` | `kubectl auth [flags] [options]` | 認可を検査します。
`autoscale` | <code>kubectl autoscale (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) [--min=MINPODS] --max=MAXPODS [--cpu-percent=CPU] [flags]</code> | ReplicationControllerで管理されているPodのセットを、自動的にスケールします。
`certificate` | `kubectl certificate SUBCOMMAND [options]` | 証明書のリソースを変更します。
`cluster-info` | `kubectl cluster-info [flags]` | クラスター内のマスターとサービスに関するエンドポイント情報を表示します。
`completion` | `kubectl completion SHELL [options]` | 指定されたシェル(bashまたはzsh)のシェル補完コードを出力します。
`config` | `kubectl config SUBCOMMAND [flags]` | kubeconfigファイルを変更します。詳細は、個々のサブコマンドを参照してください。
`convert` | `kubectl convert -f FILENAME [options]` | 異なるAPIバージョン間で設定ファイルを変換します。YAMLとJSONに対応しています。
`cordon` | `kubectl cordon NODE [options]` | Nodeをスケジュール不可に設定します。
`cp` | `kubectl cp <file-spec-src> <file-spec-dest> [options]` | コンテナとの間でファイルやディレクトリをコピーします。
`create` | `kubectl create -f FILENAME [flags]` | ファイルまたは標準出力から、1つ以上のリソースを作成します。
`delete` | <code>kubectl delete (-f FILENAME &#124; TYPE [NAME &#124; /NAME &#124; -l label &#124; --all]) [flags]</code> | ファイル、標準出力、またはラベルセレクター、リソースセレクター、リソースを指定して、リソースを削除します。
`describe` | <code>kubectl describe (-f FILENAME &#124; TYPE [NAME_PREFIX &#124; /NAME &#124; -l label]) [flags]</code> | 1つ以上のリソースの詳細な状態を表示します。
`diff` | `kubectl diff -f FILENAME [flags]`| ファイルまたは標準出力と、現在の設定との差分を表示します。
`drain` | `kubectl drain NODE [options]` | メンテナンスの準備のためにNodeをdrainします。
`edit` | <code>kubectl edit (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) [flags]</code> | デファルトのエディタを使い、サーバー上の1つ以上のリソースリソースの定義を編集し、更新します。
`exec` | `kubectl exec POD [-c CONTAINER] [-i] [-t] [flags] [-- COMMAND [args...]]` | Pod内のコンテナに対して、コマンドを実行します。
`explain` | `kubectl explain [--recursive=false] [flags]` | 様々なリソースのドキュメントを取得します。例えば、Pod、Node、Serviceなどです。
`expose` | <code>kubectl expose (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) [--port=port] [--protocol=TCP&#124;UDP] [--target-port=number-or-name] [--name=name] [--external-ip=external-ip-of-service] [--type=type] [flags]</code> | ReplicationController、Service、Podを、新しいKubernetesサービスとして公開します。
`get` | <code>kubectl get (-f FILENAME &#124; TYPE [NAME &#124; /NAME &#124; -l label]) [--watch] [--sort-by=FIELD] [[-o &#124; --output]=OUTPUT_FORMAT] [flags]</code> | 1つ以上のリソースを表示します。
`kustomize` | `kubectl kustomize <dir> [flags] [options]` | kustomization.yamlファイル内の指示から生成されたAPIリソースのセットを一覧表示します。引数はファイルを含むディレクトリのPathまたはリポジトリルートに対して同じ場所を示すパスサフィックス付きのgitリポジトリのURLを指定しなければなりません。
`label` | <code>kubectl label (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) KEY_1=VAL_1 ... KEY_N=VAL_N [--overwrite] [--all] [--resource-version=version] [flags]</code> | 1つ以上のリソースのラベルを、追加または更新します。
`logs` | `kubectl logs POD [-c CONTAINER] [--follow] [flags]` | Pod内のコンテナのログを表示します。
`options` | `kubectl options` | すべてのコマンドに適用されるグローバルコマンドラインオプションを一覧表示します。
`patch` | <code>kubectl patch (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) --patch PATCH [flags]</code> | Strategic Merge Patchの処理を使用して、リソースの1つ以上のフィールドを更新します。
`plugin` | `kubectl plugin [flags] [options]` | プラグインと対話するためのユーティリティを提供します。
`port-forward` | `kubectl port-forward POD [LOCAL_PORT:]REMOTE_PORT [...[LOCAL_PORT_N:]REMOTE_PORT_N] [flags]` | 1つ以上のローカルポートを、Podに転送します。
`proxy` | `kubectl proxy [--port=PORT] [--www=static-dir] [--www-prefix=prefix] [--api-prefix=prefix] [flags]` | Kubernetes APIサーバーへのプロキシーを実行します。
`replace` | `kubectl replace -f FILENAME` | ファイルや標準出力から、リソースを置き換えます。
`rollout` | `kubectl rollout SUBCOMMAND [options]` | リソースのロールアウトを管理します。有効なリソースには、Deployment、DaemonSetとStatefulSetが含まれます。
`run` | <code>kubectl run NAME --image=image [--env="key=value"] [--port=port] [--dry-run=server&#124;client&#124;none] [--overrides=inline-json] [flags]</code> | 指定したイメージを、クラスタ上で実行します。
`scale` | <code>kubectl scale (-f FILENAME &#124; TYPE NAME &#124; TYPE/NAME) --replicas=COUNT [--resource-version=version] [--current-replicas=count] [flags]</code> | 指定したReplicationControllerのサイズを更新します。
`set` | `kubectl set SUBCOMMAND [options]` | アプリケーションリソースを設定します。
`taint` | `kubectl taint NODE NAME KEY_1=VAL_1:TAINT_EFFECT_1 ... KEY_N=VAL_N:TAINT_EFFECT_N [options]` | 1つ以上のNodeのtaintを更新します。
`top` | `kubectl top [flags] [options]` | リソース(CPU/メモリー/ストレージ)の使用量を表示します。
`uncordon` | `kubectl uncordon NODE [options]` | Nodeをスケジュール可に設定します。
`version` | `kubectl version [--client] [flags]` | クライアントとサーバーで実行中のKubernetesのバージョンを表示します。
`wait` | <code>kubectl wait ([-f FILENAME] &#124; resource.group/resource.name &#124; resource.group [(-l label &#124; --all)]) [--for=delete&#124;--for condition=available] [options]</code> | 実験中の機能: 1つ以上のリソースが特定の状態になるまで待ちます。
コマンド操作について詳しく知りたい場合は、[kubectl](/docs/reference/kubectl/kubectl/)リファレンスドキュメントを参照してください。
## リソースタイプ {#resource-types}
以下の表に、サポートされているすべてのリソースと、省略されたエイリアスの一覧を示します。
(この出力は`kubectl api-resources`から取得でき、Kubernetes 1.13.3時点で正確でした。)
| リソース名 | 短縮名 | APIグループ | 名前空間に属するか | リソースの種類 |
|---|---|---|---|---|
| `bindings` | | | true | Binding|
| `componentstatuses` | `cs` | | false | ComponentStatus |
| `configmaps` | `cm` | | true | ConfigMap |
| `endpoints` | `ep` | | true | Endpoints |
| `limitranges` | `limits` | | true | LimitRange |
| `namespaces` | `ns` | | false | Namespace |
| `nodes` | `no` | | false | Node |
| `persistentvolumeclaims` | `pvc` | | true | PersistentVolumeClaim |
| `persistentvolumes` | `pv` | | false | PersistentVolume |
| `pods` | `po` | | true | Pod |
| `podtemplates` | | | true | PodTemplate |
| `replicationcontrollers` | `rc` | | true| ReplicationController |
| `resourcequotas` | `quota` | | true | ResourceQuota |
| `secrets` | | | true | Secret |
| `serviceaccounts` | `sa` | | true | ServiceAccount |
| `services` | `svc` | | true | Service |
| `mutatingwebhookconfigurations` | | admissionregistration.k8s.io | false | MutatingWebhookConfiguration |
| `validatingwebhookconfigurations` | | admissionregistration.k8s.io | false | ValidatingWebhookConfiguration |
| `customresourcedefinitions` | `crd`, `crds` | apiextensions.k8s.io | false | CustomResourceDefinition |
| `apiservices` | | apiregistration.k8s.io | false | APIService |
| `controllerrevisions` | | apps | true | ControllerRevision |
| `daemonsets` | `ds` | apps | true | DaemonSet |
| `deployments` | `deploy` | apps | true | Deployment |
| `replicasets` | `rs` | apps | true | ReplicaSet |
| `statefulsets` | `sts` | apps | true | StatefulSet |
| `tokenreviews` | | authentication.k8s.io | false | TokenReview |
| `localsubjectaccessreviews` | | authorization.k8s.io | true | LocalSubjectAccessReview |
| `selfsubjectaccessreviews` | | authorization.k8s.io | false | SelfSubjectAccessReview |
| `selfsubjectrulesreviews` | | authorization.k8s.io | false | SelfSubjectRulesReview |
| `subjectaccessreviews` | | authorization.k8s.io | false | SubjectAccessReview |
| `horizontalpodautoscalers` | `hpa` | autoscaling | true | HorizontalPodAutoscaler |
| `cronjobs` | `cj` | batch | true | CronJob |
| `jobs` | | batch | true | Job |
| `certificatesigningrequests` | `csr` | certificates.k8s.io | false | CertificateSigningRequest |
| `leases` | | coordination.k8s.io | true | Lease |
| `events` | `ev` | events.k8s.io | true | Event |
| `ingresses` | `ing` | extensions | true | Ingress |
| `networkpolicies` | `netpol` | networking.k8s.io | true | NetworkPolicy |
| `poddisruptionbudgets` | `pdb` | policy | true | PodDisruptionBudget |
| `podsecuritypolicies` | `psp` | policy | false | PodSecurityPolicy |
| `clusterrolebindings` | | rbac.authorization.k8s.io | false | ClusterRoleBinding |
| `clusterroles` | | rbac.authorization.k8s.io | false | ClusterRole |
| `rolebindings` | | rbac.authorization.k8s.io | true | RoleBinding |
| `roles` | | rbac.authorization.k8s.io | true | Role |
| `priorityclasses` | `pc` | scheduling.k8s.io | false | PriorityClass |
| `csidrivers` | | storage.k8s.io | false | CSIDriver |
| `csinodes` | | storage.k8s.io | false | CSINode |
| `storageclasses` | `sc` | storage.k8s.io | false | StorageClass |
| `volumeattachments` | | storage.k8s.io | false | VolumeAttachment |
## 出力オプション
ある特定のコマンドの出力に対してフォーマットやソートを行う方法については、以下の節を参照してください。どのコマンドが様々な出力オプションをサポートしているかについては、[kubectl](/docs/reference/kubectl/kubectl/)リファレンスドキュメントをご覧ください。
### 出力のフォーマット
すべての`kubectl`コマンドのデフォルトの出力フォーマットは、人間が読みやすいプレーンテキスト形式です。特定のフォーマットで、詳細をターミナルウィンドウに出力するには、サポートされている`kubectl`コマンドに`-o`または`--output`フラグのいずれかを追加します。
#### 構文
```shell
kubectl [command] [TYPE] [NAME] -o <output_format>
```
`kubectl`の操作に応じて、以下の出力フォーマットがサポートされています。
出力フォーマット | 説明
--------------| -----------
`-o custom-columns=<spec>` | [カスタムカラム](#custom-columns)のコンマ区切りのリストを使用して、テーブルを表示します。
`-o custom-columns-file=<filename>` | `<filename>`ファイル内の[カスタムカラム](#custom-columns)のテンプレートを使用して、テーブルを表示します。
`-o json` | JSON形式のAPIオブジェクトを出力します。
`-o jsonpath=<template>` | [jsonpath](/ja/docs/reference/kubectl/jsonpath/)式で定義されたフィールドを表示します。
`-o jsonpath-file=<filename>` | `<filename>`ファイル内の[jsonpath](/ja/docs/reference/kubectl/jsonpath/)式で定義されたフィールドを表示します。
`-o name` | リソース名のみを表示します。
`-o wide` | 追加情報を含めて、プレーンテキスト形式で出力します。Podの場合は、Node名が含まれます。
`-o yaml` | YAML形式のAPIオブジェクトを出力します。
##### 例
この例において、以下のコマンドは1つのPodの詳細を、YAML形式のオブジェクトとして出力します。
```shell
kubectl get pod web-pod-13je7 -o yaml
```
各コマンドでサポートされている出力フォーマットの詳細については、[kubectl](/docs/reference/kubectl/kubectl/)リファレンスドキュメントを参照してください。
#### カスタムカラム {#custom-columns}
カスタムカラムを定義して、必要な詳細のみをテーブルに出力するには、`custom-columns`オプションを使います。カスタムカラムをインラインで定義するか、`-o custom-columns=<spec>`または`-o custom-columns-file=<filename>`のようにテンプレートファイルを使用するかを選択できます。
##### 例
インラインで定義する例は、以下の通りです。
```shell
kubectl get pods <pod-name> -o custom-columns=NAME:.metadata.name,RSRC:.metadata.resourceVersion
```
テンプレートファイルを使用して定義する例は、以下の通りです。
```shell
kubectl get pods <pod-name> -o custom-columns-file=template.txt
```
ここで、`template.txt`には以下の内容が含まれます。
```
NAME RSRC
metadata.name metadata.resourceVersion
```
どちらのコマンドを実行した場合でも、以下の結果を得ます。
```
NAME RSRC
submit-queue 610995
```
#### サーバーサイドカラム
`kubectl`は、サーバーからオブジェクトに関する特定のカラム情報を受け取ることをサポートしています。
つまり、与えられた任意のリソースについて、サーバーはそのリソースに関連する列や行を返し、クライアントが表示できるようにします。
これにより、サーバーが表示の詳細をカプセル化することで、同一クラスターに対して使用されているクライアント間で、一貫した人間が読みやすい出力が可能です。
この機能は、デフォルトで有効になっています。無効にするには、`kubectl get`コマンドに`--server-print=false`フラグを追加します。
##### 例
Podの状態に関する情報を表示するには、以下のようなコマンドを使用します。
```shell
kubectl get pods <pod-name> --server-print=false
```
以下のように出力されます。
```
NAME AGE
pod-name 1m
```
### オブジェクトリストのソート
ターミナルウィンドウで、オブジェクトをソートされたリストに出力するには、サポートされている`kubectl`コマンドに`--sort-by`フラグを追加します。`--sort-by`フラグで任意の数値フィールドや文字列フィールドを指定することで、オブジェクトをソートします。フィールドの指定には、[jsonpath](/ja/docs/reference/kubectl/jsonpath/)式を使用します。
#### 構文
```shell
kubectl [command] [TYPE] [NAME] --sort-by=<jsonpath_exp>
```
##### 例
名前でソートしたPodのリストを表示するには、以下のように実行します。
```shell
kubectl get pods --sort-by=.metadata.name
```
## 例: 一般的な操作
よく使われる`kubectl`の操作に慣れるために、以下の例を使用してください。
`kubectl apply` - ファイルや標準出力から、リソースの適用や更新を行います。
```shell
# example-service.yaml内の定義を使用して、Serviceを作成します。
kubectl apply -f example-service.yaml
# example-controller.yaml内の定義を使用して、ReplicationControllerを作成します。
kubectl apply -f example-controller.yaml
# <directory>ディレクトリ内の、任意の.yaml、.yml、.jsonファイルで定義されているオブジェクトを作成します。
kubectl apply -f <directory>
```
`kubectl get` - 1つ以上のリソースの一覧を表示します。
```shell
# すべてのPodの一覧をプレーンテキスト形式で表示します。
kubectl get pods
# すべてのPodの一覧を、ード名などの追加情報を含めて、プレーンテキスト形式で表示します。
kubectl get pods -o wide
# 指定した名前のReplicationControllerの一覧をプレーンテキスト形式で表示します。'replicationcontroller'リソースタイプを短縮して、エイリアス'rc'で置き換えることもできます。
kubectl get replicationcontroller <rc-name>
# すべてのReplicationControllerとServiceの一覧をまとめてプレーンテキスト形式で表示します。
kubectl get rc,services
# すべてのDaemonSetの一覧をプレーンテキスト形式で表示します。
kubectl get ds
# server01ードで実行中のPodの一覧をプレーンテキスト形式で表示します。
kubectl get pods --field-selector=spec.nodeName=server01
```
`kubectl describe` - 1つ以上のリソースの詳細な状態を、デフォルトでは初期化されないものも含めて表示します。
```shell
# Node <node-name>の詳細を表示します。
kubectl describe nodes <node-name>
# Pod <pod-name>の詳細を表示します。
kubectl describe pods/<pod-name>
# ReplicationController <rc-name>が管理しているすべてのPodの詳細を表示します。
# ReplicationControllerによって作成された任意のPodには、ReplicationControllerの名前がプレフィックスとして付与されます。
kubectl describe pods <rc-name>
# すべてのPodの詳細を表示します。
kubectl describe pods
```
{{< note >}}
`kubectl get`コマンドは通常、同じリソースタイプの1つ以上のリソースを取得するために使用します。豊富なフラグが用意されており、例えば`-o`や`--output`フラグを使って、出力フォーマットをカスタマイズできます。`-w`や`--watch`フラグを指定することで、特定のオブジェクトの更新を監視できます。`kubectl describe`コマンドは、指定されたリソースに関する多くの側面を説明することに重点を置いています。ユーザーに対してビューを構築するために、APIサーバーへ複数のAPIコールを呼び出すことができます。例えば、`kubectl describe node`コマンドは、Nodeに関する情報だけでなく、その上で動いているPodやNodeで生成されたイベントなどをまとめて表示します。
{{< /note >}}
`kubectl delete` - ファイル、標準出力、または指定したラベルセレクター、名前、リソースセレクター、リソースを指定して、リソースを削除します。
```shell
# pod.yamlファイルで指定されたタイプと名前を用いて、Podを削除します。
kubectl delete -f pod.yaml
# '<label-key>=<label-value>'というラベルを持つPodとServiceをすべて削除します。
kubectl delete pods,services -l <label-key>=<label-value>
# 初期化されていないPodを含む、すべてのPodを削除します。
kubectl delete pods --all
```
`kubectl exec` - Pod内のコンテナに対してコマンドを実行します。
```shell
# Pod <pod-name>から、'date'を実行している時の出力を取得します。デフォルトでは、最初のコンテナから出力されます。
kubectl exec <pod-name> -- date
# Pod <pod-name>のコンテナ <container-name>から、'date'を実行している時の出力を取得します。
kubectl exec <pod-name> -c <container-name> -- date
# インタラクティブな TTY を取得し、Pod <pod-name>から/bin/bashを実行します。デフォルトでは、最初のコンテナから出力されます。
kubectl exec -ti <pod-name> -- /bin/bash
```
`kubectl logs` - Pod内のコンテナのログを表示します。
```shell
# Pod <pod-name>のログのスナップショットを返します。
kubectl logs <pod-name>
# Pod <pod-name>から、ログのストリーミングを開始します。Linuxの'tail -f'コマンドと似ています。
kubectl logs -f <pod-name>
```
`kubectl diff` - 提案されたクラスタに対する更新の差分を表示します。
```shell
# pod.jsonに含まれるリソースの差分を表示します。
kubectl diff -f pod.json
# 標準出力から読み込んだファイルの差分を表示します。
cat service.yaml | kubectl diff -f -
```
## 例: プラグインの作成と使用
`kubectl`プラグインの書き方や使い方に慣れるために、以下の例を使用してください。
```shell
# 任意の言語でシンプルなプラグインを作成し、生成される実行可能なファイルに
# プレフィックス"kubectl-"で始まる名前を付けます。
cat ./kubectl-hello
```
```shell
#!/bin/sh
# このプラグインは、"hello world"という単語を表示します。
echo "hello world"
```
プラグインを書いたら、実行可能にします。
```bash
chmod a+x ./kubectl-hello
# さらに、PATH内の場所に移動させます。
sudo mv ./kubectl-hello /usr/local/bin
sudo chown root:root /usr/local/bin
# これでkubectlプラグインを作成し、"インストール"できました。
# 通常のコマンドのようにkubectlから呼び出すことで、プラグインを使用できます。
kubectl hello
```
```
hello world
```
```shell
# 配置したPATHのフォルダから削除することで、プラグインを"アンインストール"できます。
sudo rm /usr/local/bin/kubectl-hello
```
`kubectl`で利用可能なプラグインをすべて表示するには、`kubectl plugin list`サブコマンドを使用してください。
```shell
kubectl plugin list
```
出力は以下のようになります。
```
The following kubectl-compatible plugins are available:
/usr/local/bin/kubectl-hello
/usr/local/bin/kubectl-foo
/usr/local/bin/kubectl-bar
```
`kubectl plugin list`コマンドは、実行不可能なプラグインや、他のプラグインの影に隠れてしまっているプラグインなどについて、警告することもできます。例えば、以下のようになります。
```shell
sudo chmod -x /usr/local/bin/kubectl-foo # 実行権限を削除します。
kubectl plugin list
```
```
The following kubectl-compatible plugins are available:
/usr/local/bin/kubectl-hello
/usr/local/bin/kubectl-foo
- warning: /usr/local/bin/kubectl-foo identified as a plugin, but it is not executable
/usr/local/bin/kubectl-bar
error: one plugin warning was found
```
プラグインは、既存の`kubectl`コマンドの上に、より複雑な機能を構築するための手段であると考えることができます。
```shell
cat ./kubectl-whoami
```
次の例では、下記の内容を含んだ`kubectl-whoami`が既に作成済であることを前提としています。
```shell
#!/bin/bash
# このプラグインは、`kubectl config`コマンドを使って
# 現在選択されているコンテキストに基づいて、現在のユーザーに関する情報を提供します。
kubectl config view --template='{{ range .contexts }}{{ if eq .name "'$(kubectl config current-context)'" }}Current user: {{ printf "%s\n" .context.user }}{{ end }}{{ end }}'
```
上記のコマンドを実行すると、KUBECONFIGファイル内のカレントコンテキストのユーザーを含んだ出力を得られます。
```shell
# ファイルを実行可能にします。
sudo chmod +x ./kubectl-whoami
# さらに、ファイルをPATHに移動します。
sudo mv ./kubectl-whoami /usr/local/bin
kubectl whoami
Current user: plugins-user
```
## {{% heading "whatsnext" %}}
* [kubectl](/docs/reference/generated/kubectl/kubectl-commands/)を使い始めてください。
* プラグインについてより詳しく知りたい場合は, [example cli plugin](https://github.com/kubernetes/sample-cli-plugin)を御覧ください。

View File

@ -1,5 +1,5 @@
---
title: Scheduling
weight: 70
weight: 140
toc-hide: true
---

View File

@ -3,6 +3,7 @@ title: スケジューリングポリシー
content_type: concept
sitemap:
priority: 0.2 # スケジューリングポリシーは廃止されました。
weight: 30
---
<!-- overview -->

View File

@ -1,4 +1,4 @@
---
title: セットアップツールのリファレンス
weight: 50
weight: 100
---

View File

@ -1,7 +1,7 @@
---
title: API概要
content_type: concept
weight: 10
weight: 20
no_list: true
card:
name: reference

View File

@ -198,7 +198,7 @@ MinikubeのサポートするKubernetesの機能:
`minikube start`コマンドを使用してクラスターを起動することができます。
このコマンドはシングルードのKubernetesクラスターを実行する仮想マシンを作成・設定します。
また、このクラスターと通信する[kubectl](/ja/docs/reference/kubectl/overview/)のインストールも設定します。
また、このクラスターと通信する[kubectl](/ja/docs/reference/kubectl/)のインストールも設定します。
{{< note >}}
もしWebプロキシーを通している場合、そのプロキシー情報を`minikube start`コマンドに渡す必要があります:

View File

@ -231,7 +231,7 @@ See the [list of add-ons](/ja/docs/concepts/cluster-administration/addons/) to e
## {{% heading "whatsnext" %}}
* Learn more about Kubernetes [concepts](/docs/concepts/) and [`kubectl`](/docs/reference/kubectl/overview/).
* Learn more about Kubernetes [concepts](/docs/concepts/) and [`kubectl`](/ja/docs/reference/kubectl/).
* Learn more about `kops` [advanced usage](https://kops.sigs.k8s.io/) for tutorials, best practices and advanced configuration options.
* Follow `kops` community discussions on Slack: [community discussions](https://github.com/kubernetes/kops#other-ways-to-communicate-with-the-contributors)
* Contribute to `kops` by addressing or raising an issue [GitHub Issues](https://github.com/kubernetes/kops/issues)

View File

@ -394,7 +394,7 @@ kubectl delete node <node name>
* [Sonobuoy](https://github.com/heptio/sonobuoy)を使用してクラスターが適切に動作しているか検証する。
* <a id="lifecycle" />`kubeadm`を使用したクラスターをアップグレードする方法について、[kubeadmクラスターをアップグレードする](/docs/tasks/administer-cluster/kubeadm/kubeadm-upgrade/)を読む。
* `kubeadm`の高度な利用方法について[kubeadmリファレンスドキュメント](/docs/reference/setup-tools/kubeadm/kubeadm)で学ぶ。
* Kubernetesの[コンセプト](/ja/docs/concepts/)や[`kubectl`](/ja/docs/reference/kubectl/overview/)についてもっと学ぶ。
* Kubernetesの[コンセプト](/ja/docs/concepts/)や[`kubectl`](/ja/docs/reference/kubectl/)についてもっと学ぶ。
* Podネットワークアドオンのより完全なリストを[クラスターのネットワーク](/ja/docs/concepts/cluster-administration/networking/)で確認する。
* <a id="other-addons" />ロギング、モニタリング、ネットワークポリシー、仮想化、Kubernetesクラスターの制御のためのツールなど、その他のアドオンについて、[アドオンのリスト](/ja/docs/concepts/cluster-administration/addons/)で確認する。
* クラスターイベントやPod内で実行中のアプリケーションから送られるログをクラスターがハンドリングする方法を設定する。関係する要素の概要を理解するために、[ロギングのアーキテクチャ](/docs/concepts/cluster-administration/logging/)を読んでください。

View File

@ -365,7 +365,7 @@ Windowsでは、PodSecurityContextフィールドはどれも機能しません
## ヘルプとトラブルシューティングを学ぶ {#troubleshooting}
Kubernetesクラスターのトラブルシューティングの主なヘルプソースは、この[セクション](/docs/tasks/debug-application-cluster/troubleshooting/)から始める必要があります。このセクションには、いくつか追加的な、Windows固有のトラブルシューティングヘルプが含まれています。ログは、Kubernetesにおけるトラブルシューティング問題の重要な要素です。他のコントリビューターからトラブルシューティングの支援を求めるときは、必ずそれらを含めてください。SIG-Windows[ログ収集に関するコントリビュートガイド](https://github.com/kubernetes/community/blob/master/sig-windows/CONTRIBUTING.md#gathering-logs)の指示に従ってください。
Kubernetesクラスターのトラブルシューティングの主なヘルプソースは、[トラブルシューティング](/ja/docs/tasks/debug/)ページから始める必要があります。このセクションには、いくつか追加的な、Windows固有のトラブルシューティングヘルプが含まれています。ログは、Kubernetesにおけるトラブルシューティング問題の重要な要素です。他のコントリビューターからトラブルシューティングの支援を求めるときは、必ずそれらを含めてください。SIG-Windows[ログ収集に関するコントリビュートガイド](https://github.com/kubernetes/community/blob/master/sig-windows/CONTRIBUTING.md#gathering-logs)の指示に従ってください。
1. start.ps1が正常に完了したことをどのように確認できますか

View File

@ -20,7 +20,7 @@ Windowsアプリケーションは、多くの組織で実行されるサービ
## 始める前に
* [Windows Serverを実行するマスターードとワーカーード](/ja/docs/tasks/administer-cluster/kubeadm/adding-windows-nodes)を含むKubernetesクラスターを作成します
* Kubernetes上にServiceとワークロードを作成してデプロイすることは、LinuxコンテナとWindowsコンテナ共に、ほぼ同じように動作することに注意してください。クラスターとのインタフェースとなる[Kubectlコマンド](/docs/reference/kubectl/overview/)も同じです。Windowsコンテナをすぐに体験できる例を以下セクションに用意しています。
* Kubernetes上にServiceとワークロードを作成してデプロイすることは、LinuxコンテナとWindowsコンテナ共に、ほぼ同じように動作することに注意してください。クラスターとのインタフェースとなる[Kubectlコマンド](/ja/docs/reference/kubectl/)も同じです。Windowsコンテナをすぐに体験できる例を以下セクションに用意しています。
## はじめに:Windowsコンテナのデプロイ

View File

@ -7,13 +7,13 @@ weight: 120
<!-- overview -->
このページでは、KubernetesのPodをKubernetesクラスター上の特定のードに割り当てる方法を説明します。
## {{% heading "prerequisites" %}}
## {{% heading "prerequisites" %}} {#before-you-begin}
{{< include "task-tutorial-prereqs.md" >}} {{< version-check >}}
<!-- steps -->
## ラベルをノードに追加する
## ラベルをノードに追加する {#add-a-label-to-a-node}
1. クラスター内の{{< glossary_tooltip term_id="node" text="ノード" >}}のリストをラベル付きで表示します。
@ -54,7 +54,7 @@ weight: 120
上の出力を見ると、`worker0`に`disktype=ssd`というラベルがあることがわかります。
## 選択したードにスケジューリングされるPodを作成する
## 選択したードにスケジューリングされるPodを作成する {#create-a-pod-that-gets-scheduled-to-your-chosen-node}
以下のPodの構成ファイルには、nodeSelectorに`disktype: ssd`を持つPodが書かれています。これにより、Podは`disktype: ssd`というラベルを持っているノードにスケジューリングされるようになります。
@ -79,7 +79,7 @@ weight: 120
nginx 1/1 Running 0 13s 10.200.0.4 worker0
```
## 特定のードにスケジューリングされるPodを作成する
## 特定のードにスケジューリングされるPodを作成する {#create-a-pod-that-gets-scheduled-to-specific-node}
`nodeName`という設定を使用して、Podを特定のードにスケジューリングすることもできます。

Some files were not shown because too many files have changed in this diff Show More