Openshift - Container - Platform 4.15 Cli - Tools en Us
Openshift - Container - Platform 4.15 Cli - Tools en Us
15
CLI tools
Learning how to use the command-line tools for OpenShift Container Platform
The text of and illustrations in this document are licensed by Red Hat under a Creative Commons
Attribution–Share Alike 3.0 Unported license ("CC-BY-SA"). An explanation of CC-BY-SA is
available at
http://creativecommons.org/licenses/by-sa/3.0/
. In accordance with CC-BY-SA, if you distribute this document or an adaptation of it, you must
provide the URL for the original version.
Red Hat, as the licensor of this document, waives the right to enforce, and agrees not to assert,
Section 4d of CC-BY-SA to the fullest extent permitted by applicable law.
Red Hat, Red Hat Enterprise Linux, the Shadowman logo, the Red Hat logo, JBoss, OpenShift,
Fedora, the Infinity logo, and RHCE are trademarks of Red Hat, Inc., registered in the United States
and other countries.
Linux ® is the registered trademark of Linus Torvalds in the United States and other countries.
XFS ® is a trademark of Silicon Graphics International Corp. or its subsidiaries in the United States
and/or other countries.
MySQL ® is a registered trademark of MySQL AB in the United States, the European Union and
other countries.
Node.js ® is an official trademark of Joyent. Red Hat is not formally related to or endorsed by the
official Joyent Node.js open source or commercial project.
The OpenStack ® Word Mark and OpenStack logo are either registered trademarks/service marks
or trademarks/service marks of the OpenStack Foundation, in the United States and other
countries and are used with the OpenStack Foundation's permission. We are not affiliated with,
endorsed or sponsored by the OpenStack Foundation, or the OpenStack community.
Abstract
This document provides information about installing, configuring, and using the command-line tools
for OpenShift Container Platform. It also contains a reference of CLI commands and examples of
how to use them.
Table of Contents
Table of Contents
.CHAPTER
. . . . . . . . . . 1.. .OPENSHIFT
. . . . . . . . . . . . .CONTAINER
. . . . . . . . . . . . .PLATFORM
. . . . . . . . . . . . .CLI
. . . .TOOLS
. . . . . . . .OVERVIEW
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
..............
1.1. LIST OF CLI TOOLS 10
.CHAPTER
. . . . . . . . . . 2.
. . OPENSHIFT
. . . . . . . . . . . . . CLI
. . . . (OC)
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11. . . . . . . . . . . . .
2.1. GETTING STARTED WITH THE OPENSHIFT CLI 11
2.1.1. About the OpenShift CLI 11
2.1.2. Installing the OpenShift CLI 11
2.1.2.1. Installing the OpenShift CLI by downloading the binary 11
Installing the OpenShift CLI on Linux 11
Installing the OpenShift CLI on Windows 12
Installing the OpenShift CLI on macOS 12
2.1.2.2. Installing the OpenShift CLI by using the web console 13
2.1.2.2.1. Installing the OpenShift CLI on Linux using the web console 13
2.1.2.2.2. Installing the OpenShift CLI on Windows using the web console 14
2.1.2.2.3. Installing the OpenShift CLI on macOS using the web console 15
2.1.2.3. Installing the OpenShift CLI by using an RPM 15
2.1.2.4. Installing the OpenShift CLI by using Homebrew 16
2.1.3. Logging in to the OpenShift CLI 17
2.1.4. Logging in to the OpenShift CLI using a web browser 18
2.1.5. Using the OpenShift CLI 19
2.1.5.1. Creating a project 19
2.1.5.2. Creating a new app 19
2.1.5.3. Viewing pods 19
2.1.5.4. Viewing pod logs 20
2.1.5.5. Viewing the current project 20
2.1.5.6. Viewing the status for the current project 20
2.1.5.7. Listing supported API resources 21
2.1.6. Getting help 21
2.1.7. Logging out of the OpenShift CLI 22
2.2. CONFIGURING THE OPENSHIFT CLI 23
2.2.1. Enabling tab completion 23
2.2.1.1. Enabling tab completion for Bash 23
2.2.1.2. Enabling tab completion for Zsh 23
2.3. USAGE OF OC AND KUBECTL COMMANDS 24
2.3.1. The oc binary 24
2.3.2. The kubectl binary 25
2.4. MANAGING CLI PROFILES 25
2.4.1. About switches between CLI profiles 25
2.4.2. Manual configuration of CLI profiles 27
2.4.3. Load and merge rules 29
2.5. EXTENDING THE OPENSHIFT CLI WITH PLUGINS 31
2.5.1. Writing CLI plugins 31
2.5.2. Installing and using CLI plugins 32
2.6. MANAGING CLI PLUGINS WITH KREW 32
2.6.1. Installing a CLI plugin with Krew 33
2.6.2. Updating a CLI plugin with Krew 33
2.6.3. Uninstalling a CLI plugin with Krew 34
2.6.4. Additional resources 34
2.7. OPENSHIFT CLI DEVELOPER COMMAND REFERENCE 34
2.7.1. OpenShift CLI (oc) developer commands 34
2.7.1.1. oc annotate 34
1
OpenShift Container Platform 4.15 CLI tools
2.7.1.2. oc api-resources 35
2.7.1.3. oc api-versions 35
2.7.1.4. oc apply 35
2.7.1.5. oc apply edit-last-applied 36
2.7.1.6. oc apply set-last-applied 36
2.7.1.7. oc apply view-last-applied 36
2.7.1.8. oc attach 37
2.7.1.9. oc auth can-i 37
2.7.1.10. oc auth reconcile 38
2.7.1.11. oc auth whoami 38
2.7.1.12. oc autoscale 38
2.7.1.13. oc cancel-build 38
2.7.1.14. oc cluster-info 39
2.7.1.15. oc cluster-info dump 39
2.7.1.16. oc completion 39
2.7.1.17. oc config current-context 40
2.7.1.18. oc config delete-cluster 40
2.7.1.19. oc config delete-context 41
2.7.1.20. oc config delete-user 41
2.7.1.21. oc config get-clusters 41
2.7.1.22. oc config get-contexts 41
2.7.1.23. oc config get-users 41
2.7.1.24. oc config new-admin-kubeconfig 41
2.7.1.25. oc config new-kubelet-bootstrap-kubeconfig 42
2.7.1.26. oc config refresh-ca-bundle 42
2.7.1.27. oc config rename-context 42
2.7.1.28. oc config set 42
2.7.1.29. oc config set-cluster 43
2.7.1.30. oc config set-context 43
2.7.1.31. oc config set-credentials 43
2.7.1.32. oc config unset 44
2.7.1.33. oc config use-context 44
2.7.1.34. oc config view 44
2.7.1.35. oc cp 45
2.7.1.36. oc create 45
2.7.1.37. oc create build 45
2.7.1.38. oc create clusterresourcequota 46
2.7.1.39. oc create clusterrole 46
2.7.1.40. oc create clusterrolebinding 46
2.7.1.41. oc create configmap 47
2.7.1.42. oc create cronjob 47
2.7.1.43. oc create deployment 47
2.7.1.44. oc create deploymentconfig 47
2.7.1.45. oc create identity 48
2.7.1.46. oc create imagestream 48
2.7.1.47. oc create imagestreamtag 48
2.7.1.48. oc create ingress 48
2.7.1.49. oc create job 49
2.7.1.50. oc create namespace 49
2.7.1.51. oc create poddisruptionbudget 49
2.7.1.52. oc create priorityclass 50
2.7.1.53. oc create quota 50
2.7.1.54. oc create role 50
2
Table of Contents
3
OpenShift Container Platform 4.15 CLI tools
2.7.1.108. oc replace 72
2.7.1.109. oc rollback 72
2.7.1.110. oc rollout cancel 72
2.7.1.111. oc rollout history 72
2.7.1.112. oc rollout latest 73
2.7.1.113. oc rollout pause 73
2.7.1.114. oc rollout restart 73
2.7.1.115. oc rollout resume 73
2.7.1.116. oc rollout retry 74
2.7.1.117. oc rollout status 74
2.7.1.118. oc rollout undo 74
2.7.1.119. oc rsh 74
2.7.1.120. oc rsync 75
2.7.1.121. oc run 75
2.7.1.122. oc scale 76
2.7.1.123. oc secrets link 76
2.7.1.124. oc secrets unlink 76
2.7.1.125. oc set build-hook 76
2.7.1.126. oc set build-secret 77
2.7.1.127. oc set data 77
2.7.1.128. oc set deployment-hook 77
2.7.1.129. oc set env 78
2.7.1.130. oc set image 78
2.7.1.131. oc set image-lookup 79
2.7.1.132. oc set probe 79
2.7.1.133. oc set resources 80
2.7.1.134. oc set route-backends 80
2.7.1.135. oc set selector 81
2.7.1.136. oc set serviceaccount 81
2.7.1.137. oc set subject 81
2.7.1.138. oc set triggers 81
2.7.1.139. oc set volumes 82
2.7.1.140. oc start-build 82
2.7.1.141. oc status 83
2.7.1.142. oc tag 83
2.7.1.143. oc version 84
2.7.1.144. oc wait 84
2.7.1.145. oc whoami 85
2.7.2. Additional resources 85
2.8. OPENSHIFT CLI ADMINISTRATOR COMMAND REFERENCE 85
2.8.1. OpenShift CLI (oc) administrator commands 85
2.8.1.1. oc adm build-chain 85
2.8.1.2. oc adm catalog mirror 85
2.8.1.3. oc adm certificate approve 86
2.8.1.4. oc adm certificate deny 86
2.8.1.5. oc adm copy-to-node 86
2.8.1.6. oc adm cordon 86
2.8.1.7. oc adm create-bootstrap-project-template 86
2.8.1.8. oc adm create-error-template 87
2.8.1.9. oc adm create-login-template 87
2.8.1.10. oc adm create-provider-selection-template 87
2.8.1.11. oc adm drain 87
2.8.1.12. oc adm groups add-users 87
4
Table of Contents
. . . . . . . . . . . 3.
CHAPTER . . IMPORTANT
. . . . . . . . . . . . . .UPDATE
. . . . . . . . . ON
. . . .ODO
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
...............
. . . . . . . . . . . 4.
CHAPTER . . .KNATIVE
. . . . . . . . . CLI
. . . . FOR
. . . . . USE
. . . . . WITH
. . . . . . OPENSHIFT
. . . . . . . . . . . . .SERVERLESS
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102
...............
4.1. KEY FEATURES 102
4.2. INSTALLING THE KNATIVE CLI 102
. . . . . . . . . . . 5.
CHAPTER . . PIPELINES
. . . . . . . . . . . .CLI
. . . .(TKN)
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103
...............
5.1. INSTALLING TKN 103
5
OpenShift Container Platform 4.15 CLI tools
5.1.1. Installing the Red Hat OpenShift Pipelines CLI on Linux 103
5.1.2. Installing the Red Hat OpenShift Pipelines CLI on Linux using an RPM 104
5.1.3. Installing the Red Hat OpenShift Pipelines CLI on Windows 105
5.1.4. Installing the Red Hat OpenShift Pipelines CLI on macOS 105
5.2. CONFIGURING THE OPENSHIFT PIPELINES TKN CLI 106
5.2.1. Enabling tab completion 106
5.3. OPENSHIFT PIPELINES TKN REFERENCE 106
5.3.1. Basic syntax 106
5.3.2. Global options 106
5.3.3. Utility commands 106
5.3.3.1. tkn 106
5.3.3.2. completion [shell] 107
5.3.3.3. version 107
5.3.4. Pipelines management commands 107
5.3.4.1. pipeline 107
5.3.4.2. pipeline delete 107
5.3.4.3. pipeline describe 107
5.3.4.4. pipeline list 107
5.3.4.5. pipeline logs 108
5.3.4.6. pipeline start 108
5.3.5. Pipeline run commands 108
5.3.5.1. pipelinerun 108
5.3.5.2. pipelinerun cancel 108
5.3.5.3. pipelinerun delete 108
5.3.5.4. pipelinerun describe 109
5.3.5.5. pipelinerun list 109
5.3.5.6. pipelinerun logs 109
5.3.6. Task management commands 109
5.3.6.1. task 109
5.3.6.2. task delete 109
5.3.6.3. task describe 110
5.3.6.4. task list 110
5.3.6.5. task logs 110
5.3.6.6. task start 110
5.3.7. Task run commands 110
5.3.7.1. taskrun 110
5.3.7.2. taskrun cancel 110
5.3.7.3. taskrun delete 111
5.3.7.4. taskrun describe 111
5.3.7.5. taskrun list 111
5.3.7.6. taskrun logs 111
5.3.8. Condition management commands 111
5.3.8.1. condition 111
5.3.8.2. condition delete 112
5.3.8.3. condition describe 112
5.3.8.4. condition list 112
5.3.9. Pipeline Resource management commands 112
5.3.9.1. resource 112
5.3.9.2. resource create 112
5.3.9.3. resource delete 112
5.3.9.4. resource describe 113
5.3.9.5. resource list 113
5.3.10. ClusterTask management commands 113
6
Table of Contents
. . . . . . . . . . . 6.
CHAPTER . . .GITOPS
. . . . . . . . CLI
. . . . FOR
. . . . . USE
. . . . .WITH
. . . . . .RED
. . . . .HAT
. . . . .OPENSHIFT
. . . . . . . . . . . . .GITOPS
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .119
..............
6.1. INSTALLING THE GITOPS CLI 119
6.2. ADDITIONAL RESOURCES 119
. . . . . . . . . . . 7.
CHAPTER . . OPM
. . . . . .CLI
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .120
...............
7.1. INSTALLING THE OPM CLI 120
7.1.1. About the opm CLI 120
7.1.2. Installing the opm CLI 120
7.1.3. Additional resources 121
7.2. OPM CLI REFERENCE 121
7.2.1. generate 122
7.2.1.1. dockerfile 122
7.2.2. index 123
7.2.2.1. add 124
7.2.2.2. prune 124
7.2.2.3. prune-stranded 125
7.2.2.4. rm 126
7.2.3. init 127
7.2.4. migrate 127
7.2.5. render 128
7
OpenShift Container Platform 4.15 CLI tools
.CHAPTER
. . . . . . . . . . 8.
. . .OPERATOR
. . . . . . . . . . . .SDK
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .130
...............
8.1. INSTALLING THE OPERATOR SDK CLI 130
8.1.1. Installing the Operator SDK CLI on Linux 130
8.1.2. Installing the Operator SDK CLI on macOS 131
8.2. OPERATOR SDK CLI REFERENCE 132
8.2.1. bundle 132
8.2.1.1. validate 132
8.2.2. cleanup 132
8.2.3. completion 133
8.2.4. create 133
8.2.4.1. api 133
8.2.5. generate 134
8.2.5.1. bundle 134
8.2.5.2. kustomize 135
8.2.5.2.1. manifests 135
8.2.6. init 136
8.2.7. run 136
8.2.7.1. bundle 136
8.2.7.2. bundle-upgrade 137
8.2.8. scorecard 138
8
Table of Contents
9
OpenShift Container Platform 4.15 CLI tools
Managing clusters
Developing Operators
OpenShift Container Platform offers a set of command-line interface (CLI) tools that simplify these
tasks by enabling users to perform various administration and development operations from the
terminal. These tools expose simple commands to manage the applications, as well as interact with each
component of the system.
OpenShift CLI (oc): This is the most commonly used CLI tool by OpenShift Container Platform
users. It helps both cluster administrators and developers to perform end-to-end operations
across OpenShift Container Platform using the terminal. Unlike the web console, it allows the
user to work directly with the project source code using command scripts.
Knative CLI (kn): The Knative (kn) CLI tool provides simple and intuitive terminal commands
that can be used to interact with OpenShift Serverless components, such as Knative Serving and
Eventing.
Pipelines CLI (tkn): OpenShift Pipelines is a continuous integration and continuous delivery
(CI/CD) solution in OpenShift Container Platform, which internally uses Tekton. The tkn CLI
tool provides simple and intuitive commands to interact with OpenShift Pipelines using the
terminal.
opm CLI: The opm CLI tool helps the Operator developers and cluster administrators to create
and maintain the catalogs of Operators from the terminal.
Operator SDK: The Operator SDK, a component of the Operator Framework, provides a CLI
tool that Operator developers can use to build, test, and deploy an Operator from the terminal.
It simplifies the process of building Kubernetes-native applications, which can require deep,
application-specific operational knowledge.
10
CHAPTER 2. OPENSHIFT CLI (OC)
Managing projects while restricted by bandwidth resources and the web console is unavailable
You can install the OpenShift CLI (oc) to interact with OpenShift Container Platform from a command-
line interface. You can install oc on Linux, Windows, or macOS.
IMPORTANT
If you installed an earlier version of oc, you cannot use it to complete all of the commands
in OpenShift Container Platform 4.15. Download and install the new version of oc.
Procedure
1. Navigate to the OpenShift Container Platform downloads page on the Red Hat Customer
Portal.
4. Click Download Now next to the OpenShift v4.15 Linux Client entry and save the file.
$ echo $PATH
11
OpenShift Container Platform 4.15 CLI tools
Verification
After you install the OpenShift CLI, it is available using the oc command:
$ oc <command>
Procedure
1. Navigate to the OpenShift Container Platform downloads page on the Red Hat Customer
Portal.
3. Click Download Now next to the OpenShift v4.15 Windows Client entry and save the file.
C:\> path
Verification
After you install the OpenShift CLI, it is available using the oc command:
C:\> oc <command>
Procedure
1. Navigate to the OpenShift Container Platform downloads page on the Red Hat Customer
Portal.
3. Click Download Now next to the OpenShift v4.15 macOS Client entry and save the file.
NOTE
For macOS arm64, choose the OpenShift v4.15 macOS arm64 Client entry.
$ echo $PATH
Verification
12
CHAPTER 2. OPENSHIFT CLI (OC)
Verification
After you install the OpenShift CLI, it is available using the oc command:
$ oc <command>
You can install the OpenShift CLI (oc) to interact with OpenShift Container Platform from a web
console. You can install oc on Linux, Windows, or macOS.
IMPORTANT
If you installed an earlier version of oc, you cannot use it to complete all of the commands
in OpenShift Container Platform 4.15. Download and install the new version of oc.
2.1.2.2.1. Installing the OpenShift CLI on Linux using the web console
You can install the OpenShift CLI (oc) binary on Linux by using the following procedure.
Procedure
3. Select appropriate oc binary for your Linux platform, and then click Download oc for Linux.
13
OpenShift Container Platform 4.15 CLI tools
$ echo $PATH
After you install the OpenShift CLI, it is available using the oc command:
$ oc <command>
2.1.2.2.2. Installing the OpenShift CLI on Windows using the web console
You can install the OpenShift CLI (oc) binary on Windows by using the following procedure.
Procedure
3. Select the oc binary for Windows platform, and then click Download oc for Windows for
x86_64.
C:\> path
After you install the OpenShift CLI, it is available using the oc command:
C:\> oc <command>
14
CHAPTER 2. OPENSHIFT CLI (OC)
2.1.2.2.3. Installing the OpenShift CLI on macOS using the web console
You can install the OpenShift CLI (oc) binary on macOS by using the following procedure.
Procedure
3. Select the oc binary for macOS platform, and then click Download oc for Mac for x86_64.
NOTE
For macOS arm64, click Download oc for Mac for ARM 64.
$ echo $PATH
After you install the OpenShift CLI, it is available using the oc command:
$ oc <command>
For Red Hat Enterprise Linux (RHEL), you can install the OpenShift CLI (oc) as an RPM if you have an
active OpenShift Container Platform subscription on your Red Hat account.
NOTE
15
OpenShift Container Platform 4.15 CLI tools
NOTE
It is not supported to install the OpenShift CLI (oc) as an RPM for Red Hat Enterprise
Linux (RHEL) 9. You must install the OpenShift CLI for RHEL 9 by downloading the
binary.
Prerequisites
Procedure
# subscription-manager register
# subscription-manager refresh
4. In the output for the previous command, find the pool ID for an OpenShift Container Platform
subscription and attach the subscription to the registered system:
$ oc <command>
For macOS, you can install the OpenShift CLI (oc) by using the Homebrew package manager.
Prerequisites
Procedure
16
CHAPTER 2. OPENSHIFT CLI (OC)
Prerequisites
NOTE
To access a cluster that is accessible only over an HTTP proxy server, you can set the
HTTP_PROXY, HTTPS_PROXY and NO_PROXY variables. These environment variables
are respected by the oc CLI so that all communication with the cluster goes through the
HTTP proxy.
Procedure
$ oc login -u user1
Example output
You don't have any projects. You can try to create a new project, by running
oc new-project <projectname>
17
OpenShift Container Platform 4.15 CLI tools
NOTE
If you are logged in to the web console, you can generate an oc login command that
includes your token and server information. You can use the command to log in to the
OpenShift Container Platform CLI without the interactive prompts. To generate the
command, select Copy login command from the username drop-down menu at the top
right of the web console.
You can now create a project or issue other commands for managing your cluster.
WARNING
Logging in to the CLI through the web browser runs a server on localhost with
HTTP, not HTTPS; use with caution on multi-user workstations.
Prerequisites
Procedure
1 Optionally, you can specify the server URL and callback port. For example, oc login
<cluster_url> --web --callback-port 8280 localhost:8443.
2. The web browser opens automatically. If it does not, click the link in the command output. If you
do not specify the OpenShift Container Platform server oc tries to open the web console of the
cluster specified in the current oc configuration file. If no oc configuration exists, oc prompts
interactively for the server URL.
Example output
3. If more than one identity provider is available, select your choice from the options provided.
4. Enter your username and password into the corresponding browser fields. After you are logged
18
CHAPTER 2. OPENSHIFT CLI (OC)
4. Enter your username and password into the corresponding browser fields. After you are logged
in, the browser displays the text access token received successfully; please return to your
terminal.
Example output
Login successful.
You don't have any projects. You can try to create a new project, by running
oc new-project <projectname>
NOTE
The web console defaults to the profile used in the previous session. To switch between
Administrator and Developer profiles, log out of the OpenShift Container Platform web
console and clear the cache.
You can now create a project or issue other commands for managing your cluster.
$ oc new-project my-project
Example output
$ oc new-app https://github.com/sclorg/cakephp-ex
Example output
--> Found image 40de956 (9 days old) in imagestream "openshift/php" under tag "7.2" for "php"
...
19
OpenShift Container Platform 4.15 CLI tools
Use the oc get pods command to view the pods for the current project.
NOTE
When you run oc inside a pod and do not specify a namespace, the namespace of the
pod is used by default.
Example output
$ oc logs cakephp-ex-1-deploy
Example output
$ oc project
Example output
Use the oc status command to view information about the current project, such as services,
deployments, and build configs.
$ oc status
Example output
20
CHAPTER 2. OPENSHIFT CLI (OC)
Use the oc api-resources command to view the list of supported API resources on the server.
$ oc api-resources
Example output
Use oc help to get a list and description of all available CLI commands:
$ oc help
Example output
OpenShift Client
This client helps you develop, build, deploy, and run your applications on any OpenShift or
Kubernetes compatible
platform. It also includes the administrative commands for managing a cluster under the 'adm'
subcommand.
Usage:
oc [flags]
Basic Commands:
login Log in to a server
new-project Request a new project
new-app Create a new application
...
21
OpenShift Container Platform 4.15 CLI tools
Use the --help flag to get help about a specific CLI command:
$ oc create --help
Example output
Usage:
oc create -f FILENAME [flags]
...
Use the oc explain command to view the description and fields for a particular resource:
$ oc explain pods
Example output
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. Servers should convert recognized schemas to the latest internal
value, and may reject unrecognized values. More info:
https://git.k8s.io/community/contributors/devel/api-conventions.md#resources
...
$ oc logout
Example output
22
CHAPTER 2. OPENSHIFT CLI (OC)
This deletes the saved authentication token from the server and removes it from your configuration file.
After you install the OpenShift CLI (oc), you can enable tab completion to automatically complete oc
commands or suggest options when you press Tab. The following procedure enables tab completion for
the Bash shell.
Prerequisites
Procedure
You can also save the file to a local directory and source it from your .bashrc file instead.
After you install the OpenShift CLI (oc), you can enable tab completion to automatically complete oc
commands or suggest options when you press Tab. The following procedure enables tab completion for
the Zsh shell.
Prerequisites
Procedure
To add tab completion for oc to your .zshrc file, run the following command:
$ cat >>~/.zshrc<<EOF
if [ $commands[oc] ]; then
source <(oc completion zsh)
23
OpenShift Container Platform 4.15 CLI tools
compdef _oc oc
fi
EOF
Authentication
The oc binary offers a built-in login command for authentication and lets you work with
projects, which map Kubernetes namespaces to authenticated users. Read Understanding
authentication for more information.
Additional commands
The additional command oc new-app, for example, makes it easier to get new applications
started using existing source code or pre-built images. Similarly, the additional command oc
new-project makes it easier to start a project that you can switch to as your default.
IMPORTANT
If you installed an earlier version of the oc binary, you cannot use it to complete all of the
commands in OpenShift Container Platform 4.15 . If you want the latest features, you
must download and install the latest version of the oc binary corresponding to your
OpenShift Container Platform server version.
Non-security API changes will involve, at minimum, two minor releases (4.1 to 4.2 to 4.3, for example) to
allow older oc binaries to update. Using new capabilities might require newer oc binaries. A 4.3 server
might have additional capabilities that a 4.2 oc binary cannot use and a 4.3 oc binary might have
additional capabilities that are unsupported by a 4.2 server.
24
CHAPTER 2. OPENSHIFT CLI (OC)
X.Y (Server)
X.Y+N footnote:versionpolicyn[]
(Server)
Fully compatible.
oc client might provide options and features that might not be compatible with the accessed
server.
You can install the supported kubectl binary by following the steps to Install the OpenShift CLI. The
kubectl binary is included in the archive if you download the binary, or is installed when you install the
CLI by using an RPM.
apiVersion: v1
clusters: 1
- cluster:
insecure-skip-tls-verify: true
server: https://openshift1.example.com:8443
name: openshift1.example.com:8443
- cluster:
25
OpenShift Container Platform 4.15 CLI tools
insecure-skip-tls-verify: true
server: https://openshift2.example.com:8443
name: openshift2.example.com:8443
contexts: 2
- context:
cluster: openshift1.example.com:8443
namespace: alice-project
user: alice/openshift1.example.com:8443
name: alice-project/openshift1.example.com:8443/alice
- context:
cluster: openshift1.example.com:8443
namespace: joe-project
user: alice/openshift1.example.com:8443
name: joe-project/openshift1/alice
current-context: joe-project/openshift1.example.com:8443/alice 3
kind: Config
preferences: {}
users: 4
- name: alice/openshift1.example.com:8443
user:
token: xZHd2piv5_9vQrg-SKXRJ2Dsl9SceNJdhNTljEKTb8k
1 The clusters section defines connection details for OpenShift Container Platform clusters,
including the address for their master server. In this example, one cluster is nicknamed
openshift1.example.com:8443 and another is nicknamed openshift2.example.com:8443.
4 The users section defines user credentials. In this example, the user nickname
alice/openshift1.example.com:8443 uses an access token.
The CLI can support multiple configuration files which are loaded at runtime and merged together along
with any override options specified from the command line. After you are logged in, you can use the oc
status or oc project command to verify your current working environment:
$ oc status
Example output
oc status
In project Joe's Project (joe-project)
26
CHAPTER 2. OPENSHIFT CLI (OC)
To see more information about a service or deployment, use 'oc describe service <name>' or 'oc
describe dc <name>'.
You can use 'oc get all' to see lists of each of the types described in this example.
$ oc project
Example output
You can run the oc login command again and supply the required information during the interactive
process, to log in using any other combination of user credentials and cluster details. A context is
constructed based on the supplied information if one does not already exist. If you are already logged in
and want to switch to another project the current user already has access to, use the oc project
command and enter the name of the project:
$ oc project alice-project
Example output
At any time, you can use the oc config view command to view your current CLI configuration, as seen in
the output. Additional CLI configuration commands are also available for more advanced usage.
NOTE
If you have access to administrator credentials but are no longer logged in as the default
system user system:admin, you can log back in as this user at any time as long as the
credentials are still present in your CLI config file. The following command logs in and
switches to the default project:
NOTE
This section covers more advanced usage of CLI configurations. In most situations, you
can use the oc login and oc project commands to log in and switch between contexts
and projects.
27
OpenShift Container Platform 4.15 CLI tools
If you want to manually configure your CLI config files, you can use the oc config command instead of
directly modifying the files. The oc config command includes a number of helpful sub-commands for
this purpose:
Subcom Usage
mand
set- Sets a cluster entry in the CLI config file. If the referenced cluster nickname already exists, the
cluster specified information is merged in.
set- Sets a context entry in the CLI config file. If the referenced context nickname already exists, the
context specified information is merged in.
use- Sets the current context using the specified context nickname.
context
$ oc config use-context <context_nickname>
The <property_name> is a dot-delimited name where each token represents either an attribute
name or a map key. The <property_value> is the new value being set.
The <property_name> is a dot-delimited name where each token represents either an attribute
name or a map key.
$ oc config view
Example usage
28
CHAPTER 2. OPENSHIFT CLI (OC)
Log in as a user that uses an access token. This token is used by the alice user:
$ oc login https://openshift1.example.com --
token=ns7yVhuRNpDM9cgzfhhxQ7bM5s7N2ZVrkZepSRf4LC0
$ oc config view
Example output
apiVersion: v1
clusters:
- cluster:
insecure-skip-tls-verify: true
server: https://openshift1.example.com
name: openshift1-example-com
contexts:
- context:
cluster: openshift1-example-com
namespace: default
user: alice/openshift1-example-com
name: default/openshift1-example-com/alice
current-context: default/openshift1-example-com/alice
kind: Config
preferences: {}
users:
- name: alice/openshift1.example.com
user:
token: ns7yVhuRNpDM9cgzfhhxQ7bM5s7N2ZVrkZepSRf4LC0
Update the current context to have users log in to the desired namespace:
Examine the current context, to confirm that the changes are implemented:
$ oc whoami -c
All subsequent CLI operations uses the new context, unless otherwise specified by overriding CLI
options or until the context is switched.
CLI config files are retrieved from your workstation, using the following hierarchy and merge
rules:
If the --config option is set, then only that file is loaded. The flag is set once and no merging
takes place.
If the $KUBECONFIG environment variable is set, then it is used. The variable can be a list
29
OpenShift Container Platform 4.15 CLI tools
of paths, and if so the paths are merged together. When a value is modified, it is modified in
the file that defines the stanza. When a value is created, it is created in the first file that
exists. If no files in the chain exist, then it creates the last file in the list.
The context to use is determined based on the first match in the following flow:
The user and cluster to use is determined. At this point, you may or may not have a context; they
are built based on the first match in the following flow, which is run once for the user and once
for the cluster:
The value of the --user for user name and --cluster option for cluster name.
The actual cluster information to use is determined. At this point, you may or may not have
cluster information. Each piece of the cluster information is built based on the first match in the
following flow:
--server,
--api-version
--certificate-authority
--insecure-skip-tls-verify
If cluster information and a value for the attribute is present, then use it.
The actual user information to use is determined. Users are built using the same rules as clusters,
except that you can only have one authentication technique per user; conflicting techniques
cause the operation to fail. Command line options take precedence over config file values. Valid
command line options are:
--auth-path
--client-certificate
--client-key
--token
For any information that is still missing, default values are used and prompts are given for
additional information.
30
CHAPTER 2. OPENSHIFT CLI (OC)
Procedure
This procedure creates a simple Bash plugin that prints a message to the terminal when the oc foo
command is issued.
The file name determines the command that invokes the plugin. For example, a plugin with
the file name oc-foo-bar can be invoked by a command of oc foo bar. You can also use
underscores if you want the command to contain dashes. For example, a plugin with the file
name oc-foo_bar can be invoked by a command of oc foo-bar.
#!/bin/bash
After you install this plugin for the OpenShift Container Platform CLI, it can be invoked using the oc foo
command.
Additional resources
Review the Sample plugin repository for an example of a plugin written in Go.
Review the CLI runtime repository for a set of utilities to assist in writing plugins in Go.
31
OpenShift Container Platform 4.15 CLI tools
Prerequisites
You must have a CLI plugin file that begins with oc- or kubectl-.
Procedure
$ chmod +x <plugin_file>
$ oc plugin list
Example output
/usr/local/bin/<plugin_file>
If your plugin is not listed here, verify that the file begins with oc- or kubectl-, is executable, and
is on your PATH.
$ oc ns
Note that the command to invoke the plugin depends on the plugin file name. For example, a
plugin with the file name of oc-foo-bar is invoked by the oc foo bar command.
IMPORTANT
32
CHAPTER 2. OPENSHIFT CLI (OC)
IMPORTANT
Using Krew to install and manage plugins for the OpenShift CLI is a Technology Preview
feature only. Technology Preview features are not supported with Red Hat production
service level agreements (SLAs) and might not be functionally complete. Red Hat does
not recommend using them in production. These features provide early access to
upcoming product features, enabling customers to test functionality and provide
feedback during the development process.
For more information about the support scope of Red Hat Technology Preview features,
see Technology Preview Features Support Scope .
Prerequisites
You have installed Krew by following the installation procedure in the Krew documentation.
Procedure
$ oc krew search
4. To list all plugins that were installed by Krew, run the following command:
$ oc krew list
Prerequisites
You have installed Krew by following the installation procedure in the Krew documentation.
You have installed a plugin for the OpenShift CLI with Krew.
Procedure
33
OpenShift Container Platform 4.15 CLI tools
To update all plugins that were installed by Krew, run the following command:
$ oc krew upgrade
Prerequisites
You have installed Krew by following the installation procedure in the Krew documentation.
You have installed a plugin for the OpenShift CLI with Krew.
Procedure
Run oc help to list all commands or run oc <command> --help to get additional details for a specific
command.
2.7.1.1. oc annotate
Example usage
# Update pod 'foo' with the annotation 'description' and the value 'my frontend'
# If the same annotation is set multiple times, only the last value will be applied
oc annotate pods foo description='my frontend'
# Update pod 'foo' with the annotation 'description' and the value 'my frontend running nginx',
overwriting any existing value
oc annotate --overwrite pods foo description='my frontend running nginx'
34
CHAPTER 2. OPENSHIFT CLI (OC)
2.7.1.2. oc api-resources
Example usage
2.7.1.3. oc api-versions
Print the supported API versions on the server, in the form of "group/version"
Example usage
2.7.1.4. oc apply
Example usage
35
OpenShift Container Platform 4.15 CLI tools
# Apply the configuration from all files that end with '.json'
oc apply -f '*.json'
# Apply the configuration in manifest.yaml and delete all the other config maps that are not in the file
oc apply --prune -f manifest.yaml --all --prune-allowlist=core/v1/ConfigMap
Example usage
Set the last-applied-configuration annotation on a live object to match the contents of a file
Example usage
# Set the last-applied-configuration of a resource to match the contents of a file; will create the
annotation if it does not already exist
oc apply set-last-applied -f deploy.yaml --create-annotation=true
Example usage
36
CHAPTER 2. OPENSHIFT CLI (OC)
2.7.1.8. oc attach
Example usage
# Get output from running pod mypod; use the 'oc.kubernetes.io/default-container' annotation
# for selecting the container to be attached or the first container in the pod will be chosen
oc attach mypod
# Switch to raw terminal mode; sends stdin to 'bash' in ruby-container from pod mypod
# and sends stdout/stderr from 'bash' back to the client
oc attach mypod -c ruby-container -i -t
# Get output from the first pod of a replica set named nginx
oc attach rs/nginx
Example usage
# Check to see if service account "foo" of namespace "dev" can list pods
# in the namespace "prod".
# You must be allowed to use impersonation for the global option "--as".
oc auth can-i list pods --as=system:serviceaccount:dev:foo -n prod
# Check to see if I can get the job named "bar" in namespace "foo"
oc auth can-i list jobs.batch/bar -n foo
37
OpenShift Container Platform 4.15 CLI tools
Reconciles rules for RBAC role, role binding, cluster role, and cluster role binding objects
Example usage
Example usage
2.7.1.12. oc autoscale
Autoscale a deployment config, deployment, replica set, stateful set, or replication controller
Example usage
# Auto scale a deployment "foo", with the number of pods between 2 and 10, no target CPU
utilization specified so a default autoscaling policy will be used
oc autoscale deployment foo --min=2 --max=10
# Auto scale a replication controller "foo", with the number of pods between 1 and 5, target CPU
utilization at 80%
oc autoscale rc foo --max=5 --cpu-percent=80
2.7.1.13. oc cancel-build
Example usage
# Cancel the named build and create a new one with the same parameters
38
CHAPTER 2. OPENSHIFT CLI (OC)
# Cancel all builds created from the 'ruby-build' build config that are in the 'new' state
oc cancel-build bc/ruby-build --state=new
2.7.1.14. oc cluster-info
Example usage
Example usage
2.7.1.16. oc completion
Output shell completion code for the specified shell (bash, zsh, fish, or powershell)
Example usage
39
OpenShift Container Platform 4.15 CLI tools
# Load the oc completion code for zsh[1] into the current shell
source <(oc completion zsh)
# Set the oc completion code for zsh[1] to autoload on startup
oc completion zsh > "${fpath[1]}/_oc"
# Load the oc completion code for fish[2] into the current shell
oc completion fish | source
# To load completions for each session, execute once:
oc completion fish > ~/.config/fish/completions/oc.fish
# Load the oc completion code for powershell into the current shell
oc completion powershell | Out-String | Invoke-Expression
# Set oc completion code for powershell to run on startup
## Save completion code to a script and execute in the profile
oc completion powershell > $HOME\.kube\completion.ps1
Add-Content $PROFILE "$HOME\.kube\completion.ps1"
## Execute completion code in the profile
Add-Content $PROFILE "if (Get-Command oc -ErrorAction SilentlyContinue) {
oc completion powershell | Out-String | Invoke-Expression
}"
## Add completion code directly to the $PROFILE script
oc completion powershell >> $PROFILE
Example usage
Example usage
40
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
Example usage
Example usage
Example usage
Example usage
41
OpenShift Container Platform 4.15 CLI tools
Example usage
Generate, make the server trust, and display a new kubelet /etc/kubernetes/kubeconfig.
Example usage
Example usage
# Refresh the CA bundle for the cluster named e2e in your kubeconfig
oc config refresh-ca-bundle e2e
Example usage
Example usage
42
CHAPTER 2. OPENSHIFT CLI (OC)
# Set the client-key-data field in the cluster-admin user using --set-raw-bytes option
oc config set users.cluster-admin.client-key-data cert_data_here --set-raw-bytes=true
Example usage
# Set only the server field on the e2e cluster entry without touching other values
oc config set-cluster e2e --server=https://1.2.3.4
# Set the custom TLS server name to use for validation for the e2e cluster entry
oc config set-cluster e2e --tls-server-name=my-cluster-name
Example usage
# Set the user field on the gce context entry without touching other values
oc config set-context gce --user=cluster-admin
Example usage
# Enable the Google Compute Platform auth provider for the "cluster-admin" entry
oc config set-credentials cluster-admin --auth-provider=gcp
43
OpenShift Container Platform 4.15 CLI tools
# Enable the OpenID Connect auth provider for the "cluster-admin" entry with additional arguments
oc config set-credentials cluster-admin --auth-provider=oidc --auth-provider-arg=client-id=foo --auth-
provider-arg=client-secret=bar
# Remove the "client-secret" config value for the OpenID Connect auth provider for the "cluster-
admin" entry
oc config set-credentials cluster-admin --auth-provider=oidc --auth-provider-arg=client-secret-
# Define new exec auth plugin arguments for the "cluster-admin" entry
oc config set-credentials cluster-admin --exec-arg=arg1 --exec-arg=arg2
# Create or update exec auth plugin environment variables for the "cluster-admin" entry
oc config set-credentials cluster-admin --exec-env=key1=val1 --exec-env=key2=val2
# Remove exec auth plugin environment variables for the "cluster-admin" entry
oc config set-credentials cluster-admin --exec-env=var-to-remove-
Example usage
Example usage
Example usage
# Show merged kubeconfig settings, raw certificate data, and exposed secrets
oc config view --raw
44
CHAPTER 2. OPENSHIFT CLI (OC)
2.7.1.35. oc cp
Example usage
# !!!Important Note!!!
# Requires that the 'tar' binary is present in your container
# image. If 'tar' is not present, 'oc cp' will fail.
#
# For advanced use cases, such as symlinks, wildcard expansion or
# file mode preservation, consider using 'oc exec'.
# Copy /tmp/foo_dir local directory to /tmp/bar_dir in a remote pod in the default namespace
oc cp /tmp/foo_dir <some-pod>:/tmp/bar_dir
2.7.1.36. oc create
Example usage
# Edit the data in registry.yaml in JSON then create the resource using the edited data
oc create -f registry.yaml --edit -o json
45
OpenShift Container Platform 4.15 CLI tools
Example usage
Example usage
Example usage
# Create a cluster role named "pod-reader" that allows user to perform "get", "watch" and "list" on
pods
oc create clusterrole pod-reader --verb=get,list,watch --resource=pods
Example usage
# Create a cluster role binding for user1, user2, and group1 using the cluster-admin cluster role
oc create clusterrolebinding cluster-admin --clusterrole=cluster-admin --user=user1 --user=user2 --
group=group1
46
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
# Create a new config map named my-config with specified keys instead of file basenames on disk
oc create configmap my-config --from-file=key1=/path/to/bar/file1.txt --from-
file=key2=/path/to/bar/file2.txt
# Create a new config map named my-config with key1=config1 and key2=config2
oc create configmap my-config --from-literal=key1=config1 --from-literal=key2=config2
# Create a new config map named my-config from the key=value pairs in the file
oc create configmap my-config --from-file=path/to/bar
Example usage
Example usage
# Create a deployment named my-dep that runs the nginx image with 3 replicas
oc create deployment my-dep --image=nginx --replicas=3
# Create a deployment named my-dep that runs the busybox image and expose port 5701
oc create deployment my-dep --image=busybox --port=5701
47
OpenShift Container Platform 4.15 CLI tools
Create a deployment config with default options that uses a given image
Example usage
Example usage
# Create an identity with identity provider "acme_ldap" and the identity provider username
"adamjones"
oc create identity acme_ldap:adamjones
Example usage
Example usage
Example usage
# Create a single ingress called 'simple' that directs requests to foo.com/bar to svc
# svc1:8080 with a TLS secret "my-cert"
oc create ingress simple --rule="foo.com/bar=svc1:8080,tls=my-cert"
# Create a catch all ingress of "/path" pointing to service svc:port and Ingress Class as
"otheringress"
oc create ingress catch-all --class=otheringress --rule="/path=svc:port"
48
CHAPTER 2. OPENSHIFT CLI (OC)
--annotation ingress.annotation2=bla
# Create an ingress with TLS enabled using the default ingress certificate and different path types
oc create ingress ingtls --class=default \
--rule="foo.com/=svc:https,tls" \
--rule="foo.com/path/subpath*=othersvc:8080"
# Create an ingress with TLS enabled using a specific secret and pathType as Prefix
oc create ingress ingsecret --class=default \
--rule="foo.com/*=svc:8080,tls=secret1"
Example usage
# Create a job
oc create job my-job --image=busybox
Example usage
49
OpenShift Container Platform 4.15 CLI tools
Example usage
# Create a pod disruption budget named my-pdb that will select all pods with the app=rails label
# and require at least one of them being available at any point in time
oc create poddisruptionbudget my-pdb --selector=app=rails --min-available=1
# Create a pod disruption budget named my-pdb that will select all pods with the app=nginx label
# and require at least half of the pods selected to be available at any point in time
oc create pdb my-pdb --selector=app=nginx --min-available=50%
Example usage
# Create a priority class named default-priority that is considered as the global default priority
oc create priorityclass default-priority --value=1000 --global-default=true --description="default
priority"
# Create a priority class named high-priority that cannot preempt pods with lower priority
oc create priorityclass high-priority --value=1000 --description="high priority" --preemption-
policy="Never"
Example usage
Example usage
# Create a role named "pod-reader" that allows user to perform "get", "watch" and "list" on pods
oc create role pod-reader --verb=get --verb=list --verb=watch --resource=pods
50
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
# Create a role binding for user1, user2, and group1 using the admin cluster role
oc create rolebinding admin --clusterrole=admin --user=user1 --user=user2 --group=group1
# Create a role binding for serviceaccount monitoring:sa-dev using the admin role
oc create rolebinding admin-binding --role=admin --serviceaccount=monitoring:sa-dev
Example usage
# Create an edge route named "my-route" that exposes the frontend service
oc create route edge my-route --service=frontend
# Create an edge route that exposes the frontend service and specify a path
# If the route name is omitted, the service name will be used
oc create route edge --service=frontend --path /assets
Example usage
# Create a passthrough route named "my-route" that exposes the frontend service
oc create route passthrough my-route --service=frontend
# Create a passthrough route that exposes the frontend service and specify
# a host name. If the route name is omitted, the service name will be used
oc create route passthrough --service=frontend --hostname=www.example.com
Example usage
51
OpenShift Container Platform 4.15 CLI tools
# Create a reencrypt route that exposes the frontend service, letting the
# route name default to the service name and the destination CA certificate
# default to the service CA
oc create route reencrypt --service=frontend
Example usage
# If you do not already have a .dockercfg file, create a dockercfg secret directly
oc create secret docker-registry my-secret --docker-server=DOCKER_REGISTRY_SERVER --
docker-username=DOCKER_USER --docker-password=DOCKER_PASSWORD --docker-
email=DOCKER_EMAIL
Example usage
# Create a new secret named my-secret with keys for each file in folder bar
oc create secret generic my-secret --from-file=path/to/bar
# Create a new secret named my-secret with specified keys instead of names on disk
oc create secret generic my-secret --from-file=ssh-privatekey=path/to/id_rsa --from-file=ssh-
publickey=path/to/id_rsa.pub
# Create a new secret named my-secret using a combination of a file and a literal
oc create secret generic my-secret --from-file=ssh-privatekey=path/to/id_rsa --from-
literal=passphrase=topsecret
Example usage
# Create a new TLS secret named tls-secret with the given key pair
oc create secret tls tls-secret --cert=path/to/tls.cert --key=path/to/tls.key
52
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
Example usage
Example usage
Example usage
Example usage
53
OpenShift Container Platform 4.15 CLI tools
Example usage
# Request a token to authenticate to the kube-apiserver as the service account "myapp" in the
current namespace
oc create token myapp
Example usage
# Create a user with the username "ajones" and the display name "Adam Jones"
oc create user ajones --full-name="Adam Jones"
Example usage
2.7.1.70. oc debug
Example usage
# Start a shell session into a pod using the OpenShift tools image
oc debug
54
CHAPTER 2. OPENSHIFT CLI (OC)
oc debug node/master-1
# Debug a specific failing container by running the env command in the 'second' container
oc debug daemonset/test -c second -- /bin/env
2.7.1.71. oc delete
Delete resources by file names, stdin, resources and names, or by resources and label selector
Example usage
# Delete a pod based on the type and name in the JSON passed into stdin
cat pod.json | oc delete -f -
# Delete pods and services with same names "baz" and "foo"
oc delete pod,service baz foo
55
OpenShift Container Platform 4.15 CLI tools
2.7.1.72. oc describe
Example usage
# Describe a node
oc describe nodes kubernetes-node-emt8.c.myproject.internal
# Describe a pod
oc describe pods/nginx
2.7.1.73. oc diff
Example usage
2.7.1.74. oc edit
Example usage
56
CHAPTER 2. OPENSHIFT CLI (OC)
# Edit the deployment 'mydeployment' in YAML and save the modified config in its annotation
oc edit deployment/mydeployment -o yaml --save-config
2.7.1.75. oc events
List events
Example usage
# List recent events for the specified pod, then wait for more events and list them as they arrive
oc events --for pod/web-pod-13je7 --watch
2.7.1.76. oc exec
Example usage
# Get output from running the 'date' command from pod mypod, using the first container by default
oc exec mypod -- date
# Get output from running the 'date' command in ruby-container from pod mypod
oc exec mypod -c ruby-container -- date
# Switch to raw terminal mode; sends stdin to 'bash' in ruby-container from pod mypod
# and sends stdout/stderr from 'bash' back to the client
oc exec mypod -c ruby-container -i -t -- bash -il
# List contents of /usr from the first container of pod mypod and sort by modification time
# If the command you want to execute in the pod has any flags in common (e.g. -i),
# you must use two dashes (--) to separate your command's flags/arguments
# Also note, do not surround your command and its flags/arguments with quotes
# unless that is how you would execute it normally (i.e., do ls -t /usr, not "ls -t /usr")
oc exec mypod -i -t -- ls -t /usr
# Get output from running 'date' command from the first pod of the deployment mydeployment,
57
OpenShift Container Platform 4.15 CLI tools
# Get output from running 'date' command from the first pod of the service myservice, using the first
container by default
oc exec svc/myservice -- date
2.7.1.77. oc explain
Example usage
2.7.1.78. oc expose
Example usage
# Create a route based on service nginx. The new route will reuse nginx's labels
oc expose service nginx
# Create a route and specify your own label and route name
oc expose service nginx -l name=myroute --name=fromdowntown
58
CHAPTER 2. OPENSHIFT CLI (OC)
2.7.1.79. oc extract
Example usage
# Extract only the key "nginx.conf" from config map "nginx" to the /tmp directory
oc extract configmap/nginx --to=/tmp --keys=nginx.conf
2.7.1.80. oc get
Example usage
# List all pods in ps output format with more information (such as node name)
oc get pods -o wide
# List deployments in JSON output format, in the "v1" version of the "apps" API group
oc get deployments.v1.apps -o json
# List a pod identified by type and name specified in "pod.yaml" in JSON output format
oc get -f pod.yaml -o json
59
OpenShift Container Platform 4.15 CLI tools
2.7.1.81. oc get-token
Experimental: Get token from external OIDC issuer as credentials exec plugin
Example usage
# Starts an auth code flow to the issuer url with the client id and the given extra scopes
oc get-token --client-id=client-id --issuer-url=test.issuer.url --extra-scopes=email,profile
# Starts an authe code flow to the issuer url with a different callback address.
oc get-token --client-id=client-id --issuer-url=test.issuer.url --callback-address=127.0.0.1:8343
2.7.1.82. oc idle
Example usage
# Idle the scalable controllers associated with the services listed in to-idle.txt
$ oc idle --resource-names-file to-idle.txt
Example usage
# Add a new layer to the image and store the result on disk
# This results in $(pwd)/v2/mysql/blobs,manifests
oc image append --from mysql:latest --to file://mysql:local layer.tar.gz
# Add a new layer to the image and store the result on disk in a designated directory
# This will result in $(pwd)/mysql-local/v2/mysql/blobs,manifests
oc image append --from mysql:latest --to file://mysql:local --dir mysql-local layer.tar.gz
# Add a new layer to an image that was mirrored to the current directory on disk ($(pwd)/v2/image
exists)
oc image append --from-dir v2 --to myregistry.com/myimage:latest layer.tar.gz
60
CHAPTER 2. OPENSHIFT CLI (OC)
# Add a new layer to a multi-architecture image for an os/arch that is different from the system's
os/arch
# Note: The first image in the manifest list that matches the filter will be returned when --keep-
manifest-list is not specified
oc image append --from docker.io/library/busybox:latest --filter-by-os=linux/s390x --to
myregistry.com/myimage:latest layer.tar.gz
# Add a new layer to a multi-architecture image for all the os/arch manifests when keep-manifest-list
is specified
oc image append --from docker.io/library/busybox:latest --keep-manifest-list --to
myregistry.com/myimage:latest layer.tar.gz
# Add a new layer to a multi-architecture image for all the os/arch manifests that is specified by the
filter, while preserving the manifestlist
oc image append --from docker.io/library/busybox:latest --filter-by-os=linux/s390x --keep-manifest-
list --to myregistry.com/myimage:latest layer.tar.gz
Example usage
# Extract the busybox image into the current directory for linux/s390x platform
# Note: Wildcard filter is not supported with extract; pass a single os/arch to extract
oc image extract docker.io/library/busybox:latest --filter-by-os=linux/s390x
# Extract a single file from the image into the current directory
oc image extract docker.io/library/centos:7 --path /bin/bash:.
# Extract all .repo files from the image's /etc/yum.repos.d/ folder into the current directory
oc image extract docker.io/library/centos:7 --path /etc/yum.repos.d/*.repo:.
# Extract all .repo files from the image's /etc/yum.repos.d/ folder into a designated directory (must
exist)
# This results in /tmp/yum.repos.d/*.repo on local system
oc image extract docker.io/library/centos:7 --path /etc/yum.repos.d/*.repo:/tmp/yum.repos.d
# Extract an image stored on disk in a directory other than $(pwd)/v2 into the current directory
# --confirm is required because the current directory is not empty ($(pwd)/busybox-mirror-
dir/v2/busybox exists)
oc image extract file://busybox:local --dir busybox-mirror-dir --confirm
61
OpenShift Container Platform 4.15 CLI tools
# Extract an image stored on disk in a directory other than $(pwd)/v2 into a designated directory
(must exist)
oc image extract file://busybox:local --dir busybox-mirror-dir --path /:/tmp/busybox
Example usage
Example usage
# Copy image to disk, creating a directory structure that can be served as a registry
oc image mirror myregistry.com/myimage:latest file://myrepository/myimage:latest
62
CHAPTER 2. OPENSHIFT CLI (OC)
# Copy manifest list of a multi-architecture image, even if only a single image is found
oc image mirror myregistry.com/myimage:latest=myregistry.com/other:test \
--keep-manifest-list=true
2.7.1.87. oc import-image
Example usage
# Update imported data for tag latest in an already existing image stream
oc import-image mystream
# Update imported data for tag stable in an already existing image stream
oc import-image mystream:stable
63
OpenShift Container Platform 4.15 CLI tools
# Update imported data for a tag that points to a manifest list to include the full manifest list
oc import-image mystream --import-mode=PreserveOriginal
# Import all tags into a new image stream using a custom timeout
oc --request-timeout=5m import-image mystream --from=registry.io/repo/image --all --confirm
2.7.1.88. oc kustomize
Example usage
2.7.1.89. oc label
Example usage
# Update pod 'foo' with the label 'unhealthy' and the value 'true'
oc label pods foo unhealthy=true
# Update pod 'foo' with the label 'status' and the value 'unhealthy', overwriting any existing value
oc label --overwrite pods foo status=unhealthy
2.7.1.90. oc login
Log in to a server
64
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
# Log in interactively
oc login --username=myuser
# Log in to the given server with the given certificate authority file
oc login localhost:8443 --certificate-authority=/path/to/cert.crt
# Log in to the given server with the given credentials (will not prompt interactively)
oc login localhost:8443 --username=myuser --password=mypass
# Log in to the external OIDC issuer through Auth Code + PKCE by starting a local server listening
port 8080
oc login localhost:8443 --exec-plugin=oc-oidc --client-id=client-id --extra-scopes=email,profile --
callback-port=8080
2.7.1.91. oc logout
Example usage
# Log out
oc logout
2.7.1.92. oc logs
Example usage
# Start streaming the logs of the most recent build of the openldap build config
oc logs -f bc/openldap
# Start streaming the logs of the latest deployment of the mysql deployment config
oc logs -f dc/mysql
# Get the logs of the first deployment for the mysql deployment config. Note that logs
# from older deployments may not exist either because the deployment was successful
# or due to deployment pruning or manual deletion of the deployment
oc logs --version=1 dc/mysql
2.7.1.93. oc new-app
65
OpenShift Container Platform 4.15 CLI tools
Example usage
# List all local templates and image streams that can be used to create an app
oc new-app --list
# Create an application based on the source code in the current git repository (with a public remote)
and a container image
oc new-app . --image=registry/repo/langimage
# Create an application myapp with Docker based build strategy expecting binary input
oc new-app --strategy=docker --binary --name myapp
# Use the public container registry MySQL image to create an app. Generated artifacts will be
labeled with db=mysql
oc new-app mysql MYSQL_USER=user MYSQL_PASSWORD=pass MYSQL_DATABASE=testdb -
l db=mysql
# Use a MySQL image in a private registry to create an app and override application artifacts'
names
oc new-app --image=myregistry.com/mycompany/mysql --name=private
# Use an image with the full manifest list to create an app and override application artifacts' names
oc new-app --image=myregistry.com/mycompany/image --name=private --import-
mode=PreserveOriginal
# Create an application from a remote private repository and specify which existing secret to use
oc new-app https://github.com/youruser/yourgitrepo --source-secret=yoursecret
# Search all templates, image streams, and container images for the ones that match "ruby"
oc new-app --search ruby
# Search for "ruby", but only in stored templates (--template, --image-stream and --image
# can be used to filter search results)
oc new-app --search --template=ruby
# Search for "ruby" in stored templates and print the output as YAML
oc new-app --search --template=ruby --output=yaml
66
CHAPTER 2. OPENSHIFT CLI (OC)
2.7.1.94. oc new-build
Example usage
# Create a build config based on the source code in the current git repository (with a public
# remote) and a container image
oc new-build . --image=repo/langimage
# Create a NodeJS build config based on the provided [image]~[source code] combination
oc new-build centos/nodejs-8-centos7~https://github.com/sclorg/nodejs-ex.git
# Create a build config from a remote repository using its beta2 branch
oc new-build https://github.com/openshift/ruby-hello-world#beta2
# Create a build config from a remote repository and add custom environment variables
oc new-build https://github.com/openshift/ruby-hello-world -e RACK_ENV=development
# Create a build config from a remote private repository and specify which existing secret to use
oc new-build https://github.com/youruser/yourgitrepo --source-secret=yoursecret
# Create a build config using an image with the full manifest list to create an app and override
application artifacts' names
oc new-build --image=myregistry.com/mycompany/image --name=private --import-
mode=PreserveOriginal
# Create a build config from a remote repository and inject the npmrc into a build
oc new-build https://github.com/openshift/ruby-hello-world --build-secret npmrc:.npmrc
# Create a build config from a remote repository and inject environment data into a build
oc new-build https://github.com/openshift/ruby-hello-world --build-config-map env:config
# Create a build config that gets its input from a remote repository and another container image
oc new-build https://github.com/openshift/ruby-hello-world --source-image=openshift/jenkins-1-
centos7 --source-image-path=/var/lib/jenkins:tmp
2.7.1.95. oc new-project
Example usage
2.7.1.96. oc observe
67
OpenShift Container Platform 4.15 CLI tools
Example usage
# Observe changes to services, including the clusterIP and invoke a script for each
oc observe services --template '{ .spec.clusterIP }' -- register_dns.sh
2.7.1.97. oc patch
Example usage
# Partially update a node using a strategic merge patch, specifying the patch as JSON
oc patch node k8s-node-1 -p '{"spec":{"unschedulable":true}}'
# Partially update a node using a strategic merge patch, specifying the patch as YAML
oc patch node k8s-node-1 -p $'spec:\n unschedulable: true'
# Partially update a node identified by the type and name specified in "node.json" using strategic
merge patch
oc patch -f node.json -p '{"spec":{"unschedulable":true}}'
# Update a deployment's replicas through the 'scale' subresource using a merge patch
oc patch deployment nginx-deployment --subresource='scale' --type='merge' -p '{"spec":
{"replicas":2}}'
Example usage
68
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
Example usage
# Check whether service accounts sa1 and sa2 can admit a pod with a template pod spec specified
in my_resource.yaml
# Service Account specified in myresource.yaml file is ignored
oc policy scc-review -z sa1,sa2 -f my_resource.yaml
# Check whether the service account specified in my_resource_with_sa.yaml can admit the pod
oc policy scc-review -f my_resource_with_sa.yaml
# Check whether the default service account can admit the pod; default is taken since no service
account is defined in myresource_with_no_sa.yaml
oc policy scc-review -f myresource_with_no_sa.yaml
Example usage
# Check whether user bob who belongs to projectAdmin group can create a pod specified in
myresource.yaml
oc policy scc-subject-review -u bob -g projectAdmin -f myresource.yaml
# Check whether a service account specified in the pod template spec in myresourcewithsa.yaml
can create the pod
oc policy scc-subject-review -f myresourcewithsa.yaml
2.7.1.102. oc port-forward
Example usage
69
OpenShift Container Platform 4.15 CLI tools
# Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in the pod
oc port-forward pod/mypod 5000 6000
# Listen on ports 5000 and 6000 locally, forwarding data to/from ports 5000 and 6000 in a pod
selected by the deployment
oc port-forward deployment/mydeployment 5000 6000
# Listen on port 8443 locally, forwarding to the targetPort of the service's port named "https" in a pod
selected by the service
oc port-forward service/myservice 8443:https
# Listen on port 8888 on localhost and selected IP, forwarding to 5000 in the pod
oc port-forward --address localhost,10.19.21.23 pod/mypod 8888:5000
2.7.1.103. oc process
Example usage
# Convert the template.json file into a resource list and pass to create
oc process -f template.json | oc create -f -
2.7.1.104. oc project
70
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
2.7.1.105. oc projects
Example usage
2.7.1.106. oc proxy
Example usage
# To proxy only part of the Kubernetes API and also some static files
# You can get pods info with 'curl localhost:8001/api/v1/pods'
oc proxy --www=/my/files --www-prefix=/static/ --api-prefix=/api/
# Run a proxy to the Kubernetes API server on port 8011, serving static content from ./local/www/
oc proxy --port=8011 --www=./local/www/
# Run a proxy to the Kubernetes API server, changing the API prefix to k8s-api
# This makes e.g. the pods API available at localhost:8001/k8s-api/v1/pods/
oc proxy --api-prefix=/k8s-api
Example usage
71
OpenShift Container Platform 4.15 CLI tools
2.7.1.108. oc replace
Example usage
2.7.1.109. oc rollback
Example usage
# Perform a rollback to the last successfully completed deployment for a deployment config
oc rollback frontend
# See what a rollback to version 3 will look like, but do not perform the rollback
oc rollback frontend --to-version=3 --dry-run
# Perform the rollback manually by piping the JSON of the new config back to oc
oc rollback frontend -o json | oc replace dc/frontend -f -
# Print the updated deployment configuration in JSON format instead of performing the rollback
oc rollback frontend -o json
Example usage
72
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
Start a new rollout for a deployment config with the latest state from its triggers
Example usage
# Start a new rollout based on the latest images defined in the image change triggers
oc rollout latest dc/nginx
Example usage
Restart a resource
Example usage
# Restart a deployment
oc rollout restart deployment/nginx
73
OpenShift Container Platform 4.15 CLI tools
Example usage
Example usage
Example usage
Example usage
# Roll back to deployment revision 3. The replication controller for that version must exist
oc rollout undo dc/nginx --to-revision=3
2.7.1.119. oc rsh
Example usage
# Open a shell session on the first container in pod 'foo' and namespace 'bar'
# (Note that oc client specific arguments must come before the resource name and its arguments)
oc rsh -n bar foo
74
CHAPTER 2. OPENSHIFT CLI (OC)
# Open a shell session on the container named 'index' inside a pod of your job
oc rsh -c index job/scheduled
2.7.1.120. oc rsync
Example usage
2.7.1.121. oc run
Example usage
# Start a hazelcast pod and let the container expose port 5701
oc run hazelcast --image=hazelcast/hazelcast --port=5701
# Start a hazelcast pod and set labels "app=hazelcast" and "env=prod" in the container
oc run hazelcast --image=hazelcast/hazelcast --labels="app=hazelcast,env=prod"
# Dry run; print the corresponding API objects without creating them
oc run nginx --image=nginx --dry-run=client
# Start a nginx pod, but overload the spec with a partial set of values parsed from JSON
oc run nginx --image=nginx --overrides='{ "apiVersion": "v1", "spec": { ... } }'
# Start a busybox pod and keep it in the foreground, don't restart it if it exits
oc run -i -t busybox --image=busybox --restart=Never
# Start the nginx pod using the default command, but use custom arguments (arg1 .. argN) for that
command
oc run nginx --image=nginx -- <arg1> <arg2> ... <argN>
# Start the nginx pod using a different command and custom arguments
oc run nginx --image=nginx --command -- <cmd> <arg1> ... <argN>
75
OpenShift Container Platform 4.15 CLI tools
2.7.1.122. oc scale
Example usage
Example usage
# Add an image pull secret to a service account to automatically use it for pulling pod images
oc secrets link serviceaccount-name pull-secret --for=pull
# Add an image pull secret to a service account to automatically use it for both pulling and pushing
build images
oc secrets link builder builder-image-secret --for=pull,mount
Example usage
Example usage
# Set the post-commit hook to execute a test suite using a new entrypoint
76
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
Example usage
# Update a secret with the contents of a directory, one key per file
oc set data secret/foo --from-file=secret-dir
Example usage
# Set the pre deployment hook to execute a db migration command for an application
# using the data volume from the application
77
OpenShift Container Platform 4.15 CLI tools
Example usage
# Update all containers in all replication controllers in the project to have ENV=prod
oc set env rc --all ENV=prod
# Remove the environment variable ENV from container 'c1' in all deployment configs
oc set env dc --all --containers="c1" ENV-
# Remove the environment variable ENV from a deployment config definition on disk and
# update the deployment config on the server
oc set env -f dc.json ENV-
# Set some of the local shell environment into a deployment config on the server
oc set env | grep RAILS_ | oc env -e - dc/myapp
Example usage
# Set a deployment config's nginx container image to 'nginx:1.9.1', and its busybox container image
to 'busybox'.
oc set image dc/nginx busybox=busybox nginx=nginx:1.9.1
# Set a deployment config's app container image to the image referenced by the imagestream tag
78
CHAPTER 2. OPENSHIFT CLI (OC)
'openshift/ruby:2.3'.
oc set image dc/myapp app=openshift/ruby:2.3 --source=imagestreamtag
# Print result (in YAML format) of updating nginx container image from local file, without hitting the
server
oc set image -f path/to/file.yaml nginx=nginx:1.9.1 --local -o yaml
Example usage
# Print all of the image streams and whether they resolve local names
oc set image-lookup
Example usage
# Set an HTTP startup probe for port 8080 and path /healthz over HTTP on the pod IP
oc set probe dc/webapp --startup --get-url=http://:8080/healthz
79
OpenShift Container Platform 4.15 CLI tools
# Set an HTTP readiness probe for port 8080 and path /healthz over HTTP on the pod IP
oc set probe dc/webapp --readiness --get-url=http://:8080/healthz
# Set an HTTP readiness probe over HTTPS on 127.0.0.1 for a hostNetwork pod
oc set probe dc/router --readiness --get-url=https://127.0.0.1:1936/stats
Example usage
# Set a deployments nginx container CPU limits to "200m and memory to 512Mi"
oc set resources deployment nginx -c=nginx --limits=cpu=200m,memory=512Mi
# Set the resource request and limits for all containers in nginx
oc set resources deployment nginx --limits=cpu=200m,memory=512Mi --
requests=cpu=100m,memory=256Mi
# Print the result (in YAML format) of updating nginx container limits locally, without hitting the server
oc set resources -f path/to/file.yaml --limits=cpu=200m,memory=512Mi --local -o yaml
Example usage
# Set two backend services on route 'web' with 2/3rds of traffic going to 'a'
oc set route-backends web a=2 b=1
# Set weight of b to 10
oc set route-backends web --adjust b=10
80
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
Example usage
# Print the result (in YAML format) of updated nginx deployment with service account from a local
file, without hitting the API server
oc set sa -f nginx-deployment.yaml serviceaccount1 --local --dry-run -o yaml
Update the user, group, or service account in a role binding or cluster role binding
Example usage
# Print the result (in YAML format) of updating role binding subjects locally, without hitting the server
oc create rolebinding admin --role=admin --user=admin -o yaml --dry-run | oc set subject --local -f -
--user=foo -o yaml
Example usage
81
OpenShift Container Platform 4.15 CLI tools
Example usage
# Add a new empty dir volume to deployment config (dc) 'myapp' mounted under
# /var/lib/myapp
oc set volume dc/myapp --add --mount-path=/var/lib/myapp
# Use an existing persistent volume claim (PVC) to overwrite an existing volume 'v1'
oc set volume dc/myapp --add --name=v1 -t pvc --claim-name=pvc1 --overwrite
# Create a new persistent volume claim that overwrites an existing volume 'v1'
oc set volume dc/myapp --add --name=v1 -t pvc --claim-size=1G --overwrite
# Modify the deployment config by removing volume mount "v1" from container "c1"
# (and by removing the volume "v1" if no other containers have volume mounts that reference it)
oc set volume dc/myapp --remove --name=v1 --containers=c1
# Add new volume based on a more complex volume source (AWS EBS, GCE PD,
# Ceph, Gluster, NFS, ISCSI, ...)
oc set volume dc/myapp --add -m /data --source=<json-string>
2.7.1.140. oc start-build
82
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
# Send the contents of a Git repository to the server from tag 'v2'
oc start-build hello-world --from-repo=../hello-world --commit=v2
# Start a new build for build config "hello-world" and watch the logs until the build
# completes or fails
oc start-build hello-world --follow
# Start a new build for build config "hello-world" and wait until the build completes. It
# exits with a non-zero return code if the build fails
oc start-build hello-world --wait
2.7.1.141. oc status
Example usage
# See an overview of the current project including details for any identified issues
oc status --suggest
2.7.1.142. oc tag
Example usage
# Tag the current image for the image stream 'openshift/ruby' and tag '2.0' into the image stream
'yourproject/ruby with tag 'tip'
oc tag openshift/ruby:2.0 yourproject/ruby:tip
83
OpenShift Container Platform 4.15 CLI tools
# Tag an external container image and include the full manifest list
oc tag --source=docker openshift/origin-control-plane:latest yourproject/ruby:tip --import-
mode=PreserveOriginal
2.7.1.143. oc version
Example usage
# Print the OpenShift client, kube-apiserver, and openshift-apiserver version information for the
current context
oc version
# Print the OpenShift client, kube-apiserver, and openshift-apiserver version numbers for the current
context in json format
oc version --output json
# Print the OpenShift client version information for the current context
oc version --client
2.7.1.144. oc wait
Example usage
# Wait for the pod "busybox1" to contain the status condition of type "Ready"
oc wait --for=condition=Ready pod/busybox1
# The default value of status condition is true; you can wait for other targets after an equal delimiter
(compared after Unicode simple case folding, which is a more general form of case-insensitivity)
oc wait --for=condition=Ready=false pod/busybox1
# Wait for the pod "busybox1" to contain the status phase to be "Running"
oc wait --for=jsonpath='{.status.phase}'=Running pod/busybox1
# Wait for the pod "busybox1" to be deleted, with a timeout of 60s, after having issued the "delete"
command
oc delete pod/busybox1
oc wait --for=delete pod/busybox1 --timeout=60s
84
CHAPTER 2. OPENSHIFT CLI (OC)
2.7.1.145. oc whoami
Example usage
For developer commands, see the OpenShift CLI developer command reference .
Run oc adm -h to list all administrator commands or run oc <command> --help to get additional
details for a specific command.
Example usage
# Build the dependency tree for the 'v2' tag in dot format and visualize it via the dot utility
oc adm build-chain <image-stream>:v2 -o dot | dot -T svg -o deps.svg
# Build the dependency tree across all namespaces for the specified image stream tag found in the
'test' namespace
oc adm build-chain <image-stream> -n test --all
Example usage
85
OpenShift Container Platform 4.15 CLI tools
# Edit the mirroring mappings and mirror with "oc image mirror" manually
oc adm catalog mirror --manifests-only quay.io/my/image:latest myregistry.com
oc image mirror -f manifests/mapping.txt
Example usage
Example usage
Example usage
Example usage
86
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
Example usage
Example usage
Example usage
# Drain node "foo", even if there are pods not managed by a replication controller, replica set, job,
daemon set, or stateful set on it
oc adm drain foo --force
# As above, but abort if there are pods not managed by a replication controller, replica set, job,
daemon set, or stateful set, and use a grace period of 15 minutes
oc adm drain foo --grace-period=900
Example usage
87
OpenShift Container Platform 4.15 CLI tools
Example usage
Remove old OpenShift groups referencing missing records from an external provider
Example usage
# Prune all orphaned groups except the ones from the denylist file
oc adm groups prune --blacklist=/path/to/denylist.txt --sync-config=/path/to/ldap-sync-config.yaml --
confirm
# Prune all orphaned groups from a list of specific groups specified in an allowlist file
oc adm groups prune --whitelist=/path/to/allowlist.txt --sync-config=/path/to/ldap-sync-config.yaml --
confirm
# Prune all orphaned groups from a list of specific groups specified in a list
oc adm groups prune groups/group_name groups/other_name --sync-config=/path/to/ldap-sync-
config.yaml --confirm
Example usage
88
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
# Sync all groups except the ones from the blacklist file with an LDAP server
oc adm groups sync --blacklist=/path/to/blacklist.txt --sync-config=/path/to/ldap-sync-config.yaml --
confirm
# Sync all OpenShift groups that have been synced previously with an LDAP server
oc adm groups sync --type=openshift --sync-config=/path/to/ldap-sync-config.yaml --confirm
# Sync specific OpenShift groups if they have been synced previously with an LDAP server
oc adm groups sync groups/group1 groups/group2 groups/group3 --sync-config=/path/to/sync-
config.yaml --confirm
Example usage
Example usage
# Update the imagecontentsourcepolicy.yaml file to a new imagedigestmirrorset file under the mydir
directory
oc adm migrate icsp imagecontentsourcepolicy.yaml --dest-dir mydir
Example usage
89
OpenShift Container Platform 4.15 CLI tools
Example usage
# Gather information using the default plug-in image and command, writing into ./must-gather.local.
<rand>
oc adm must-gather
Example usage
Example usage
90
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
Remove old CAs from ConfigMaps representing platform trust bundles in an OpenShift cluster
Example usage
# Remove only CA certificates created before a certain date from all trust bundles
oc adm ocp-certificates remove-old-trust configmaps -A --all --created-before 2023-06-05T14:44:06Z
Example usage
Example usage
91
OpenShift Container Platform 4.15 CLI tools
# Allow all projects with label name=top-secret to have their own isolated project network
oc adm pod-network isolate-projects --selector='name=top-secret'
Example usage
Example usage
# Allow project p1 to access all pods in the cluster and vice versa
oc adm pod-network make-projects-global <p1>
# Allow all projects with label name=share to access all pods in the cluster and vice versa
oc adm pod-network make-projects-global --selector='name=share'
Example usage
Example usage
92
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
# Add the 'privileged' security context constraint to serviceaccount1 in the current namespace
oc adm policy add-scc-to-user privileged -z serviceaccount1
Example usage
# Check whether service accounts sa1 and sa2 can admit a pod with a template pod spec specified
in my_resource.yaml
# Service Account specified in myresource.yaml file is ignored
oc adm policy scc-review -z sa1,sa2 -f my_resource.yaml
# Check whether the service account specified in my_resource_with_sa.yaml can admit the pod
oc adm policy scc-review -f my_resource_with_sa.yaml
# Check whether the default service account can admit the pod; default is taken since no service
account is defined in myresource_with_no_sa.yaml
oc adm policy scc-review -f myresource_with_no_sa.yaml
Example usage
# Check whether user bob who belongs to projectAdmin group can create a pod specified in
myresource.yaml
oc adm policy scc-subject-review -u bob -g projectAdmin -f myresource.yaml
# Check whether a service account specified in the pod template spec in myresourcewithsa.yaml
can create the pod
oc adm policy scc-subject-review -f myresourcewithsa.yaml
93
OpenShift Container Platform 4.15 CLI tools
Example usage
# Dry run deleting older completed and failed builds and also including
# all builds whose associated build config no longer exists
oc adm prune builds --orphans
# To actually perform the prune operation, the confirm flag must be appended
oc adm prune builds --orphans --confirm
Example usage
# Dry run deleting all but the last complete deployment for every deployment config
oc adm prune deployments --keep-complete=1
# To actually perform the prune operation, the confirm flag must be appended
oc adm prune deployments --keep-complete=1 --confirm
Remove old OpenShift groups referencing missing records from an external provider
Example usage
# Prune all orphaned groups except the ones from the denylist file
oc adm prune groups --blacklist=/path/to/denylist.txt --sync-config=/path/to/ldap-sync-config.yaml --
confirm
# Prune all orphaned groups from a list of specific groups specified in an allowlist file
oc adm prune groups --whitelist=/path/to/allowlist.txt --sync-config=/path/to/ldap-sync-config.yaml --
confirm
# Prune all orphaned groups from a list of specific groups specified in a list
oc adm prune groups groups/group_name groups/other_name --sync-config=/path/to/ldap-sync-
config.yaml --confirm
Example usage
# See what the prune command would delete if only images and their referrers were more than an
hour old
# and obsoleted by 3 newer revisions under the same tag were considered
94
CHAPTER 2. OPENSHIFT CLI (OC)
# To actually perform the prune operation, the confirm flag must be appended
oc adm prune images --keep-tag-revisions=3 --keep-younger-than=60m --confirm
# See what the prune command would delete if we are interested in removing images
# exceeding currently set limit ranges ('openshift.io/Image')
oc adm prune images --prune-over-size-limit
# To actually perform the prune operation, the confirm flag must be appended
oc adm prune images --prune-over-size-limit --confirm
# Force the insecure HTTP protocol with the particular registry host name
oc adm prune images --registry-url=http://registry.example.org --confirm
# Force a secure connection with a custom certificate authority to the particular registry host name
oc adm prune images --registry-url=registry.example.org --certificate-
authority=/path/to/custom/ca.crt --confirm
Example usage
# Reboot all MachineConfigPools that inherit from worker. This include all custom
MachineConfigPools and infra.
oc adm reboot-machine-config-pool mcp/worker
# Reboot masters
oc adm reboot-machine-config-pool mcp/master
Example usage
# Use git to check out the source code for the current cluster release to DIR
oc adm release extract --git=DIR
# Use git to check out the source code for the current cluster release to DIR from linux/s390x image
# Note: Wildcard filter is not supported; pass a single os/arch to extract
oc adm release extract --git=DIR quay.io/openshift-release-dev/ocp-release:4.11.2 --filter-by-
os=linux/s390x
95
OpenShift Container Platform 4.15 CLI tools
Example usage
Example usage
# Perform a dry run showing what would be mirrored, including the mirror objects
oc adm release mirror 4.11.0 --to myregistry.local/openshift/release \
--release-image-signature-to-dir /tmp/releases --dry-run
# Mirror the 4.11.0 release to repository registry.example.com and apply signatures to connected
cluster
oc adm release mirror --from=quay.io/openshift-release-dev/ocp-release:4.11.0-x86_64 \
--to=registry.example.com/your/repository --apply-release-image-signature
Example usage
# Create a release from the latest origin images and push to a DockerHub repository
oc adm release new --from-image-stream=4.11 -n origin --to-image
96
CHAPTER 2. OPENSHIFT CLI (OC)
docker.io/mycompany/myrepo:latest
Example usage
Example usage
# Update node 'foo' with a taint with key 'dedicated' and value 'special-user' and effect 'NoSchedule'
# If a taint with that key and effect already exists, its value is replaced as specified
oc adm taint nodes foo dedicated=special-user:NoSchedule
# Remove from node 'foo' the taint with key 'dedicated' and effect 'NoSchedule' if one exists
oc adm taint nodes foo dedicated:NoSchedule-
# Remove from node 'foo' all the taints with key 'dedicated'
oc adm taint nodes foo dedicated-
97
OpenShift Container Platform 4.15 CLI tools
Example usage
Example usage
Example usage
Example usage
Example usage
98
CHAPTER 2. OPENSHIFT CLI (OC)
Example usage
Example usage
# Verify the image signature and identity using the local GPG keychain
oc adm verify-image-signature
sha256:c841e9b64e4579bd56c794bdd7c36e1c257110fd2404bebbb8b613e4935228c4 \
--expected-identity=registry.local:5000/foo/bar:v1
# Verify the image signature and identity using the local GPG keychain and save the status
oc adm verify-image-signature
sha256:c841e9b64e4579bd56c794bdd7c36e1c257110fd2404bebbb8b613e4935228c4 \
--expected-identity=registry.local:5000/foo/bar:v1 --save
# Verify the image signature and identity via exposed registry route
oc adm verify-image-signature
sha256:c841e9b64e4579bd56c794bdd7c36e1c257110fd2404bebbb8b613e4935228c4 \
--expected-identity=registry.local:5000/foo/bar:v1 \
--registry-url=docker-registry.foo.com
Example usage
# Wait for all nodes to complete a requested reboot from 'oc adm reboot-machine-config-pool
mcp/worker mcp/master'
oc adm wait-for-node-reboot nodes --all
# Wait for masters to complete a requested reboot from 'oc adm reboot-machine-config-pool
mcp/master'
99
OpenShift Container Platform 4.15 CLI tools
Example usage
100
CHAPTER 3. IMPORTANT UPDATE ON ODO
IMPORTANT
For the materials maintained by the upstream community, Red Hat provides support
under Cooperative Community Support.
101
OpenShift Container Platform 4.15 CLI tools
Create and manage Knative Eventing components, such as event sources and triggers.
Create sink bindings to connect existing Kubernetes applications and Knative services.
Extend the Knative CLI with flexible plugin architecture, similar to the kubectl CLI.
Scripted usage, such as waiting for the results of an operation, or deploying custom rollout and
rollback strategies.
102
CHAPTER 5. PIPELINES CLI (TKN)
You can also find the URL to the latest binaries from the OpenShift Container Platform web console by
clicking the ? icon in the upper-right corner and selecting Command Line Tools. :FeatureName:
Running Red Hat OpenShift Pipelines on ARM hardware
IMPORTANT
For more information about the support scope of Red Hat Technology Preview features,
see Technology Preview Features Support Scope .
NOTE
Both the archives and the RPMs contain the following executables:
tkn
tkn-pac
opc
IMPORTANT
Running Red Hat OpenShift Pipelines with the opc CLI tool is a Technology Preview
feature only. Technology Preview features are not supported with Red Hat production
service level agreements (SLAs) and might not be functionally complete. Red Hat does
not recommend using them in production. These features provide early access to
upcoming product features, enabling customers to test functionality and provide
feedback during the development process.
For more information about the support scope of Red Hat Technology Preview features,
see Technology Preview Features Support Scope .
Procedure
103
OpenShift Container Platform 4.15 CLI tools
2. Add the location of your tkn, tkn-pac, and opc files to your PATH environment variable.
$ echo $PATH
5.1.2. Installing the Red Hat OpenShift Pipelines CLI on Linux using an RPM
For Red Hat Enterprise Linux (RHEL) version 8, you can install the Red Hat OpenShift Pipelines CLI as
an RPM.
Prerequisites
You have an active OpenShift Container Platform subscription on your Red Hat account.
Procedure
# subscription-manager register
# subscription-manager refresh
4. In the output for the previous command, find the pool ID for your OpenShift Container Platform
subscription and attach the subscription to the registered system:
104
CHAPTER 5. PIPELINES CLI (TKN)
After you install the CLI, it is available using the tkn command:
$ tkn version
Procedure
3. Add the location of your tkn, tkn-pac, and opc files to your PATH environment variable.
C:\> path
Procedure
macOS
macOS on ARM
3. Add the location of your tkn, tkn-pac, and opc files to your PATH environment variable.
$ echo $PATH
105
OpenShift Container Platform 4.15 CLI tools
Prerequisites
Procedure
The following procedure enables tab completion for Bash.
Alternatively, you can save the file to a local directory and source it from your .bashrc file
instead.
5.3.3.1. tkn
106
CHAPTER 5. PIPELINES CLI (TKN)
$ tkn
Print shell completion code which must be evaluated to provide interactive completion. Supported
shells are bash and zsh.
5.3.3.3. version
$ tkn version
5.3.4.1. pipeline
Manage pipelines.
Delete a pipeline.
Describe a pipeline.
107
OpenShift Container Platform 4.15 CLI tools
Start a pipeline.
5.3.5.1. pipelinerun
$ tkn pipelinerun -h
Example: Delete all pipeline runs from a namespace, except the five most recently executed
pipeline runs
108
CHAPTER 5. PIPELINES CLI (TKN)
1 Replace 5 with the number of most recently executed pipeline runs you want to retain.
NOTE
Starting with Red Hat OpenShift Pipelines 1.6, the tkn pipelinerun delete --all command
does not delete any resources that are in the running state.
Example: Display the logs of the mypipelinerun pipeline run with all tasks and steps in a
namespace
5.3.6.1. task
Manage tasks.
$ tkn task -h
Delete a task.
109
OpenShift Container Platform 4.15 CLI tools
Describe a task.
List tasks.
Example: Display logs for the mytaskrun task run of the mytask task
Start a task.
5.3.7.1. taskrun
$ tkn taskrun -h
110
CHAPTER 5. PIPELINES CLI (TKN)
Delete a TaskRun.
Example: Delete the mytaskrun1 and mytaskrun2 task runs from a namespace
Example: Delete all but the five most recently executed task runs from a namespace
1 Replace 5 with the number of most recently executed task runs you want to retain.
Example: Display live logs for the mytaskrun task run in a namespace
5.3.8.1. condition
Manage Conditions.
111
OpenShift Container Platform 4.15 CLI tools
Delete a Condition.
Describe a Condition.
List Conditions.
5.3.9.1. resource
$ tkn resource -h
This is an interactive command that asks for input on the name of the Resource, type of the Resource,
and the values based on the type of the Resource.
112
CHAPTER 5. PIPELINES CLI (TKN)
IMPORTANT
In Red Hat OpenShift Pipelines 1.10, ClusterTask functionality of the tkn command line
utility is deprecated and is planned to be removed in a future release.
5.3.10.1. clustertask
Manage ClusterTasks.
Describe a ClusterTask.
113
OpenShift Container Platform 4.15 CLI tools
List ClusterTasks.
Start ClusterTasks.
5.3.11.1. eventlistener
Manage EventListeners.
$ tkn eventlistener -h
Delete an EventListener.
Describe an EventListener.
List EventListeners.
114
CHAPTER 5. PIPELINES CLI (TKN)
5.3.11.6. triggerbinding
Manage TriggerBindings.
$ tkn triggerbinding -h
Delete a TriggerBinding.
Describe a TriggerBinding.
List TriggerBindings.
5.3.11.10. triggertemplate
Manage TriggerTemplates.
$ tkn triggertemplate -h
115
OpenShift Container Platform 4.15 CLI tools
Delete a TriggerTemplate.
Describe a TriggerTemplate.
List TriggerTemplates.
5.3.11.14. clustertriggerbinding
Manage ClusterTriggerBindings.
$ tkn clustertriggerbinding -h
Delete a ClusterTriggerBinding.
Describe a ClusterTriggerBinding.
List ClusterTriggerBindings.
116
CHAPTER 5. PIPELINES CLI (TKN)
5.3.12.1. hub
$ tkn hub -h
NOTE
For each example, to get the corresponding sub-commands and flags, run tkn hub
<command> --help.
Example: Downgrade the mytask task in the mynamespace namespace to it’s older version
Example: Get the manifest for a specific version of the myresource pipeline or task from the
tekton catalog
$ tkn hub get [pipeline | task] myresource --from tekton --version version
Display information about a resource by its name, kind, catalog, and version.
Example: Display information about a specific version of the mytask task from the tekton
catalog
117
OpenShift Container Platform 4.15 CLI tools
Example: Install a specific version of the mytask task from the tekton catalog in the
mynamespace namespace
$ tkn hub install task mytask --from tekton --version version -n mynamespace
Example: Reinstall a specific version of the mytask task from the tekton catalog in the
mynamespace namespace
$ tkn hub reinstall task mytask --from tekton --version version -n mynamespace
Example: Upgrade the installed mytask task in the mynamespace namespace to a new
version
118
CHAPTER 6. GITOPS CLI FOR USE WITH RED HAT OPENSHIFT GITOPS
With the GitOps CLI, you can make GitOps computing tasks simple and concise. You can install this CLI
tool on different platforms.
119
OpenShift Container Platform 4.15 CLI tools
A catalog contains a database of pointers to Operator manifest content that can be queried through an
included API that is served when the container image is run. On OpenShift Container Platform,
Operator Lifecycle Manager (OLM) can reference the image in a catalog source, defined by a
CatalogSource object, which polls the image at regular intervals to enable frequent updates to installed
Operators on the cluster.
Additional resources
See Operator Framework packaging format for more information about the bundle format.
To create a bundle image using the Operator SDK, see Working with bundle images.
Prerequisites
Procedure
1. Navigate to the OpenShift mirror site and download the latest version of the tarball that
matches your operating system.
IMPORTANT
There is currently a known issue where the version of the opm CLI tool released
with OpenShift Container Platform 4.15 does not support RHEL 8. As a
workaround, RHEL 8 users can navigate to the OpenShift mirror site and
download the latest version of the tarball released with OpenShift Container
Platform 4.14.
120
CHAPTER 7. OPM CLI
$ echo $PATH
For Windows:
C:\> path
Verification
$ opm version
Flag Description
-skip-tls-verify Skip TLS certificate verification for container image registries while pulling
bundles or indexes.
--use-http When you pull bundles, use plain HTTP for container image registries.
121
OpenShift Container Platform 4.15 CLI tools
IMPORTANT
The SQLite-based catalog format, including the related CLI commands, is a deprecated
feature. Deprecated functionality is still included in OpenShift Container Platform and
continues to be supported; however, it will be removed in a future release of this product
and is not recommended for new deployments.
For the most recent list of major functionality that has been deprecated or removed
within OpenShift Container Platform, refer to the Deprecated and removed features
section of the OpenShift Container Platform release notes.
7.2.1. generate
Generate various artifacts for declarative config indexes.
Command syntax
Subcommand Description
Flags Description
7.2.1.1. dockerfile
IMPORTANT
This command creates a Dockerfile in the same directory as the <dcRootDir> (named
<dcDirName>.Dockerfile) that is used to build the index. If a Dockerfile with the same
name already exists, this command fails.
When specifying extra labels, if duplicate keys exist, only the last value of each duplicate
key gets added to the generated Dockerfile.
Command syntax
122
CHAPTER 7. OPM CLI
Flag Description
-i, --binary-image Image in which to build catalog. The default value is quay.io/operator-
(string) framework/opm:latest.
-l, --extra-labels Extra labels to include in the generated Dockerfile. Labels have the form
(string) key=value.
NOTE
To build with the official Red Hat image, use the registry.redhat.io/openshift4/ose-
operator-registry:v4.15 value with the -i flag.
7.2.2. index
Generate Operator index for SQLite database format container images from pre-existing Operator
bundles.
IMPORTANT
As of OpenShift Container Platform 4.11, the default Red Hat-provided Operator catalog
releases in the file-based catalog format. The default Red Hat-provided Operator
catalogs for OpenShift Container Platform 4.6 through 4.10 released in the deprecated
SQLite database format.
The opm subcommands, flags, and functionality related to the SQLite database format
are also deprecated and will be removed in a future release. The features are still
supported and must be used for catalogs that use the deprecated SQLite database
format.
Many of the opm subcommands and flags for working with the SQLite database format,
such as opm index prune, do not work with the file-based catalog format.
For more information about working with file-based catalogs, see "Additional resources".
Command syntax
Subcommand Description
123
OpenShift Container Platform 4.15 CLI tools
Subcommand Description
prune-stranded Prune an index of stranded bundles, which are bundles that are not associated
with a particular image.
7.2.2.1. add
Command syntax
Flag Description
-u, --build-tool (string) Tool to build container images: podman (the default value) or docker.
Overrides part of the --container-tool flag.
-c, --container-tool Tool to interact with container images, such as for saving and building: docker or
(string) podman.
--generate If enabled, only creates the Dockerfile and saves it to local disk.
--mode (string) Graph update mode that defines how channel graphs are updated: replaces (the
default value), semver, or semver-skippatch.
-p, --pull-tool (string) Tool to pull container images: none (the default value), docker, or podman .
Overrides part of the --container-tool flag.
-t, --tag (string) Custom tag for container image being built.
7.2.2.2. prune
124
CHAPTER 7. OPM CLI
Command syntax
Flag Description
-c, --container-tool Tool to interact with container images, such as for saving and building: docker or
(string) podman.
--generate If enabled, only creates the Dockerfile and saves it to local disk.
-t, --tag (string) Custom tag for container image being built.
7.2.2.3. prune-stranded
Prune an index of stranded bundles, which are bundles that are not associated with a particular image.
Command syntax
Flag Description
-c, --container-tool Tool to interact with container images, such as for saving and building: docker or
(string) podman.
125
OpenShift Container Platform 4.15 CLI tools
Flag Description
--generate If enabled, only creates the Dockerfile and saves it to local disk.
-t, --tag (string) Custom tag for container image being built.
7.2.2.4. rm
Command syntax
Flag Description
-u, --build-tool (string) Tool to build container images: podman (the default value) or docker.
Overrides part of the --container-tool flag.
-c, --container-tool Tool to interact with container images, such as for saving and building: docker or
(string) podman.
--generate If enabled, only creates the Dockerfile and saves it to local disk.
126
CHAPTER 7. OPM CLI
Flag Description
-p, --pull-tool (string) Tool to pull container images: none (the default value), docker, or podman .
Overrides part of the --container-tool flag.
-t, --tag (string) Custom tag for container image being built.
Additional resources
7.2.3. init
Generate an olm.package declarative config blob.
Command syntax
Flag Description
-o, --output (string) Output format: json (the default value) or yaml.
7.2.4. migrate
Migrate a SQLite database format index image or database file to a file-based catalog.
IMPORTANT
127
OpenShift Container Platform 4.15 CLI tools
IMPORTANT
The SQLite-based catalog format, including the related CLI commands, is a deprecated
feature. Deprecated functionality is still included in OpenShift Container Platform and
continues to be supported; however, it will be removed in a future release of this product
and is not recommended for new deployments.
For the most recent list of major functionality that has been deprecated or removed
within OpenShift Container Platform, refer to the Deprecated and removed features
section of the OpenShift Container Platform release notes.
Command syntax
Flag Description
-o, --output (string) Output format: json (the default value) or yaml.
7.2.5. render
Generate a declarative config blob from the provided index images, bundle images, and SQLite
database files.
Command syntax
Flag Description
-o, --output (string) Output format: json (the default value) or yaml.
7.2.6. serve
Serve declarative configs via a GRPC server.
NOTE
The declarative config directory is loaded by the serve command at startup. Changes
made to the declarative config after this command starts are not reflected in the served
content.
Command syntax
128
CHAPTER 7. OPM CLI
Flag Description
--cache-dir (string) If this flag is set, it syncs and persists the server cache directory.
--cache-enforce- Exits with an error if the cache is not present or is invalidated. The default value is
integrity true when the --cache-dir flag is set and the --cache-only flag is false.
Otherwise, the default is false.
-p, --port (string) The port number for the service. The default value is 50051 .
--pprof-addr (string) The address of the startup profiling endpoint. The format is Addr:Port.
-t, --termination-log The path to a container termination log file. The default value is
(string) /dev/termination-log.
7.2.7. validate
Validate the declarative config JSON file(s) in a given directory.
Command syntax
129
OpenShift Container Platform 4.15 CLI tools
Operator authors with cluster administrator access to a Kubernetes-based cluster, such as OpenShift
Container Platform, can use the Operator SDK CLI to develop their own Operators based on Go,
Ansible, Java, or Helm. Kubebuilder is embedded into the Operator SDK as the scaffolding solution for
Go-based Operators, which means existing Kubebuilder projects can be used as is with the Operator
SDK and continue to work. See Developing Operators for full documentation on the Operator SDK.
NOTE
Prerequisites
Go v1.19+
Procedure
2. From the latest 4.15 directory, download the latest version of the tarball for Linux.
$ chmod +x operator-sdk
TIP
$ echo $PATH
130
CHAPTER 8. OPERATOR SDK
Verification
After you install the Operator SDK CLI, verify that it is available:
$ operator-sdk version
Example output
Prerequisites
Go v1.19+
Procedure
1. For the amd64 and arm64 architectures, navigate to the OpenShift mirror site for the amd64
architecture and OpenShift mirror site for the arm64 architecture respectively.
2. From the latest 4.15 directory, download the latest version of the tarball for macOS.
3. Unpack the Operator SDK archive for amd64 architecture by running the following command:
4. Unpack the Operator SDK archive for arm64 architecture by running the following command:
$ chmod +x operator-sdk
6. Move the extracted operator-sdk binary to a directory that is on your PATH by running the
following command:
TIP
$ echo $PATH
Verification
131
OpenShift Container Platform 4.15 CLI tools
After you install the Operator SDK CLI, verify that it is available by running the following
command::
$ operator-sdk version
Example output
8.2.1. bundle
The operator-sdk bundle command manages Operator bundle metadata.
8.2.1.1. validate
Flag Description
--index-builder Tool to pull and unpack bundle images. Only used when validating a bundle image.
(string) Available options are docker, which is the default, podman , or none.
--list-optional List all optional validators available. When set, no validators are run.
--select-optional Label selector to select optional validators to run. When run with the --list-
(string) optional flag, lists available optional validators.
8.2.2. cleanup
The operator-sdk cleanup command destroys and removes resources that were created for an
Operator that was deployed with the run command.
132
CHAPTER 8. OPERATOR SDK
Flag Description
--kubeconfig (string) Path to the kubeconfig file to use for CLI requests.
--timeout <duration> Time to wait for the command to complete before failing. The default value is
2m0s.
8.2.3. completion
The operator-sdk completion command generates shell completions to make issuing CLI commands
quicker and easier.
Subcommand Description
Flag Description
For example:
Example output
8.2.4. create
The operator-sdk create command is used to create, or scaffold, a Kubernetes API.
8.2.4.1. api
The create api subcommand scaffolds a Kubernetes API. The subcommand must be run in a project
133
OpenShift Container Platform 4.15 CLI tools
The create api subcommand scaffolds a Kubernetes API. The subcommand must be run in a project
that was initialized with the init command.
Flag Description
8.2.5. generate
The operator-sdk generate command invokes a specific generator to generate code or manifests.
8.2.5.1. bundle
The generate bundle subcommand generates a set of bundle manifests, metadata, and a
bundle.Dockerfile file for your Operator project.
NOTE
Typically, you run the generate kustomize manifests subcommand first to generate the
input Kustomize bases that are used by the generate bundle subcommand. However,
you can use the make bundle command in an initialized project to automate running
these commands in sequence.
Flag Description
--channels (string) Comma-separated list of channels to which the bundle belongs. The default value
is alpha .
--deploy-dir (string) Root directory for Operator manifests, such as deployments and RBAC. This
directory is different from the directory passed to the --input-dir flag.
--input-dir (string) Directory from which to read an existing bundle. This directory is the parent of
your bundle manifests directory and is different from the--deploy-dir
directory.
--kustomize-dir Directory containing Kustomize bases and a kustomization.yaml file for bundle
(string) manifests. The default path is config/manifests.
134
CHAPTER 8. OPERATOR SDK
Flag Description
--overwrite Overwrite the bundle metadata and Dockerfile if they exist. The default value is
true.
--version (string) Semantic version of the Operator in the generated bundle. Set only when creating
a new bundle or upgrading the Operator.
Additional resources
See Bundling an Operator and deploying with Operator Lifecycle Manager for a full procedure
that includes using the make bundle command to call the generate bundle subcommand.
8.2.5.2. kustomize
The generate kustomize subcommand contains subcommands that generate Kustomize data for the
Operator.
8.2.5.2.1. manifests
The generate kustomize manifests subcommand generates or regenerates Kustomize bases and a
kustomization.yaml file in the config/manifests directory, which are used to build bundle manifests by
other Operator SDK commands. This command interactively asks for UI metadata, an important
component of manifest bases, by default unless a base already exists or you set the --interactive=false
flag.
Flag Description
--interactive When set to false, if no Kustomize base exists, an interactive command prompt is
presented to accept custom metadata.
135
OpenShift Container Platform 4.15 CLI tools
Flag Description
8.2.6. init
The operator-sdk init command initializes an Operator project and generates, or scaffolds, a default
project directory layout for the given plugin.
Flag Description
--plugins (string) Name and optionally version of the plugin to initialize the project with. Available
plugins are ansible.sdk.operatorframework.io/v1, go.kubebuilder.io/v2,
go.kubebuilder.io/v3, and helm.sdk.operatorframework.io/v1.
--project-version Project version. Available values are 2 and 3-alpha, which is the default.
8.2.7. run
The operator-sdk run command provides options that can launch the Operator in various
environments.
8.2.7.1. bundle
The run bundle subcommand deploys an Operator in the bundle format with Operator Lifecycle
136
CHAPTER 8. OPERATOR SDK
The run bundle subcommand deploys an Operator in the bundle format with Operator Lifecycle
Manager (OLM).
Flag Description
--index-image (string) Index image in which to inject a bundle. The default image is quay.io/operator-
framework/upstream-opm-builder:latest .
--install-mode Install mode supported by the cluster service version (CSV) of the Operator, for
<install_mode_value example AllNamespaces or SingleNamespace.
>
--kubeconfig (string) Path to the kubeconfig file to use for CLI requests.
--security-context- Specifies the security context to use for the catalog pod. Allowed values include
config restricted and legacy. The default value is legacy. [1]
<security_context>
1. The restricted security context is not compatible with the default namespace. To configure
your Operator’s pod security admission in your production environment, see "Complying with
pod security admission". For more information about pod security admission, see
"Understanding and managing pod security admission".
Additional resources
8.2.7.2. bundle-upgrade
The run bundle-upgrade subcommand upgrades an Operator that was previously installed in the
bundle format with Operator Lifecycle Manager (OLM).
Flag Description
--kubeconfig (string) Path to the kubeconfig file to use for CLI requests.
137
OpenShift Container Platform 4.15 CLI tools
Flag Description
--security-context- Specifies the security context to use for the catalog pod. Allowed values include
config restricted and legacy. The default value is legacy. [1]
<security_context>
1. The restricted security context is not compatible with the default namespace. To configure
your Operator’s pod security admission in your production environment, see "Complying with
pod security admission". For more information about pod security admission, see
"Understanding and managing pod security admission".
8.2.8. scorecard
The operator-sdk scorecard command runs the scorecard tool to validate an Operator bundle and
provide suggestions for improvements. The command takes one argument, either a bundle image or
directory containing manifests and metadata. If the argument holds an image tag, the image must be
present remotely.
Flag Description
-c, --config (string) Path to scorecard configuration file. The default path is
bundle/tests/scorecard/config.yaml.
-o, --output (string) Output format for results. Available values are text , which is the default, and json .
--pod-security Option to run scorecard with the specified security context. Allowed values
<security_context> include restricted and legacy. The default value is legacy. [1]
-l, --selector (string) Label selector to determine which tests are run.
138
CHAPTER 8. OPERATOR SDK
Flag Description
-s, --service-account Service account to use for tests. The default value is default.
(string)
-w, --wait-time Seconds to wait for tests to complete, for example 35s. The default value is 30s.
<duration>
1. The restricted security context is not compatible with the default namespace. To configure
your Operator’s pod security admission in your production environment, see "Complying with
pod security admission". For more information about pod security admission, see
"Understanding and managing pod security admission".
Additional resources
See Validating Operators using the scorecard tool for details about running the scorecard tool.
139