October 17, 2022

OpenShift 4.6 Automation and Integration: Getting Resources Information, Scripts, Rollout, Job, CronJob, Ansible

Getting Resource Information

$ oc get nodes -o wide

$ oc get nodes -o name

$ oc api-resources

$ oc explain route.spec

$ oc get -n openshift-authentication deployment oauth-openshift -o json

$ oc get -n openshift-authentication deployment oauth-openshift -o jsonpath='{.status.availableReplicas}'

$ oc get -n openshift-authentication deployment oauth-openshift -o jsonpath='{.status.conditions[*].type}'

$ oc get -n openshift-authentication deployment oauth-openshift -o jsonpath='{.spec.template.spec.containers[0].name}'

$ oc get -n openshift-authentication deployment oauth-openshift -o jsonpath='{.status.conditions[?(@.type=="Available")].status}'

$ oc get -n openshift-monitoring route -o jsonpath='{.items[*].spec.host}'

$ oc get pods -A -o custom-columns=NAME:.metadata.name,STATUS:.status.phase,IMAGE:.spec.containers[*].name
$ cat not_ready_pods.jsonpath
{range .items[*]}
  {.metadata.name}
  {range .status.conditions[?(@.status=="False")]}
    {.type}{"="}{.status} {.message}
  {end}
{end}

$ oc get nodes -o jsonpath-file=/tmp/not_ready_pods.jsonpath

Labels

$ oc get nodes --show-labels

$ oc get -n openshift-authentication deployment oauth-openshift --show-labels

$ oc get nodes -l node-role.kubernetes.io/worker= -o name

Creating Scripts for Automation

$ oc wait -h
...
Examples:
  # 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 set it to false
  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
...

$ oc rollout status -h
...
Examples:
  # Watch the status of the latest rollout
  oc rollout status dc/nginx
...
$ cat add-user.sh

#!/bin/bash
username=$1
password=$2

echo "$username:$password"

secretname=$(oc get oauth cluster -o jsonpath='{.spec.identityProviders[?(@.name=="htpasswd")].htpasswd.fileData.name}')

secretfile=$(oc extract secret/$secretname -n openshift-config --confirm)

cut -d : -f 1 $secretfile

htpasswd -B -b $secretfile $username $password 

cat $secretfile

oldpods=$(oc get pods -n openshift-authentication -o name)

oc set data secret/$secretname -n openshift-config --from-file=$secretfile

oc wait co/authentication --for condition=Progressing --timeout=90s

oc rollout status -n openshift-authentication deployment oauth-openshift --timeout=90s

oc wait $oldpods -n openshift-authentication --for delete --timeout=90s

rm -f secretfile

ServiceAccount, Role, RoleBinding, Job and CronJob

https://access.redhat.com/documentation/en-us/openshift_container_platform/4.6/html-single/nodes/index#nodes-nodes-jobs

https://access.redhat.com/documentation/en-us/openshift_container_platform/4.6/html-single/authentication_and_authorization/index#ldap-auto-syncing_ldap-syncing-groups

$ oc get pods -A -o jsonpath='{.items[*].spec.containers[*].image}' | sed 's/ /\n/g' | sort | uniq

$ oc new-project audit

$ oc create serviceaccount audit-sa

$ oc create clusterrole audit-cr --verb=get,list,watch --resource=pods

$ oc create clusterrolebinding audit-crb --clusterrole=audit-cr --serviceaccount=audit:audit-sa

apiVersion: batch/v1
kind: Job
metadata:
  name: audit-job
  namespace: audit
spec:
  parallelism: 1
  completions: 1
  activeDeadlineSeconds: 1800
  backoffLimit: 6
  template:
    metadata:
      name: audit-job
    spec:
      serviceAccount: audit-sa
      serviceAccountName: audit-sa
      restartPolicy: "Never"
      containers:
        - name: audit-job
          image: "registry.redhat.io/openshift4/ose-cli:latest"
          command:
            - "/bin/bash"
            - "-c"
            - "oc get pods --all-namespaces -o jsonpath='{.items[*].spec.containers[*].image}' | sed 's/ /\\\n/g' | sort | uniq"
        
$ echo "Hello from OCP $(date +'%F %T')"

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: hello-cr
  namespace: audit
spec:
  schedule: "*/1 * * * *"  
  successfulJobsHistoryLimit: 3
  failedJobsHistoryLimit: 3
  jobTemplate:
    spec:
      template:
        metadata:
          name: "hello-cr"
          labels:
            parent: "hello-cr"
        spec:
          serviceAccount: audit-sa
          serviceAccountName: audit-sa
          restartPolicy: "Never"
          containers:
            - name: hello-cr
              image: "registry.redhat.io/openshift4/ose-cli:latest"
              command:
                - "/bin/bash"
                - "-c"
                - echo "Hello from OCP $(date +'%F %T')"

Ansible Playbooks

$ sudo dnf install -y ansible ansible-collection-community-kubernetes jq

$ pip install openshift

https://docs.ansible.com/ansible/2.9/modules/list_of_clustering_modules.html#k8s

- name: Demo k8s modules
  hosts: localhost
  become: false
  vars:
    namespace: automation-hello
  module_defaults:
    group/k8s:
      namespace: "{{ namespace }}"
      # ca_cert: "/etc/pki/tls/certs/ca-bundle.crt"
      validate_certs: false
  tasks:
    - name: Create project
      k8s:
        api_version: project.openshift.io/v1
        kind: Project
        name: "{{ namespace }}"
        state: present
        namespace: ""

    - name: Create deployment, service and route
      k8s:
        state: present
        src: "/tmp/hello.yaml"

    - name: Get a pod info
      k8s_info:
        kind: Pod

#    - name: Scale deployment
#      k8s_scale:
#        kind: Deployment
#        name: hello
#        replicas: 3

    - name: Get hostname from the route
      k8s_info:
        kind: Route
        name: hello
      register: route

    - name: Test access
      uri:
        url: "http://{{ route.resources[0].spec.host }}"
        return_content: yes
      register: response
      until: response.status == 200
      retries: 10
      delay: 5

    - name: Display response
      debug:
        var: response.content
apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: hello
  name: hello
  namespace: automation-hello
spec:
  replicas: 1
  selector:
    matchLabels:
      deployment: hello
  template:
    metadata:
      labels:
        deployment: hello
    spec:
      containers:
      - image: quay.io/redhattraining/versioned-hello:v1.0
        name: hello
        ports:
        - containerPort: 8080
          protocol: TCP
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app: hello
  name: hello
  namespace: automation-hello
spec:
  ports:
  - name: 8080-tcp
    port: 8080
    protocol: TCP
    targetPort: 8080
  selector:
    deployment: hello
---
apiVersion: route.openshift.io/v1
kind: Route
metadata:
  labels:
    app: hello
  name: hello
  namespace: automation-hello
spec:
  port:
    targetPort: 8080-tcp
  to:
    kind: Service
    name: hello
$ ansible-playbook /tmp/k8s.yml

No comments: