CLI reference
- Overview
- Install the CLI
- Log on to the CLI
- Get help
- Extend the CLI with plug-ins
- Basic CLI commands
- CLI commands
- Troubleshoot and debugging CLI commands
- Advanced developer CLI commands
- api-resources
- api-versions
- auth
- cluster-info
- convert
- extract
- idle
- image
- observe
- patch
- policy
- process
- registry
- replace
- CLI commands
- management CLI commands
- Security and policy CLI commands
- Maintenance CLI commands
- Configuration CLI commands
Overview
With the OpenShift command-line interface (CLI), we can create applications and manage OpenShift projects from a terminal. The CLI is ideal in situations where you:
- Work directly with project source code.
- Script OpenShift operations.
- Are restricted by bandwidth resources and can not use the web console.
Install the CLI
We can install the CLI in order to interact with OpenShift using a command-line interface.
Procedure
- From the OpenShift Infrastructure Providers page, click Download Command-line Tools.
- Click the folder for your operating system and architecture and click the compressed file.
- Save the file to your file system.
- Extract the compressed file.
- Place it in a directory that is on your PATH.
After installing the CLI, it is available using the oc command:
$ oc <command>
Log on to the CLI
- Obtain access to an OpenShift cluster.
- Log in to the CLI using the oc login command...
$ oc login Server [https://localhost:8443]: https://openshift.example.com:6443 The server uses a certificate signed by an unknown authority. You can bypass the certificate check, but any data you send to the server could be intercepted by others. Use insecure connections? (y/n): y Authentication required for https://openshift.example.com:6443 (openshift) Username: user1 Password: Login successful. You don't have any projects. You can try to create a new project, by running oc new-project <projectname> Welcome! See 'oc help' to get started.We can now create a project or issue other commands for managing the cluster.
Create a project
Create a new project.
$ oc new-project my-project Now using project "my-project" on server "https://openshift.example.com:6443".
Create a new app
Create a new application.
$ oc new-app https://github.com/sclorg/cakephp-ex --> Found image 40de956 (9 days old) in imagestream "openshift/php" under tag "7.2" for "php" ... Run 'oc status' to view your app.
View pods
View the pods for the current project.
$ oc get pods -o wide NAME READY STATUS RESTARTS AGE IP NODE NOMINATED NODE cakephp-ex-1-build 0/1 Completed 0 5m45s 10.131.0.10 ip-10-0-141-74.ec2.internal <none> cakephp-ex-1-deploy 0/1 Completed 0 3m44s 10.129.2.9 ip-10-0-147-65.ec2.internal <none> cakephp-ex-1-ktz97 1/1 Running 0 3m33s 10.128.2.11 ip-10-0-168-105.ec2.internal <none>
View pod logs
View logs for a particular pod.
$ oc logs cakephp-ex-1-deploy --> Scaling cakephp-ex-1 to 1 --> Success
View the current project
View the current project.
$ oc project Using project "my-project" on server "https://openshift.example.com:6443".
View the status for the current project
View information about the current project, such as Services, DeploymentConfigs, and BuildConfigs.
$ oc status In project my-project on server https://openshift.example.com:6443 svc/cakephp-ex - 172.30.236.80 ports 8080, 8443 dc/cakephp-ex deploys istag/cakephp-ex:latest <- bc/cakephp-ex source builds https://github.com/sclorg/cakephp-ex on openshift/php:7.2 deployment #1 deployed 2 minutes ago - 1 pod 3 infos identified, use 'oc status --suggest' to see details.
List supported API resources
$ oc api-resources NAME SHORTNAMES APIGROUP NAMESPACED KIND bindings true Binding componentstatuses cs false ComponentStatus configmaps cm true ConfigMap ...
Get help
- Use oc help to get a list and description of all available CLI commands:
$ oc help OpenShift Client This client helps you develop, build, deploy, and run our 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 ...Get help about a specific CLI command: Example: Get help for the oc create command
$ oc create --help Create a resource by filename or stdin JSON and YAML formats are accepted. Usage: oc create -f FILENAME [flags] ...View the description and fields for a particular resource: Example: View documentation for the Pod resource
$ oc explain pods 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 ...
Log out of the CLI
$ oc logout Logged "user1" out on "https://openshift.example.com"This deletes the saved authentication token from the server and removes it from your configuration file.
Enable tab completion
We can enable tab completion to automatically complete oc commands or suggest options when you press Tab.
Prerequisites
- We must have the oc CLI tool installed.
Procedure
The following procedure enables tab completion for Bash.
- Save the Bash completion code to a file.
$ oc completion bash > oc_bash_completion- Copy the file to /etc/bash_completion.d/.
$ sudo cp oc_bash_completion /etc/bash_completion.d/We can also save the file to a local directory and source it from your .bashrc file instead.
Tab completion is enabled when you open a new terminal.
Extend the CLI with plug-ins
We can write and install plug-ins to build on the default oc commands, allowing you to perform new and more complex tasks with the OpenShift CLI.
Write CLI plug-ins
We can write a plug-in for the OpenShift CLI in any programming language or script that allows us to write command-line commands. Note that we can not use a plug-in to overwrite an existing oc command. Important
OpenShift CLI plug-ins are currently a Technology Preview feature. Technology Preview features are not supported with Red Hat production service level agreements (SLAs), might not be functionally complete, and Red Hat does not recommend to use them for production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process.
See the Red Hat Technology Preview features support scope for more information.
Procedure
This procedure creates a simple Bash plug-in that prints a message to the terminal when the oc foo command is issued.
- Create a file called oc-foo.
When naming your plug-in file, keep the following in mind:
- The file must begin with oc- or kubectl- in order to be recognized as a plug-in.
- The file name determines the command that invokes the plug-in. For example, a plug-in with the file name oc-foo-bar can be invoked by a command of oc foo bar. We can also use underscores if we want the command to contain dashes. For example, a plug-in with the file name oc-foo_bar can be invoked by a command of oc foo-bar.
- Add the following contents to the file.
#!/bin/bash # optional argument handling if [[ "$1" == "version" ]] then echo "1.0.0" exit 0 fi # optional argument handling if [[ "$1" == "config" ]] then echo $KUBECONFIG exit 0 fi echo "I am a plugin named kubectl-foo"After installing this plug-in for the OpenShift CLI, it can be invoked using the oc foo command.
Additional resources
- Review the Sample plug-in repository for an example of a plug-in written in Go.
- Review the CLI runtime repository for a set of utilities to assist in writing plug-ins in Go.
Install and use CLI plug-ins
After you write a custom plug-in for the OpenShift CLI, we must install it to use the functionality that it provides. Important
OpenShift CLI plug-ins are currently a Technology Preview feature. Technology Preview features are not supported with Red Hat production service level agreements (SLAs), might not be functionally complete, and Red Hat does not recommend to use them for production. These features provide early access to upcoming product features, enabling customers to test functionality and provide feedback during the development process.
See the Red Hat Technology Preview features support scope for more information.
Prerequisites
- We must have the oc CLI tool installed.
- We must have a CLI plug-in file that begins with oc- or kubectl-.
Procedure
- If necessary, update the plug-in file to be executable.
$ chmod +x <plugin_file>- Place the file anywhere in your PATH, such as /usr/local/bin/.
$ sudo mv <plugin_file> /usr/local/bin/.- Run oc plugin list to make sure that the plug-in is listed.
$ oc plugin list The following compatible plugins are available: /usr/local/bin/<plugin_file>If your plug-in is not listed here, verify that the file begins with oc- or kubectl-, is executable, and is on your PATH.
- Invoke the new command or option introduced by the plug-in.
For example, if you built and installed the kubectl-ns plug-in from the Sample plug-in repository, we can use the following command to view the current namespace.
$ oc nsNote that the command to invoke the plug-in depends on the plug-in file name. For example, a plug-in with the file name of oc-foo-bar is invoked by the oc foo bar command.
Basic CLI commands
explain
Display documentation for a certain resource.
Example: Display documentation for Pods
$ oc explain pods
login
Log in to the OpenShift server and save login information for subsequent use.
Example: Interactive login
$ oc loginExample: Log in specifying a user name
$ oc login -u user1
new-app
Create a new application by specifying source code, a template, or an image.
Example: Create a new application from a local Git repository
$ oc new-app .Example: Create a new application from a remote Git repository
$ oc new-app https://github.com/sclorg/cakephp-exExample: Create a new application from a private remote repository
$ oc new-app https://github.com/youruser/yourprivaterepo --source-secret=yoursecret
new-project
Create a new project and switch to it as the default project in your configuration.
Example: Create a new project
$ oc new-project myproject
project
Switch to another project and make it the default in your configuration.
Example: Switch to a different project
$ oc project test-project
projects
Display information about the current active project and existing projects on the server.
Example: List all projects
$ oc projects
status
Show a high-level overview of the current project.
Example: Show the status of the current project
$ oc status
Build and Deploy CLI commands
cancel-build
Cancel a running, pending, or new build.
Example: Cancel a build
$ oc cancel-build python-1Example: Cancel all pending builds from the python BuildConfig
$ oc cancel-build buildconfig/python --state=pending
import-image
Import the latest tag and image information from an image repository.
Example: Import the latest image information
$ oc import-image my-ruby
new-build
Create a new BuildConfig from source code.
Example: Create a BuildConfig from a local Git repository
$ oc new-build .Example: Create a BuildConfig from a remote Git repository
$ oc new-build https://github.com/sclorg/cakephp-ex
rollback
Revert an application back to a previous Deployment.
Example: Roll back to the last successful Deployment
$ oc rollback phpExample: Roll back to a specific version
$ oc rollback php --to-version=3
rollout
Start a new rollout, view its status or history, or roll back to a previous revision of our application.
Example: Roll back to the last successful Deployment
$ oc rollout undo deploymentconfig/phpExample: Start a new rollout for a DeploymentConfig with its latest state
$ oc rollout latest deploymentconfig/php
start-build
Start a build from a BuildConfig or copy an existing build.
Example: Start a build from the specified BuildConfig
$ oc start-build pythonExample: Start a build from a previous build
$ oc start-build --from-build=python-1Example: Set an environment variable to use for the current build
$ oc start-build python --env=mykey=myvalue
tag
Tag existing images into imagestreams.
Example: Configure the ruby image's latest tag to refer to the image for the 2.0 tag
$ oc tag ruby:latest ruby:2.0
Application management CLI commands
annotate
Update the annotations on one or more resources.
Example: Add an annotation to a Route
$ oc annotate route/test-route haproxy.router.openshift.io/ip_whitelist="192.168.1.10"Example: Remove the annotation from the Route
$ oc annotate route/test-route haproxy.router.openshift.io/ip_whitelist-
apply
Apply a configuration to a resource by file name or standard in (stdin) in JSON or YAML format.
Example: Apply the configuration in pod.json to a Pod
$ oc apply -f pod.json
autoscale
Autoscale a DeploymentConfig or ReplicationController.
Example: Autoscale to a minimum of two and maximum of five Pods
$ oc autoscale deploymentconfig/parksmap-katacoda --min=2 --max=5
create
Create a resource by file name or standard in (stdin) in JSON or YAML format.
Example: Create a Pod using the content in pod.json
$ oc create -f pod.json
delete
Delete a resource.
Example: Delete a Pod named parksmap-katacoda-1-qfqz4
$ oc delete pod/parksmap-katacoda-1-qfqz4Example: Delete all Pods with the app=parksmap-katacoda label
$ oc delete pods -l app=parksmap-katacoda
describe
Return detailed information about a specific object.
Example: Describe a Deployment named example
$ oc describe deployment/exampleExample: Describe all Pods
$ oc describe pods
edit
Edit a resource.
Example: Edit a DeploymentConfig using the default editor
$ oc edit deploymentconfig/parksmap-katacoda
Example: Edit a DeploymentConfig using a different editor
$ OC_EDITOR="nano" oc edit deploymentconfig/parksmap-katacoda
Example: Edit a DeploymentConfig in JSON format
$ oc edit deploymentconfig/parksmap-katacoda -o json
expose
Expose a Service externally as a Route.
Example: Expose a Service
$ oc expose service/parksmap-katacodaExample: Expose a Service and specify the host name
$ oc expose service/parksmap-katacoda --hostname=www.my-host.com
get
Display one or more resources.
Example: List Pods in the default namespace
$ oc get pods -n defaultExample: Get details about the python DeploymentConfig in JSON format
$ oc get deploymentconfig/python -o json
label
Update the labels on one or more resources.
Example: Update the python-1-mz2rf Pod with the label status set to unhealthy
$ oc label pod/python-1-mz2rf status=unhealthy
scale
Set the desired number of replicas for a ReplicationController or a DeploymentConfig.
Example: Scale the ruby-app DeploymentConfig to three Pods
$ oc scale deploymentconfig/ruby-app --replicas=3
secrets
Manage secrets in our project.
Example: Allow my-pull-secret to be used as an image pull secret by the default service account
$ oc secrets link default my-pull-secret --for=pull
serviceaccounts
Get a token assigned to a service account or create a new token or kubeconfig file for a service account.
Example: Get the token assigned to the default service account
$ oc serviceaccounts get-token default
set
Configure existing application resources.
Example: Sets the name of a secret on a BuildConfig
$ oc set build-secret --source buildconfig/mybc mysecret
Troubleshoot and debugging CLI commands
attach
Attach the shell to a running container.
Example: Get output from the python container from Pod python-1-mz2rf
$ oc attach python-1-mz2rf -c python
cp
Copy files and directories to and from containers.
Example: Copy a file from the python-1-mz2rf Pod to the local file system
$ oc cp default/python-1-mz2rf:/opt/app-root/src/README.md ~/mydirectory/.
debug
Launch a command shell to debug a running application.
Example: Debug the python Deployment
$ oc debug deploymentconfig/python
exec
Execute a command in a container.
Example: Execute the ls command in the python container from Pod python-1-mz2rf
$ oc exec python-1-mz2rf -c python ls
logs
Retrieve the log output for a specific build, BuildConfig, DeploymentConfig, or Pod.
Example: Stream the latest logs from the python DeploymentConfig
$ oc logs -f deploymentconfig/python
port-forward
Forward one or more local ports to a Pod.
Example: Listen on port 8888 locally and forward to port 5000 in the Pod
$ oc port-forward python-1-mz2rf 8888:5000
proxy
Run a proxy to the Kubernetes API server.
Example: Run a proxy to the API server on port 8011 serving static content from ./local/www/
$ oc proxy --port=8011 --www=./local/www/
rsh
Open a remote shell session to a container.
Example: Open a shell session on the first container in the python-1-mz2rf Pod
$ oc rsh python-1-mz2rf
rsync
Copy contents of a directory to or from a running Pod container. Only changed files are copied using the rsync command from your operating system.
Example: Synchronize files from a local directory with a Pod directory
$ oc rsync ~/mydirectory/ python-1-mz2rf:/opt/app-root/src/
run
Create and run a particular image. By default, this creates a DeploymentConfig to manage the created containers.
Example: Start an instance of the perl image with three replicas
$ oc run my-test --image=perl --replicas=3
wait
Wait for a specific condition on one or more resources.
Example: Wait for the python-1-mz2rf Pod to be deleted
$ oc wait --for=delete pod/python-1-mz2rf
Advanced developer CLI commands
api-resources
Display the full list of API resources that the server supports.
Example: List the supported API resources
$ oc api-resources
api-versions
Display the full list of API versions that the server supports.
Example: List the supported API versions
$ oc api-versions
auth
Inspect permissions and reconcile RBAC roles.
Example: Check whether the current user can read Pod logs
$ oc auth can-i get pods --subresource=logExample: Reconcile RBAC roles and permissions from a file
$ oc auth reconcile -f policy.json
cluster-info
Display the address of the master and cluster services.
Example: Display cluster information
$ oc cluster-info
convert
Convert a YAML or JSON configuration file to a different API version and print to standard output (stdout).
Example: Convert pod.yaml to the latest version
$ oc convert -f pod.yaml
extract
Extract the contents of a ConfigMap or secret. Each key in the ConfigMap or secret is created as a separate file with the name of the key.
Example: Download the contents of the ruby-1-ca ConfigMap to the current directory
$ oc extract configmap/ruby-1-caExample: Print the contents of the ruby-1-ca ConfigMap to stdout
$ oc extract configmap/ruby-1-ca --to=-
idle
Idle scalable resources. An idled Service will automatically become unidled when it receives traffic or it can be manually unidled using the oc scale command.
Example: Idle the ruby-app Service
$ oc idle ruby-app
image
Manage images in the OpenShift cluster.
Example: Copy an image to another tag
$ oc image mirror myregistry.com/myimage:latest myregistry.com/myimage:stable
observe
Observe changes to resources and take action on them.
Example: Observe changes to Services
$ oc observe services
patch
Updates one or more fields of an object using strategic merge patch in JSON or YAML format.
Example: Update the spec.unschedulable field for node node1 to true
$ oc patch node/node1 -p '{"spec":{"unschedulable":true}}'NoteIf we must patch a Custom Resource Definition, we must include the --type merge option in the command.
policy
Manage authorization policies.
Example: Add the edit role to user1 for the current project
$ oc policy add-role-to-user edit user1
process
Process a template into a list of resources.
Example: Convert template.json to a resource list and pass to oc create
$ oc process -f template.json | oc create -f -
registry
Manage the integrated registry on OpenShift.
Example: Display information about the integrated registry
$ oc registry info
replace
Modify an existing object based on the contents of the specified configuration file.
Example: Update a Pod using the content in pod.json
$ oc replace -f pod.json
Sets CLI commands
completion
Output shell completion code for the specified shell.
Example: Display completion code for Bash
$ oc completion bash
config
Manage the client configuration files.
Example: Display the current configuration
$ oc config viewExample: Switch to a different context
$ oc config use-context test-context
logout
Log out of the current session.
Example: End the current session
$ oc logout
whoami
Display information about the current session.
Example: Display the currently authenticated user
$ oc whoami
Other developer CLI commands
help
Display general help information for the CLI and a list of available commands.
Example: Display available commands
$ oc helpExample: Display the help for the new-project command
$ oc help new-project
plugin
List the available plug-ins on the user's PATH.
Example: List available plug-ins
$ oc plugin list
version
Display the oc client and server versions.
Example: Display version information
$ oc version------------------------ Last updated: 2019-08-22 ------------------------
Administrator CLI commands
Cluster management CLI commands
must-gather
Bulk collect data about the current state of the cluster to debug issues.
Example: Gather debugging information
$ oc adm must-gather
top
Show usage statistics of resources on the server.
Example: Show CPU and memory usage for Pods
$ oc adm top podsExample: Show usage statistics for images
$ oc adm top images
Node management CLI commands
cordon
Mark a node as unschedulable. Manually marking a node as unschedulable blocks any new pods from being scheduled on the node, but does not affect existing pods on the node.
Example: Mark node1 as unschedulable
$ oc adm cordon node1
drain
Drain a node in preparation for maintenance.
Example: Drain node1
$ oc adm drain node1
node-logs
Display and filter node logs.
Example: Get logs for NetworkManager
$ oc adm node-logs --role master -u NetworkManager.service
taint
Update the taints on one or more nodes.
Example: Add a taint to dedicate a node for a set of users
$ oc adm taint nodes node1 dedicated=groupName:NoScheduleExample: Remove the taints with key dedicated from node node1
$ oc adm taint nodes node1 dedicated-
uncordon
Mark a node as schedulable.
Example: Mark node1 as schedulable
$ oc adm uncordon node1
Security and policy CLI commands
certificate
Approve or reject certificate signing requests (CSRs).
Example: Approve a CSR
$ oc adm certificate approve csr-sqgzp
groups
Manage groups in the cluster.
Example: Create a new group
$ oc adm groups new my-group
new-project
Create a new project and specify administrative options.
Example: Create a new project using a node selector
$ oc adm new-project myproject --node-selector='type=user-node,region=east'
pod-network
Manage Pod networks in the cluster.
Example: Isolate project1 and project2 from other non-global projects
$ oc adm pod-network isolate-projects project1 project2
policy
Manage roles and policies on the cluster.
Example: Add the edit role to user1 for all projects
$ oc adm policy add-cluster-role-to-user edit user1Example: Add the privileged security context constraint to a service account
$ oc adm policy add-scc-to-user privileged -z myserviceaccount
Maintenance CLI commands
migrate
Migrate resources on the cluster to a new version or format depending on the subcommand used.
Example: Perform an update of all stored objects
$ oc adm migrate storageExample: Perform an update of only Pods
$ oc adm migrate storage --include=pods
prune
Remove older versions of resources from the server.
Example: Prune older builds including those whose BuildConfigs no longer exist
$ oc adm prune builds --orphans
Configuration CLI commands
create-api-client-config
Create a client configuration for connecting to the server. This creates a folder containing a client certificate, a client key, a server certificate authority, and a kubeconfig file for connecting to the master as the provided user.
Example: Generate a client certificate for a proxy
$ oc adm create-api-client-config \ --certificate-authority='/etc/origin/master/proxyca.crt' \ --client-dir='/etc/origin/master/proxy' \ --signer-cert='/etc/origin/master/proxyca.crt' \ --signer-key='/etc/origin/master/proxyca.key' \ --signer-serial='/etc/origin/master/proxyca.serial.txt' \ --user='system:proxy'
create-bootstrap-policy-file
Create the default bootstrap policy.
Example: Create a file called policy.json with the default bootstrap policy
$ oc adm create-bootstrap-policy-file --filename=policy.json
create-bootstrap-project-template
Create a bootstrap project template.
Example: Output a bootstrap project template in YAML format to stdout
$ oc adm create-bootstrap-project-template -o yaml
create-error-template
Create a template for customizing the error page.
Example: Output a template for the error page to stdout
$ oc adm create-error-template
create-kubeconfig
Creates a basic .kubeconfig file from client certificates.
Example: Create a .kubeconfig file with the provided client certificates
$ oc adm create-kubeconfig \ --client-certificate=/path/to/client.crt \ --client-key=/path/to/client.key \ --certificate-authority=/path/to/ca.crt
create-login-template
Create a template for customizing the login page.
Example: Output a template for the login page to stdout
$ oc adm create-login-template
create-provider-selection-template
Create a template for customizing the provider selection page.
Example: Output a template for the provider selection page to stdout
$ oc adm create-provider-selection-template
Other Administrator CLI commands
build-chain
Output the inputs and dependencies of any builds.
Example: Output dependencies for the perl imagestream
$ oc adm build-chain perl
completion
Output shell completion code for the oc adm commands for the specified shell.
Example: Display oc adm completion code for Bash
$ oc adm completion bash
config
Manage the client configuration files. This command has the same behavior as the oc config command.
Example: Display the current configuration
$ oc adm config viewExample: Switch to a different context
$ oc adm config use-context test-context
release
Manage various aspects of the OpenShift release process, such as viewing information about a release or inspecting the contents of a release.
Example: Generate a changelog between two releases and save to changelog.md
$ oc adm release info --changelog=/tmp/git \ quay.io/openshift-release-dev/ocp-release:4.1.0-rc.7 \ quay.io/openshift-release-dev/ocp-release:4.1.0 \ > changelog.md
verify-image-signature
Verify the image signature of an image imported to the internal registry using the local public GPG key.
Example: Verify the nodejs image signature
$ oc adm verify-image-signature \ sha256:2bba968aedb7dd2aafe5fa8c7453f5ac36a0b9639f1bf5b03f95de325238b288 \ --expected-identity 172.30.1.1:5000/openshift/nodejs:latest \ --public-key /etc/pki/rpm-gpg/RPM-GPG-KEY-redhat-release \ --save
Quick Links
Help
Site Info
Related Sites
About