Search code examples
gitjenkinsgroovyjenkins-pipelinecicd

Jenkins Pipeline Error: fatal: unable to access repo URL rejected: Port number was not a decimal number between 0 and 65535


I'm facing an issue with my Jenkins pipeline when trying to push changes to a remote Git repository. The error I'm getting is:

fatal: unable to access 'https://example.org/git/usernamerepo/devops-gitops-apps.git/': URL rejected: Port number was not a decimal number between 0 and 65535

Here's the relevant part of my Jenkinsfile:

pipeline {
    agent {
        kubernetes {
            yaml '''
apiVersion: v1
kind: Pod
metadata:
  labels:
    pod-name: jenkins-agent
spec:
  containers:
  - name: git
    image: alpine/git
    command:
    - cat
    tty: true
    env:
    - name: http_proxy
      value: proxyvalue
    - name: https_proxy
      value: proxyvalue
    - name: no_proxy
      value: somevalues,othersvalue
    volumeMounts:
    - name: yq-bin
      mountPath: /yq-bin
    resources:
      requests:
        memory: "256Mi"
        cpu: "0.25"
  - name: jnlp
    image: jenkins/inbound-agent:latest
    args: ['$(JENKINS_SECRET)', '$(JENKINS_NAME)']
  initContainers:
  - name: yq
    image: mikefarah/yq:4.43.1
    command: ["sh", "-c", "cp /usr/bin/yq /yq-bin/yq"]
    volumeMounts:
    - name: yq-bin
      mountPath: /yq-bin
  volumes:
  - name: yq-bin
    emptyDir: {}
            '''
        }
    }

    environment {
        HELM_HOME = "/usr/local/bin/helm"
        VALUES_FILE = "jenkins/values.yaml"
        GIT_REPO = "https://example.org/git/usernamerepo/devops-gitops-apps.git"
        GIT_BRANCH = "master"
        NEW_BRANCH = "jenkins-update"
        GIT_CREDENTIALS_ID = "giteaAccess" 
    }

    stages {
        stage('Checkout') {
            steps {
                container('git') {
                    git branch: "${env.GIT_BRANCH}", url: "${env.GIT_REPO}", credentialsId: "${env.GIT_CREDENTIALS_ID}"
                }
            }
        }

        stage('Debug YQ Path') {
            steps {
                container('git') {
                    script {
                        sh 'ls -l /yq-bin'
                        sh '/yq-bin/yq --version'
                    }
                }
            }
        }

        stage('Read Plugins') {
            steps {
                container('git') {
                    script {
                        def plugins = sh(script: "/yq-bin/yq e '.controller.installPlugins[]' ${env.VALUES_FILE}", returnStdout: true).trim().split("\n")
                        env.PLUGINS = plugins.join(" ")
                    }
                }
            }
        }

        stage('Update Plugins') {
            steps {
                container('git') {
                    script {
                        def pluginsList = env.PLUGINS.tokenize()
                        sh "sed -i '/installPlugins:/,\$d' ${env.VALUES_FILE}"
                        sh "echo 'controller:' >> ${env.VALUES_FILE}"
                        sh "echo '  installPlugins:' >> ${env.VALUES_FILE}"
                        pluginsList.each { plugin ->
                            sh "echo '    - ${plugin}' >> ${env.VALUES_FILE}"
                        }
                    }
                }
            }
        }

        stage('Configure Git Safe Directory') {
            steps {
                container('git') {
                    script {
                        sh "git config --global --add safe.directory /home/jenkins/agent/workspace/jenkinsupdater"
                    }
                }
            }
        }

        stage('Commit Changes') {
            steps {
                container('git') {
                    script {
                        withCredentials([usernamePassword(credentialsId: "${env.GIT_CREDENTIALS_ID}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
                            sh "git checkout -b ${env.NEW_BRANCH}"
                            sh 'git config user.email "[email protected]"'
                            sh 'git config user.name "${USERNAME}"'
                            sh 'git add ${VALUES_FILE}'
                            sh 'git commit -m "Automated update of Jenkins plugins"'
                            sh '''
                            git remote set-url origin https://${USERNAME}:${PASSWORD}@example.org/git/usernamerepo/devops-gitops-apps.git
                            git push -u origin ${NEW_BRANCH}
                            '''
                        }
                    }
                }
            }
        }

        stage('Create Pull Request') {
            steps {
                container('git') {
                    script {
                        withCredentials([usernamePassword(credentialsId: "${env.GIT_CREDENTIALS_ID}", usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD')]) {
                            sh """
                            curl -X POST -H "Content-Type: application/json" -u ${USERNAME}:${PASSWORD} \
                            -d '{
                                  "title": "Automated update of Jenkins plugins",
                                  "body": "This PR includes automated updates of Jenkins plugins",
                                  "head": "${NEW_BRANCH}",
                                  "base": "master"
                                }' \
                            https://example.org/git/usernamerepo/devops-gitops-apps/pulls
                            """
                        }
                    }
                }
            }
        }
    }

    post {
        always {
            echo "Cleaning up and finalizing pipeline."
            cleanWs()
        }
    }
}

I'm using Jenkins Kubernetes agents to run this pipeline. The pipeline checks out the repository, updates a values.yaml file with a list of Jenkins plugins, commits the changes, pushes a new branch to the remote repository, and creates a pull request.

I've tried to avoid directly embedding credentials into the URL to prevent security issues. The credentials are managed using Jenkins' withCredentials block.

Despite this, I still encounter the error related to the URL and port number. What could be causing this issue, and how can I resolve it?

Things I've checked/tried:

  • Ensuring credentials are correctly handled by withCredentials.
  • Using different ways to set the remote URL and push the changes.
  • Checking the proxy configuration.

Any suggestions or insights would be greatly appreciated!

Create a pull request to update plugins from gitops repo


Solution

  • If your USERNAME environment variable contains @ character then that would explain the error. http://[email protected]:[email protected]/git/usernamerepo/devops-gitops-apps.git would result in bob being treated as a user name, gmail.com as a host name, and :Pasw00rd as a port number that is "not a decimal".

    Any special characters in both the user name and the password would need to be url-encoded. Or avoided.

    To bypass this problem entirely you could use the gitUsernamePassword parameter:

    withCredentials([gitUsernamePassword(credentialsId: "${env.GIT_CREDENTIALS_ID}",
                     gitToolName: 'Default')]) {
      sh 'git fetch --all'
    }