Kahibaro
Discord Login Register

6.2 OpenShift CLI (oc)

What the `oc` CLI Is and When to Use It

The oc command-line interface is the primary tool for interacting with OpenShift clusters from a terminal. It builds on Kubernetes kubectl concepts, but adds OpenShift-specific commands and workflows (for example, working with projects, routes, and Builds).

You typically use oc to:

The web console is ideal for exploration and visualization; oc is better for automation, scripting, and fast, repeatable operations.

Installing and Configuring `oc`

Getting the `oc` Binary

You normally install oc from:

The installation steps differ by operating system, but in all cases you:

  1. Download the appropriate archive.
  2. Extract it and place the oc binary into a directory on your PATH.
  3. Confirm installation with:
bash
oc version

You should see both the client version and (if connected) the server version.

Cluster Access Prerequisites

To use oc against a cluster, you need:

Access control specifics are covered under authentication/authorization; here we focus on how oc uses these.

Authenticating with `oc`

Basic Login

You typically log into a cluster with:

bash
oc login https://api.example.openshift.com:6443

oc will prompt for a username and password (or redirect you to a browser, depending on the configured identity provider).

Once logged in, oc stores your credentials and cluster information in a kubeconfig file (by default ~/.kube/config).

You can check your current context with:

bash
oc whoami
oc whoami --show-context
oc whoami --show-server

Token-Based Login

You may be given a token (for example from the web console):

bash
oc login --token=<token> --server=https://api.example.openshift.com:6443

Tokens are useful for:

Never hardcode tokens in public scripts or repositories.

Working with Multiple Clusters and Contexts

The kubeconfig file can store multiple clusters, users, and contexts. oc commands respect the current context, which usually maps to:

Common context operations:

bash
# List known clusters and contexts
oc config get-contexts
# Switch context
oc config use-context my-cluster-context
# View current context details
oc config view --minify

Working with Projects and Namespaces via `oc`

OpenShift uses projects as a higher-level concept over Kubernetes namespaces. From the CLI, you manage them with oc:

bash
# List projects you can access
oc get projects
# Switch the active project (affects default namespace for commands)
oc project my-app-project
# Show current project
oc project

Many oc commands implicitly operate in your current project. You can override this with the -n or --namespace flag:

bash
oc get pods -n other-project

Exploring Cluster Resources with `oc`

Discovering Resource Types

To see what you can manage:

bash
oc api-resources           # list all API resources
oc api-versions            # list enabled API versions

To get help on a specific resource type:

bash
oc explain pods
oc explain deployment.spec

oc explain shows fields and their descriptions, useful when editing YAML or learning resource structure.

Basic Get, Describe, and Logs

Some core inspection commands:

bash
# List resources
oc get pods
oc get svc
oc get deployment
# More details, including age, selectors, etc.
oc get pods -o wide
# Show full details of one object
oc describe pod my-pod-123
# View pod logs
oc logs my-pod-123
oc logs -f my-pod-123             # follow logs
oc logs deployment/my-deployment  # logs from pods of a deployment

To work with multiple resource types in one command:

bash
oc get pods,svc,route

Creating and Modifying Resources

Declarative vs Imperative with `oc`

With oc, you generally work in two ways:

Imperative Examples

bash
# Create a new project
oc new-project demo
# Create a configmap from a file
oc create configmap app-config --from-file=config.yml
# Expose a service as a route
oc expose svc/my-service
# Scale a deployment
oc scale deployment my-deployment --replicas=3

Declarative Examples

bash
# Apply configuration from file or directory
oc apply -f deployment.yaml
oc apply -f k8s-manifests/
# Create from file (fail if it already exists)
oc create -f service.yaml
# Replace whole object definition
oc replace -f deployment.yaml

oc apply is generally preferable for iterative configuration management, as it attempts to merge changes.

Editing Resources In-Place

For small modifications:

bash
oc edit deployment my-deployment

oc opens your default editor, lets you change the YAML, then sends the updated object back to the API. This is convenient for quick changes, but less appropriate for long-term, version-controlled configuration.

For one-off patches:

bash
oc patch deployment my-deployment \
  -p '{"spec":{"replicas":4}}' \
  --type=merge

Application-Centric `oc` Commands

OpenShift adds several higher-level oc commands that work at an application level, abstracting multiple lower-level resources.

`oc new-app`

oc new-app helps quickly create and deploy an application from:

Examples:

bash
# From source + builder image (Source-to-Image workflow)
oc new-app quay.io/org/php-74~https://github.com/example/my-php-app.git
# From an existing image
oc new-app quay.io/library/nginx:latest
# From a template
oc new-app --template=my-template -p KEY=VALUE

oc new-app typically creates:

It’s ideal for rapid prototyping and learning, but in more mature setups, you often move to fully declarative manifests or pipelines.

`oc start-build` and Builds

When your applications use OpenShift Builds (e.g., Source-to-Image):

bash
# Start a build from a BuildConfig
oc start-build my-app
# Follow logs of the started build
oc start-build my-app --follow
# Rebuild from local source
oc start-build my-app --from-dir=. --follow

These commands integrate tightly with the OpenShift build and image ecosystem.

Managing Deployments with `oc`

For deployment-related actions:

bash
# Scale
oc scale deployment my-app --replicas=3
# Roll out a new version (when using deployments)
oc rollout restart deployment/my-app
# Monitor rollout status
oc rollout status deployment/my-app
# View rollout history (if recorded)
oc rollout history deployment/my-app
# Roll back to previous revision
oc rollout undo deployment/my-app

You can also inspect deployment details:

bash
oc get deployment my-app -o yaml
oc describe deployment my-app

Accessing Applications and Debugging with `oc`

Port-Forwarding

When you need local access to a pod’s port without exposing it externally:

bash
oc port-forward pod/my-pod 8080:80

This forwards local port 8080 to port 80 on the pod, useful for debugging services from your workstation.

Executing Commands in Pods

To run commands inside a running container:

bash
# Execute a command
oc exec pod/my-pod -- ls /app
# Get an interactive shell
oc rsh pod/my-pod
# or
oc exec -it pod/my-pod -- /bin/bash

oc rsh picks a container and shell automatically when possible; oc exec is more explicit.

Debugging Pods

oc debug can spin up a debug pod or modify an existing one for troubleshooting:

bash
# Debug a node (if you have permissions)
oc debug node/worker-1
# Debug a pod (creates a copy with a different command)
oc debug pod/my-pod

This is useful when the original container image lacks debugging tools.

Working with YAML and Output Formats

Most oc get commands support various output formats:

bash
# Raw YAML or JSON
oc get pod my-pod -o yaml
oc get pod my-pod -o json
# Custom columns
oc get pods -o custom-columns=NAME:.metadata.name,IP:.status.podIP
# Name-only list (handy for scripting)
oc get pods -o name

You can combine this with Unix tools like grep, jq, or yq for powerful ad-hoc queries.

For generating skeleton manifests:

bash
oc create deployment my-app --image=nginx --dry-run=client -o yaml

This prints YAML without creating the object, so you can redirect to a file and edit:

bash
oc create deployment my-app --image=nginx --dry-run=client -o yaml > deployment.yaml

Using `oc` in Scripts and Automation

oc is widely used in shell scripts and CI pipelines. A few patterns:

Example: wait for a rollout in a script:

bash
oc rollout status deployment/my-app --timeout=120s

Example: check if a route is available:

bash
if oc get route my-app-route >/dev/null 2>&1; then
  echo "Route exists"
else
  echo "Route missing"
fi

For CI/CD, it’s common to:

Getting Help and Learning More `oc` Commands

oc has extensive built-in help:

bash
oc --help            # top-level help
oc get --help        # help for a specific command
oc new-app --help

You can discover subcommands with autocomplete (if enabled in your shell) or by listing:

bash
oc | less

Over time, you’ll develop a core set of frequently used commands; for everything else, --help and oc explain are the quickest way to explore capabilities without leaving the terminal.

Views: 60

Comments

Please login to add a comment.

Don't have an account? Register now!