skip to Main Content

this is the code that i used in gitlab bash:

kubectl --kubeconfig=$KUBECONFIG -n $NAMESPACE_NAME patch service $CI_PROJECT_NAME -p '{"spec": {"selector": {"app.kubernetes.io/instance": "${HELM_NAME}-blue"}}}' 

But when deploying, the following error is shown:
Error from server (BadRequest): invalid character ‘s’ looking for beginning of object key string

i want to using by kubectl patch <resource> update an object.

Where is the problem with the code? Where am I doing wrong?
i think the error is about single and double quotation in json object. but i couldn’t find correct syntax.

2

Answers


  1. Solution:
    kubectl --kubeconfig=$KUBECONFIG -n $NAMESPACE_NAME patch service $CI_PROJECT_NAME -p "{"spec": {"selector": {"app.kubernetes.io/instance": "${HELM_NAME}-blue"}}}"

    Why?

    This is a Bash thing and the difference between " and '.

    " – environmental variables referenced in the string are expanded

    $ export HELM_NAME=release123
    $ echo "${HELM_NAME}"
    release123
    

    ' – environmental variables are NOT expanded

    $ export HELM_NAME=release123
    $ echo '${HELM_NAME}'
    ${HELM_NAME}
    
    Login or Signup to reply.
  2. The error you get is due to the incorrect handling of quotes within the JSON patch string. In your command, you are using both single and double quotes which might be causing the shell to misinterpret the intended structure of the JSON object.

    The approach I suggest is to use single quotes for the entire JSON string and double quotes for the keys and values inside the JSON object.

    Something like this:

    kubectl --kubeconfig=$KUBECONFIG -n $NAMESPACE_NAME patch service $CI_PROJECT_NAME -p '{"spec": {"selector": {"app.kubernetes.io/instance": "'"${HELM_NAME}-blue"'"}}}'
    

    In this command:

    • The entire JSON patch ('{"spec": {"selector": {"app.kubernetes.io/instance": "'"${HELM_NAME}-blue"'"}}}') is enclosed in single quotes to ensure it is treated as a single string by the shell.
    • The value for app.kubernetes.io/instance includes an inner set of double quotes wrapped around a shell variable, by closing the single quotes before the variable ('") and reopening them after the variable ("').
      This should ensure that the value of the variable ${HELM_NAME}-blue is
      correctly interpreted by the shell and then included within double
      quotes in the resulting JSON string.

    This structure prevents the shell and kubectl from misinterpreting the parts of the JSON string and ensures that the patch is formatted correctly as a JSON object.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search