Skip to content

Instantly share code, notes, and snippets.

@mpreu
Last active February 22, 2021 15:00
Show Gist options
  • Save mpreu/2434d56870cb2ad7e2ab8f9043d6d92e to your computer and use it in GitHub Desktop.
Save mpreu/2434d56870cb2ad7e2ab8f9043d6d92e to your computer and use it in GitHub Desktop.
OCP unique project generation.

To generate projects in OpenShift with unique names without manually intervention:

Via REST API:

TOKEN=$(oc whoami -t)
ENDPOINT=$(oc config current-context | cut -d/ -f2 | tr - .)

curl -k \
    -X POST \
    -d @- \
    -H "Authorization: Bearer $TOKEN" \
    -H 'Accept: application/json' \
    -H 'Content-Type: application/json' \
    https://$ENDPOINT/api/v1/namespaces <<'EOF'
{
  "kind": "Namespace",
  "apiVersion": "v1",
  "metadata": {
      "generateName": "cso-",
      "annotations": {
        "openshift.io/display-name": "Test project",
        "openshift.io/description": "Test project with generateName"
      }   
  }
}
EOF

# Check response body and code 201

# Be aware of the error condition:
#
# If this field is specified and the generated name exists, 
# the server will NOT return a 409 - instead, it will either 
# return 201 Created or 500 with Reason ServerTimeout indicating 
# a unique name could not be found in the time allotted, and the 
# client should retry (optionally after the time indicated in the Retry-After header).

Via resource yaml:

cat << EOF > project.yaml
apiVersion: v1
kind: Namespace
metadata:
  annotations:
    "openshift.io/display-name": "Test project"
    "openshift.io/description": "Test project with generateName"
  generateName: cso-
EOF

oc create -f project.yaml

The internal implementation how a name is generated can be found here: https://github.com/kubernetes/apiserver/blob/master/pkg/storage/names/generate.go https://github.com/kubernetes/apimachinery/blob/master/pkg/util/rand/rand.go

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment