- The Kubernetes and OpenShift Command-line Interfaces
- Guided Exercise:
The Kubernetes and OpenShift Command-line Interfaces
- Inspect Kubernetes Resources
- Guided Exercise:
Inspect Kubernetes Resources
- Assess the Health of an OpenShift Cluster
- Guided Exercise:
Assess the Health of an OpenShift Cluster
- Lab: Kubernetes and OpenShift Command-line Interfaces and APIs
- Quiz: Kubernetes and OpenShift Command-line Interfaces and APIs
- Summary
- Lab: Kubernetes and OpenShift Command-line Interfaces and APIs
Abstract
| Goal | |
| Objectives |
|
| Sections |
|
| Lab |
|
Access an OpenShift cluster by using the Kubernetes and OpenShift command-line interfaces.
You can manage an OpenShift cluster from the web console or by using the kubectl or oc command-line interfaces (CLI).
The kubectl commands are native to Kubernetes, and are a thin wrapper over the Kubernetes API.
The OpenShift oc commands are a superset of the kubectl commands, and add commands for the OpenShift-specific features.
In this course, examples of both the kubectl and the oc commands are shown, to highlight the differences between the commands.
With the oc command, you can create applications and manage Red Hat OpenShift Container Platform (RHOCP) projects from a terminal.
The OpenShift CLI is ideal in the following situations:
Working directly with project source code.
Scripting OpenShift Container Platform operations.
Managing projects that are restricted by bandwidth.
When the web console is unavailable.
Working with OpenShift resources, such as
routesanddeployment configs.
The oc CLI installation also includes an installation of the kubectl CLI, which is the recommended method for installing the kubectl CLI for OpenShift users.
You can also install the kubectl CLI independently of the oc CLI.
You must use a kubectl CLI version that is within one minor version difference of your cluster.
For example, a v1.26 client can communicate with v1.25, v1.26, and v1.27 control planes.
Using the latest compatible version of the kubectl CLI can help to avoid unforeseen issues.
To perform a manual installation of the kubectl binary for a Linux installation, you must first download the latest release by using the curl command.
[user@host ~]$ curl -LO "https://dl.k8s.io/release/$(curl -L \
-s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl"Then, you must download the kubectl checksum file and then validate the kubectl binary against the checksum file.
[user@host ~]$ curl -LO "https://dl.k8s.io/$(curl -L \
-s https://dl.k8s.io/release/stable.txt)/bin/linux/amd64/kubectl.sha256"[user@host ~]$ echo "$(cat kubectl.sha256) kubectl" | sha256sum --check
kubectl: OKIf the check fails, then the sha256sum command exits with nonzero status, and prints a kubectl: FAILED message.
You can then install the kubectl CLI.
[user@host ~]$ sudo install -o root -g root -m 0755 kubectl \
/usr/local/bin/kubectlNote
If you do not have root access on the target system, you can still install the kubectl CLI to the ~/.local/bin directory.
For more information, refer to https://kubernetes.io/docs/tasks/tools/install-kubectl-linux/.
Finally, use the kubectl version command to verify the installed version.
This command prints the client and server versions.
Use the --client option to view the client version only.
[user@host ~]$ kubectl version --clientAlternatively, a distribution that is based on Red Hat Enterprise Linux (RHEL) can install the kubectl CLI with the following command:
[user@host ~]$cat <<EOF | sudo tee /etc/yum.repos.d/kubernetes.repo [kubernetes] name=Kubernetes baseurl=https://packages.cloud.google.com/yum/repos/kubernetes-el7-\$basearch enabled=1 gpgcheck=1 gpgkey=https://packages.cloud.google.com/yum/doc/rpm-package-key.gpg EOF[user@host ~]$sudo yum install -y kubectl
To view a list of the available kubectl commands, use the kubectl --help command.
[user@host ~]$ kubectl --help
kubectl controls the Kubernetes cluster manager.
Find more information at:
https://kubernetes.io/docs/reference/kubectl/
Basic Commands (Beginner):
create Create a resource from a file or from stdin
expose Take a replication controller, service, deployment or pod and
expose it as a new Kubernetes Service
run Run a particular image on the cluster
set Set specific features on objects
Basic Commands (Intermediate):
...output omitted...You can also use the --help option on any command to view detailed information about the command, including its purpose, examples, available subcommands, and options.
For example, the following command provides information about the kubectl create command and its usage.
[user@host ~]$ kubectl create --help
Create a resource from a file or from stdin.
JSON and YAML formats are accepted.
Examples:
# Create a pod using the data in pod.json
kubectl create -f ./pod.json
# Create a pod based on the JSON passed into stdin
cat pod.json | kubectl create -f -
# Edit the data in registry.yaml in JSON then create the resource using the edited data
kubectl create -f registry.yaml --edit -o json
Available Commands:
clusterrole Create a cluster role
clusterrolebinfing Create a cluster role binding for a particular cluster role
...output omitted...Kubernetes uses many resource components to support applications.
The kubectl explain command provides detailed information about the attributes of a given resource.
For example, use the following command to learn more about the attributes of a pod resource.
[user@host ~]$ kubectl explain pod
KIND: Pod
VERSION: v1
DESCRIPTION:
Pod is a collection of containers that can run on a host. This resource is
created by clients and scheduled onto hosts.
FIELDS:
apiVersion <string>
APIVersion defines the versioned schema of this representation of an
object.
...output omitted...Refer to Kubernetes Documentation - Getting Started for further information about the kubectl commands.
The main method of interacting with an RHOCP cluster is by using the oc command.
You can download the oc CLI from the OpenShift web console to ensure that the CLI tools are compatible with the RHOCP cluster.
From the OpenShift web console, navigate to → .
The menu is represented by a ? icon.
The web console provides several installation options for the oc client, such as downloads for the following operating systems:
x86_64 Windows, Mac, and Linux systems
ARM 64 Linux and Mac systems
Linux for IBM Z, IBM Power, and little endian
The basic usage of the oc command is through its subcommands in the following syntax:
[user@host ~]$ oc commandBecause the oc CLI is a superset of the kubectl CLI, the version, --help, and explain commands are the same for both CLIs.
However, the oc CLI includes additional commands that are not included in the kubectl CLI, such as the oc login and oc new-project commands.
Developers who are familiar with Kubernetes can use the kubectl utility to manage a RHOCP cluster.
This course uses the oc command-line utility, to take advantage of additional RHOCP features.
The oc commands manage resources that are exclusive to RHOCP, such as projects, deployment configurations, routes, and image streams.
Before you can interact with your RHOCP cluster, you must authenticate your requests.
Use the oc login command to authenticate your requests.
The oc login command provides role-based authentication and authorization that protects the RHOCP cluster from unauthorized access.
The syntax to log in is shown below:
[user@host ~]$ oc login cluster-urlFor example, in this course, you can use the following command:
[user@host ~]$oc login https://api.ocp4.example.com:6443Username:developerPassword:developerLogin successful. You don't have any projects. You can try to create a new project, by running $ oc new-project <projectname> Welcome to OpenShift! See 'oc help' to get started.
After authenticating to the RHOCP cluster, you can create a project with the oc new-project command.
Projects provide isolation between your application resources.
Projects are Kubernetes namespaces with additional annotations that provide multitenancy scoping for applications.
[user@host ~]$ oc new-project myappSeveral essential commands can manage RHOCP and Kubernetes resources, as described here.
Unless otherwise specified, the following commands are compatible with both the oc and kubectl CLIs.
Some commands require a user with cluster administrator access.
The following list includes several useful oc commands for cluster administrators.
- oc cluster-info
The
cluster-infocommand prints the address of the control plane and other cluster services. Theoc cluster-info dumpcommand expands the output to include helpful details for debugging cluster problems.[user@host ~]$
oc cluster-infoKubernetes control plane is running at https://api.ocp4.example.com:6443 ...output omitted...- oc api-versions
The structure of cluster resources has a corresponding API version, which the
oc api-versionscommand displays. The command prints the supported API versions on the server, in the form of "group/version".In the following example, the group is
admissionregistration.k8s.ioand the version isv1:[user@host ~]$
oc api-versionsadmissionregistration.k8s.io/v1 ...output omitted...- oc get clusteroperator
The cluster operators that Red Hat ships serve as the architectural foundation for RHOCP. RHOCP installs cluster operators by default. Use the
oc get clusteroperatorcommand to see a list of the cluster operators:[user@host ~]$
oc get clusteroperatorNAME VERSION AVAILABLE PROGRESSING DEGRADED SINCE ... authentication 4.14.0 True False False 18d baremetal 4.14.0 True False False 18d ...output omitted...
Other useful commands are available to both regular and administrator users:
- oc get
Use the
getcommand to retrieve information about resources in the selected project. Generally, this command shows only the most important characteristics of the resources, and omits more detailed information.The
oc getcommand displays a summary of all resources of the specified type.RESOURCE_TYPEFor example, the following command returns the list of the
podresources in the current project:[user@host ~]$
oc get podNAME READY STATUS RESTARTS AGE quotes-api-6c9f758574-nk8kd 1/1 Running 0 39m quotes-ui-d7d457674-rbkl7 1/1 Running 0 67sYou can use the
oc getcommand to export a resource definition. Typical use cases include creating a backup or modifying a definition. TheRESOURCE_TYPERESOURCE_NAME-o yamloption prints the object representation in YAML format. You can change to JSON format by providing a-o jsonoption.- oc get all
Use the
oc get allcommand to retrieve a summary of the most important components of a cluster. This command iterates through the major resource types for the current project, and prints a summary of their information:[user@host ~]$
oc get allNAME DOCKER REPO TAGS UPDATED is/nginx 172.30.1.1:5000/basic-kubernetes/nginx latest About an hour ago NAME REVISION DESIRED CURRENT TRIGGERED BY dc/nginx 1 1 1 config,image(nginx:latest) NAME DESIRED CURRENT READY AGE rc/nginx-1 1 1 1 1h NAME CLUSTER-IP EXTERNAL-IP PORT(S) AGE svc/nginx 172.30.72.75 <none> 80/TCP,443/TCP 1h NAME READY STATUS RESTARTS AGE po/nginx-1-ypp8t 1/1 Running 0 1h- oc describe
If the summaries from the
getcommand are insufficient, then you can use theoc describecommand to retrieve additional information. Unlike theRESOURCE_TYPERESOURCE_NAMEgetcommand, you can use thedescribecommand to iterate through all the different resources by type. Although most major resources can be described, this function is not available across all resources. The following example demonstrates describing a pod resource:[user@host ~]$
oc describe mysql-openshift-1-glgrpName: mysql-openshift-1-glqrp Namespace: mysql-openshift Priority: 0 Node: cluster-worker-1/172.25.250.52 Start Time: Fri, 15 Feb 2019 02:14:34 +0000 Labels: app=mysql-openshift deployment=mysql-openshift-1 ...output omitted... Status: Running IP: 10.129.0.85- oc explain
To learn about the fields of an API resource object, use the
oc explaincommand. This command describes the purpose and the fields that are associated with each supported API resource. You can also use this command to print the documentation of a specific field of a resource. Fields are identified via a JSONPath identifier. The following example prints the documentation for the.spec.containers.resourcesfield of thepodresource type:[user@host ~]$
oc explain pods.spec.containers.resourcesKIND: Pod VERSION: v1 FIELD: resources <ResourceRequiremnts> DESCRIPTION: Compute Resources required by this container. Cannot be updated. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ ResourceRequirements describes the compute resource requirements. FIELDS: claims <[]ResourceClaim> Claims lists the names of resources, defined in spec.resourceClaims, that are used by this container. This is an alpha field nd requires enabling the DynamicResourceAllocation feature gate. This field is immutable. It can only be set for containers. limits <map[string]Quantity> Limits describes the maximum amount of compute resources allowed. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ requests <map[string]Quantity> Requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/
Add the --recursive flag to display all fields of a resource without descriptions.
Information about each field is retrieved from the server in OpenAPI format.
- oc create
Use the
createcommand to create a RHOCP resource in the current project. This command creates resources from a resource definition. Typically, this command is paired with theoc getcommand for editing definitions. Developers commonly use theRESOURCE_TYPERESOURCE_NAME-o yaml-fflag to indicate the file that contains the JSON or YAML representation of an RHOCP resource.For example, to create resources from the
pod.yamlfile, use the following command:[user@host ~]$
oc create -f pod.yamlpod/quotes-pod createdRHOCP resources in the YAML format are discussed later.
- oc status
The
oc statuscommand provides a high-level overview of the current project. The command shows services, deployments, build configurations, and active deployments. Information about any misconfigured components is also shown. The--suggestoption shows additional details for any identified issues.- oc delete
Use the
deletecommand to delete an existing RHOCP resource from the current project. You must specify the resource type and the resource name.For example, to delete the
quotes-uipod, use the following command:[user@host ~]$
oc delete pod quotes-uipod/quotes-ui deletedA fundamental understanding of the RHOCP architecture is needed here, because deleting managed resources, such as pods, results in the automatic creation of new instances of those resources. When a project is deleted, it deletes all the resources and applications within it.
Each of these commands is executed in the current selected project.
To execute commands in a different project, you must include the --namespace or -n options.
[user@host ~]$ oc get pods -n openshift-apiserver
NAME READY STATUS RESTARTS AGE
apiserver-68c9485699-ndqlc 2/2 Running 2 18dRefer to the references for a complete list of oc commands.
For users to interact with RHOCP, they must first authenticate to the cluster. The authentication layer identifies the user that is associated with requests to the RHOCP API. After authentication, the authorization layer then uses information about the requesting user to determine whether the request is allowed.
A user in OpenShift is an entity that can make requests to the RHOCP API.
An RHOCP User object represents an actor that can be granted permissions in the system by adding roles to the user or to the user's groups.
Typically, this represents the account of a developer or an administrator.
Several types of users can exist.
- Regular users
Most interactive RHOCP users are represented by this user type. An RHOCP
Userobject represents a regular user.- System users
Infrastructure uses system users to interact with the API securely. Some system users are automatically created, including the cluster administrator, with access to everything. By default, unauthenticated requests use an anonymous system user.
- Service accounts
ServiceAccountobjects represent service accounts. RHOCP creates service accounts automatically when a project is created. Project administrators can create additional service accounts to define access to the contents of each project.
Each user must authenticate to access a cluster. After authentication, policy determines what the user is authorized to do.
Note
Authentication and authorization are covered in greater detail in the "DO280: Red Hat OpenShift Administration II: Operating a Production Kubernetes Cluster" course.
The RHOCP control plane includes a built-in OAuth server. To authenticate themselves to the API, users obtain OAuth access tokens. Token authentication is the only guaranteed method to work with any OpenShift cluster, because enterprise Single Sign-On (SSO) might replace the login form of the web console.
When a person requests a new OAuth token, the OAuth server uses the configured identity provider to determine the identity of the person who makes the request. The OAuth server then determines the user that the identity maps to; creates an access token for that user; and then returns the token for use.
To retrieve an OAuth token by using the OpenShift web console, navigate to → .
The menu is represented by a ? icon.
On the Command Line Tools page, navigate to .
The following page requires you to log in with your OpenShift user credentials.
Next, navigate to .
Use the command under the Log in with this token label to log in to the OpenShift API.
Copy the command from the web console and paste it on the command line.
The copied command uses the --token and --server options, similar to the following example.
[user@host ~]$ oc login --token=sha256-BW...rA8 \
--server=https://api.ocp4.example.com:6443References
For more information, refer to the Getting Started with the OpenShift CLI chapter in the Red Hat OpenShift Container Platform 4.14 CLI Tools documentation at https://docs.redhat.com/en/documentation/openshift_container_platform/4.14/html-single/cli_tools/index#cli-about-cli_cli-developer-commands
For more information, refer to the CLI Developer Commands chapter in the Red Hat OpenShift Container Platform 4.14 CLI Tools documentation at Refer to the OpenShift CLI Developer Command Reference
Kubernetes Documentation - Install and Set Up kubectl on Linux