google-cloud-platformgoogle-cloud-build

How To Set A GCloud Flag During Cloud Build Runtime?


I need to set a Gcloud deployment flag with an environment variable that I set during runtime. The reason for this is that I am trying to version my cloud run services and if the parameter TAG_NAME comes in as ver1.0.0 or ver1.0.1 I only ever want it to be the variable ver1.

So long story short I want to be able to use

_CUT_TAG=$(echo $TAG_NAME | cut -d '.' -f 1)

In the script below to set the parameter

 --tag $_CUT_TAG \

But every time I try to set it the function fails. Here is the entire command:

  - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
    entrypoint: 'bash'
    args:
      - '-c'
      - |
        _CUT_TAG=$(echo $TAG_NAME | cut -d '.' -f 1)

        gcloud beta run deploy my-service \
          --image gcr.io/$PROJECT_ID/account-service \
          --region us-central1 \
          --tag $_CUT_TAG \

And here is the error I am receiving

ERROR: (gcloud.beta.run.deploy) argument --tag: expected one argument

which is telling me that the parameter isnt getting set.


Solution

  • I suspect your command's flags and values are being mangled.

    When you use long flags (apart from being easier to understand), you can use = to bind to the value, i.e. --tag=value.

    Try:

    - name: 'gcr.io/google.com/cloudsdktool/cloud-sdk'
        entrypoint: 'bash'
        args:
          - '-c'
          - |
            _CUT_TAG=$(echo $TAG_NAME | cut -d '.' -f 1)
    
            gcloud beta run deploy my-service \
              --image=gcr.io/$PROJECT_ID/account-service \
              --region=us-central1 \
              --tag=${_CUT_TAG} \
              ...
    

    Because you're using bash, you benefit from the richness of the shell in your script. So you could, e.g.:

    _CUT_TAG=$(echo $TAG_NAME | cut -d '.' -f 1)
    
    printf "_CUT_TAG=%s" ${_CUT_TAG}
    
    # Echo the gcloud command to see what's being generated
    echo gcloud beta run deploy my-service \
    --image=gcr.io/$PROJECT_ID/account-service \
    --region=us-central1 \
    --tag=${_CUT_TAG} \
    ...
    

    Please consider providing a minimal-repro of your issue in your questions. Your YAML snippet is less value to future readers and requires more work to recreate your issue by those responding.