openshift

Run ocp commands inside an Openshift Cronjob to update a Secret


I want to create an Openshift Cronjob to monthly update the password field of an Openshift Secret. I tried to update the password field from a Secret using the ocp cli on my local machine with the patch command with success:

oc patch secret my secret -p '{"data":{"password": ""}}';

This is the Cronjob that I created:

apiVersion: batch/v1beta1
kind: CronJob
metadata:
  name: rotate-postgres-credentials
  namespace: my-ns
spec:
  schedule: "@monthly"       
  concurrencyPolicy: "Replace"  
  jobTemplate:                  
    spec:
      template:
        spec:
          containers:
          - name: oc-cli
            image: 'openshift/origin-cli'
            resources:
              limits:
                cpu: "1"
                memory: 512Mi
              requests:
                cpu: "1"
                memory: 256Mi
            command:
            - /bin/sh
            - '-c'
            - >-
              oc login https://******:6443/ --insecure-skip-tls-verify -u my-user -p my-pass;
              oc project my-ns;
              oc patch secret my-secret -p '{"data":{"password": ""}}';
          restartPolicy: OnFailure

and after run this Cronjob I see this error message on the pod log:

Logged into "https://******:6443" as "my-user" using the token provided.

You have access to *** projects, the list has been suppressed. You can list all projects with 'oc projects'

Using project "default".
error: KUBECONFIG is set to a file that cannot be created or modified: /.kube/config; caused by: mkdir /.kube: permission denied
error: You are not a member of project "my-ns".
You are not a member of any projects. You can request a project to be created with the 'new-project' command.
Error from server (Forbidden): secrets "pg-creditcard-pguser-creditcard" is forbidden: User "system:serviceaccount:my-ns:default" cannot get resource "secrets" in API group "" in the namespace "my-ns"

I don´t know exactly why inside the Cronjob the patch command is not working and in my local machine is working fine, since my user has rights to edit the Secret.

Also I'm using the image "openshift/origin-cli", but I don´t know if is the correct one to run ocp commands.

Does anyone knows how to successfully run ocp commands inside a Cronjob?


Solution

  • Based on the below error, it evident that logged in user doesn't have access to modify the secret.

    Error from server (Forbidden): secrets "pg-creditcard-pguser-creditcard" is forbidden: User "system:serviceaccount:my-ns:default" cannot get resource "secrets" in API group "" in the namespace "my-ns"

    Either grant access to the user to update secret. Best practice is to create a service account, grant the privileges to update this secret and your CronJob uses this service account to run.

    This will avoid individual users getting the update privileges.