semural
semural

Reputation: 4611

Jenkins replace image tag in yaml file that stored in another repository

I've two different repo for app and manifests.In manifest repo I've values.yaml files for each microservices. I am looking for a way to update image.tag value with ${BUILD_NUMBER} and then commit/merge this changes to manifest repository from the app pipeline as below.

What is the best way of doing this ?

image:
  repository: example.com/app/backend
  tag: "450"
  pullPolicy: Always

Here is the stage in jenkinsfile for app repo.

stage('Deploy to DEV') {
    when{
        beforeAgent true
        expression{return env.GIT_BRANCH == "origin/development"}
    }
    steps {
        script {
            sh """
                git clone https://github.com/mycompany/backend.git
                cd apps/project1/app-dev/backend-dev
                
                def text = readFile file: "values.yaml"
                text = text.replaceAll("%tag%", "${${BUILD_NUMBER}}") 

                git add . -m "Update app image tag to ${BUILD_NUMBER}"
                git push origin master
            """
        }
    }

Upvotes: 0

Views: 2700

Answers (1)

Altaf
Altaf

Reputation: 3076

With the solution you have your values.yaml would be replaced with the contents and everytime time this file would be seen as changed.
As another solution could be: Handle environmental variables in yaml file and export the value via jenkinsfile.
You can add an environmental variable ${ENVIRONMENT_VARIABLE} in the values.yaml file in the tags section.
Example in this could be : ${BUILD_NUMBER}
You can then pass the value of this environmental variable via jenkins pipeline.
export ENV_VAR_NAME=env_var_value
export BUILD_NUMBER=${BUILD_NUMBER}

                sh """
                git clone https://github.com/mycompany/backend.git
                cd apps/project1/app-dev/backend-dev
                
                # def text = readFile file: "values.yaml"
                # text = text.replaceAll("%tag%", "${${BUILD_NUMBER}}") 
                export BUILD_NUMBER=${BUILD_NUMBER}
                git add . -m "Update app image tag to ${BUILD_NUMBER}"
                git push origin master
            """

More info on using environmental variables in yaml file: https://docs.greatexpectations.io/en/0.11.6/how_to_guides/configuring_data_contexts/how_to_use_a_yaml_file_or_environment_variables_to_populate_credentials.html

Upvotes: 1

Related Questions