Is there a way for Jenkins to dynamically set Bitbucket workspace variables?

Jenkins setup:

Jenkins: 2.426.2
OS: Linux - 4.14.330-250.540.amzn2.x86_64
Java: 17.0.9 - Eclipse Adoptium (OpenJDK 64-Bit Server VM)

We create our staging and production branches dynamically on a weekly basis and I have a Jenkins pipeline that stores them in Jenkins system variables that other pipelines can then read.

Is there a way to also store these as workspace variables in our Bitbucket Cloud instance? For example, I want to have STAGING_BRANCH and PRODUCTION_BRANCH workspace variables setup, and when then update them weekly when we create the corresponding branches. Thanks!

Did u try chatGPT :wink:

pipeline {
    agent any
    environment {
        BITBUCKET_WORKSPACE = 'your-workspace'
        BITBUCKET_REPO_SLUG = 'your-repo'
        BITBUCKET_API_TOKEN = credentials('bitbucket-api-token')
        STAGING_BRANCH = 'your-staging-branch'
        PRODUCTION_BRANCH = 'your-production-branch'
    }
    stages {
        stage('Update Bitbucket Workspace Variables') {
            steps {
                script {
                    def updateBitbucketVariable = { variableName, variableValue ->
                        sh """
                        curl -X PUT -H "Authorization: Bearer ${BITBUCKET_API_TOKEN}" \
                             -H "Content-Type: application/json" \
                             https://api.bitbucket.org/2.0/repositories/${BITBUCKET_WORKSPACE}/${BITBUCKET_REPO_SLUG}/pipelines_config/variables/ \
                             -d '{
                                  "key": "${variableName}",
                                  "value": "${variableValue}",
                                  "secured": false
                             }'
                        """
                    }
                    updateBitbucketVariable('STAGING_BRANCH', STAGING_BRANCH)
                    updateBitbucketVariable('PRODUCTION_BRANCH', PRODUCTION_BRANCH)
                }
            }
        }
    }
}