Best practices for integrating the ROS Jenkins plugin with Git

Updated at:

Integrate the Alibaba Cloud ROS Plugin for Jenkins with a Git repository to build a code-change-driven infrastructure deployment pipeline with version-controlled ROS templates and multi-environment isolation.

Use cases

ROS templates and parameter files stored in a Git repository benefit from version control, but infrastructure must be updated whenever they change. Manual console deployments are inefficient and error-prone, risking outages from missed steps or environment confusion. Development and production parameter configurations must be strictly isolated, and credentials such as your Alibaba Cloud AccessKey must never appear in plain text in your repository or build logs.

A Jenkins pipeline monitors your Git repository, automatically reads the correct ROS template and parameter file for the target environment, and calls the Alibaba Cloud ROS Plugin to create or update a stack. Credentials are stored securely in the Jenkins Credential Store, so no sensitive information is exposed. After code is merged, infrastructure changes are applied within minutes without manual intervention.

Solution architecture

整体架构图

Jenkins periodically polls the Git repository using pollSCM('H/5 * * * *'), or you can configure a GitHub webhook for real-time triggers. When Jenkins detects a new commit, it starts the build pipeline automatically. Your Git SSH key is stored in the Jenkins Credential Store, managed separately from other credentials.

Separate parameter files such as parameters/dev.json isolate configuration for each environment, ensuring that development parameters stay within their permitted scope. The pipeline first calls CreateRosStack to create a stack. If the stack already exists, it automatically switches to UpdateRosStack for an incremental update.

All ROS operations reference the pre-configured Alibaba Cloud credential in Jenkins through the credentialsId parameter, preventing your AccessKey from appearing in pipeline scripts or build logs.

Procedure

Step 1: Organize Git repository and ROS templates

Before you begin, install and configure the ROS Jenkins plugin. For more information, see ROS Jenkins plugin overview.

Organize your repository with separate directories for templates and parameters:

my-project/
├── templates/             # ROS template directory
│   └── vpc-template.json  # Infrastructure definition
├── parameters/            # Environment parameter isolation
│   ├── dev.json           # Development environment parameters
│   └── prod.json          # Production environment parameters (strict access control)
└── Jenkinsfile  

The templates/*.json files must include the ROSTemplateFormatVersion field. Do not hard-code environment variables in the template. Instead, inject all environment-specific values through parameters. The parameters/*.json files contain an array of parameter objects, each with a ParameterKey and a ParameterValue, and should not store sensitive information like passwords.

ROS template file

The templates/vpc-template.json file defines a basic network infrastructure including a VPC, a vSwitch, and a security group. The template receives external input through the Parameters section. The Fn::Sub function appends an environment identifier to resource names so that resources in different environments do not conflict:

{
  "ROSTemplateFormatVersion": "2015-09-01",
  "Description": {
    "en": "ROS Template: Creating a VPC.",
    "zh-cn": "ROS模板:创建VPC。"
  },
  "Parameters": {
    "Environment": {
      "Type": "String",
      "Default": "development",
      "AllowedValues": [
        "development",
        "staging",
        "production"
      ],
      "Description": {
        "en": "Environment Type",
        "zh-cn": "环境类型"
      }
    },
    "VpcName": {
      "Type": "String",
      "Default": "my-vpc",
      "Description": {
        "en": "Vpc Name",
        "zh-cn": "VPC名称"
      }
    },
    "CidrBlock": {
      "Type": "String",
      "Default": "192.168.0.0/16",
      "Description": {
        "en": "Cidr Block",
        "zh-cn": "VPC CIDR块"
      }
    }
  },
  "Resources": {
    "VPC": {
      "Type": "ALIYUN::ECS::VPC",
      "Properties": {
        "CidrBlock": {
          "Ref": "CidrBlock"
        },
        "VpcName": {
          "Fn::Sub": "${VpcName}-${Environment}"
        },
        "Description": "VPC for ${Environment} environment"
      }
    },
    "VSwitch": {
      "Type": "ALIYUN::ECS::VSwitch",
      "Properties": {
        "VpcId": {
          "Ref": "VPC"
        },
        "CidrBlock": "192.168.1.0/24",
        "ZoneId": {
          "Fn::Select": [
            0,
            {
              "Fn::GetAZs": {
                "Ref": "ALIYUN::Region"
              }
            }
          ]
        },
        "VSwitchName": {
          "Fn::Sub": "vswitch-${Environment}"
        }
      }
    },
    "SecurityGroup": {
      "Type": "ALIYUN::ECS::SecurityGroup",
      "Properties": {
        "VpcId": {
          "Ref": "VPC"
        },
        "SecurityGroupName": {
          "Fn::Sub": "sg-${Environment}"
        },
        "Description": "Security group for ${Environment} environment"
      }
    }
  },
  "Outputs": {
    "VpcId": {
      "Value": {
        "Ref": "VPC"
      },
      "Description": {
        "en": "VPC ID.",
        "zh-cn": "创建的VPC ID。"
      }
    }
  }
}

Environment parameter file

The parameters/dev.json file defines the VPC name, CIDR block, and environment identifier for the development environment:

[
  {
    "ParameterKey": "VpcName",
    "ParameterValue": "dev-name"
  },
  {
    "ParameterKey": "CidrBlock",
    "ParameterValue": "192.168.0.0/16"
  },
  {
    "ParameterKey": "Environment",
    "ParameterValue": "development"
  }
]

Step 2: Configure Jenkins credentials and the pipeline

Configure credentials before creating the pipeline. The pipeline script references credentials by ID, preventing sensitive information from being exposed in your code.

Configure security credentials

Configure two credentials in Jenkins > System Administration > Credentials > System > Global Credentials. For the Git credential, select SSH Username with private key and set the ID to git-credentials. This credential allows Jenkins to pull code from your Git repository. For the Alibaba Cloud credential, select Alibaba Cloud Credentials and set the ID to aliyun-ak-creds. The ROS plugin uses this credential to call Alibaba Cloud APIs.

Create a pipeline task

  1. In the Jenkins console, click New Item, enter a name for the task, select the Pipeline type, and click OK.

  1. In the Pipeline configuration section, configure the Git source code management. The credentialsId references the Git credential that you created in the previous step:

checkout([
    $class: 'GitSCM',
    branches: [[name: "${params.BRANCH}"]],
    userRemoteConfigs: [[
        url: 'https://github.com/your-org/my-project.git',  // [Modify] Replace with your actual repository URL
        credentialsId: 'git-creds'  // [Required] Use the Jenkins credential ID
    ]]
])

Configure the pipeline script

In the Pipeline section, enter the pipeline script and click Save:

pipeline {
    agent any

    parameters {
        string(name: 'BRANCH', defaultValue: 'master', description: 'The branch to build')
        string(name: 'CREDENTIALS_ID', defaultValue: 'aliyun-ak-creds', description: 'ros ak')
        string(name: 'REGION_ID', defaultValue: 'cn-shenzhen', description: 'stack region')
        string(name: 'STACK_NAME', defaultValue: 'my-jenkins-stack', description: 'stack name')
        booleanParam(name: 'PERFORM_DEPLOY', defaultValue: false, description: 'Check if you want to deploy')
    }

    triggers {
        pollSCM('H/5 * * * *') // Check the Git repository for changes every 5 minutes.
    }

    stages {

        stage('① Checkout: Pull code') {
            steps {
                checkout([
                    $class: 'GitSCM',
                    branches: [[name: "${params.BRANCH}"]],
                    userRemoteConfigs: [[
                        url: 'https://github.com/your-org/my-project.git', // <-- [Modify] Replace with your actual repository URL
                        credentialsId: 'git-credentials' // <-- [Confirm] Use the configured Git credential ID
                    ]]
                ])
                sh 'echo "Code pulled from branch $BRANCH."'
            }
        }
        stage('Build') {
            steps {
                echo 'Building the application...'
            }
        }

        stage('Deploy with ROS') {
            steps {
                script {
                    def templatePath = "${WORKSPACE}/templates/vpc-template.json"
                    def templateContent = readFile(templatePath)
                    def paramsFile = "${WORKSPACE}/parameters/${env.ENVIRONMENT ?: 'dev'}.json"
                    def tplParams = readFile(paramsFile)
                    
                    echo "Using template: ${templatePath}"

                    try {
                        def stackId = CreateRosStack(
                            stackName: "${params.STACK_NAME}",
                            regionId: "${params.REGION_ID}",
                            credentialsId: "${params.CREDENTIALS_ID}",
                            parameters: tplParams,
                            templateBody: templateContent
                        )
                        echo "Created stack with ID: ${stackId}"
                        env.STACK_ID = stackId
                    } catch (Exception e) {
                        echo "Stack already exists, will attempt to update it."
                        if (e.getMessage().contains("already exists")) {
                            def stacks = ListRosStacks(
                                stackName: ["${params.STACK_NAME}"],
                                regionId: "${params.REGION_ID}",
                                credentialsId: "${params.CREDENTIALS_ID}"
                            )
                            echo "stacks: ${stacks}"
                            if (stacks && stacks.TotalCount > 0) {
                                def stackId = stacks.Stacks[0].StackId
                                try {
                                    echo "Stack ${stackId} already exists, will attempt to update it."
                                    UpdateRosStack(
                                        stackId: stackId,
                                        regionId: "${params.REGION_ID}",
                                        credentialsId: "${params.CREDENTIALS_ID}",
                                        parameters: tplParams,
                                        templateBody: templateContent
                                    )
                                    env.STACK_ID = stackId
                                } catch (Exception ex) {
                                    echo ex.getMessage()
                                }
                            }
                        } else {
                            echo "An unexpected error occurred: ${e.getMessage()}"
                            currentBuild.result = 'FAILURE'
                            throw e
                        }
                    }
                }
            }
        }

        stage('Test') {
            steps {
                echo 'Running tests...'
            }
        }
        stage('Deploy') {
            steps {
                echo 'Deploying the application...'
            }
        }
    }

    post {
        always {
            echo 'Pipeline finished.'
        }
        success {
            echo 'Pipeline succeeded!'
        }
        failure {
            echo 'Pipeline failed!'
        }
    }
}

The core logic resides in the Deploy with ROS stage. The pollSCM trigger polls the Git repository every 5 minutes. When a new commit is detected, the pipeline pulls the latest code, reads the ROS template from templates/ and the corresponding environment parameter file from parameters/. The deployment stage first calls CreateRosStack. If an "already exists" exception is caught, it queries for the existing stack ID using ListRosStacks and then calls UpdateRosStack. This create-first, update-on-failure pattern handles both initial deployments and subsequent changes automatically.

Step 3: Verify the initial deployment

  1. On the Jenkins task page, click Build with Parameters to manually trigger a build.

  2. Check the build log and confirm that the output is similar to the following.

[Deploy ROS] Created stack with ID: 4ee9****-****-****-****-************
[Post-build] ✅ dev environment deployed successfully! Stack: 4ee9****-****-****-****-************
  1. In the ROS console, confirm that the stack status is CREATE_COMPLETE.

Step 4: Verify automatic deployment on Git changes

Modify the parameter file and push the changes to verify that Jenkins automatically detects the changes and updates the stack.

Commit parameter changes

  1. Modify the parameters/dev.json file to change the value of the VpcName parameter to dev-new-name:

[
  {
    "ParameterKey": "VpcName",
    "ParameterValue": "dev-new-name"
  },
  {
    "ParameterKey": "CidrBlock",
    "ParameterValue": "192.168.0.0/16"
  },
  {
    "ParameterKey": "Environment",
    "ParameterValue": "development"
  }
]
  1. Commit the changes and push them to the remote repository.

git add parameters/dev.json
git commit -m "Update VpcName to dev-new-name"
git push origin master

Confirm deployment results

Jenkins polls the Git repository every 5 minutes and automatically triggers a build when it detects a commit. The pipeline pulls the latest code, reads the updated parameter file, and calls UpdateRosStack to update the stack. The process typically completes within two minutes, and the stack status changes from UPDATE_IN_PROGRESS to UPDATE_COMPLETE.

In the ROS console, view the stack events to confirm that the VpcName of the VPC has been updated to dev-new-name-development (the Fn::Sub function in the template automatically appends the environment suffix). You can also search for will attempt to update it in the Jenkins build log to confirm that the update was triggered.