How to create a git repository inside a pipeline as code

2.9k Views Asked by At

I am attempting to move a declarative pipeline from being written in a Jenkins Pipeline Configuration input box, to code hosted in BitBucket so that we have source control for any changes we make to this pipeline.

Due to the pipeline as code steps being written in a Jenkinsfile in a git repository, when I try to initialise a git repository to add my generated files to, I get an error:

+ git remote add origin [email protected]:X/Y.git
fatal: remote origin already exists.

Is there any way to handle this properly?

Edit:

            sh "git init"
            sh "git add ."
            sh "git commit -m \"Initial commit\""
            sh "git remote rm origin"
            sh "git remote add origin [email protected]:X/Y.git"
            sh "git remote -v"
            sh "git push origin master"
            sh "cat .git/config"
2

There are 2 best solutions below

1
On

So the error states that theres already a remote with the same name. And sensibly you cant add that twice. A couple of options:

  1. update the remote url:
git remote set-url origin [email protected]:X/Y.git
  1. remove and re-add the origin
git remote rm origin
git remote add origin [email protected]:X/Y.git

EDIT

Seems like a duplicate of: Github "fatal: remote origin already exists"

3
On

It's unclear what you're trying to achieve with the init of the git repo. Each time you run your job, the repo would be initialized and pushed. This is hard to do more than once.

Jenkins knows how to run Jenkinsfile that is stored on the repo. You need to manually create your repo, commit the Jenkinsfile there, and then add a new job in Jenkins telling it that the Jenkinsfile should be brought over from the repo. This is called "Pipeline script from SCM". You then should configure the credentials, the path, the branch etc. in Jenkins. Each time you run the job, Jenkins would check out your Jenkinsfile from the repo, and then run it.