How to deal with merge conflicts in rails ENCRYPTED credential files - ruby-on-rails

With rails 6 (or 5.2) encrypted credentials, I am running into difficulty managing and resolving merge conflicts in the credentials.yml.enc file. As is outlined in the documentation, the intention is that encrypted credentials can be added to source control (https://guides.rubyonrails.org/security.html#custom-credentials)
E.g.
branch_a adds credentials for service a and gets merged to master
branch_b adds credentials for service b and when rebasing, the conflict in the credentials.yml.enc file looks something like this:
<<<<<<< HEAD
sahdkajshdkajhsdkjahsdkjahsdkajhsdkjahsdkjahdskjahsdjkahsdencryptedstring-a09dpjmcas==
=======
laskdjalksjdlakjsdlaksjdlakjsdlaksjdlakjsdlajsdlkajsdlkjasdljalsdajsdencryptedstringrere=
>>>>>>> branch_b
I can view the unencrypted credentials.yml.enc on each branch and resolve conflicts quite manually but is there a better way to go about managing credentials generally in order to avoid these credential conflicts.

I don't believe there is a better way, no.
Because of the nature of the encryption, there is no way to resolve it in it's encrypted state. If that was possible it would imply that you can somehow know the values and keys of the file in the encrypted state.
When you do your merge, you should resolve any conflicts in the source file, and then rerun the command that generates the encrypted file, then complete your merge.

It is possible. From the rails credentials usage:
=== Set up Git to Diff Credentials
Rails provides `rails credentials:diff --enroll` to instruct Git to call `rails credentials:diff`
when `git diff` is run on a credentials file.
Running the command enrolls the project such that all credentials files use the
"rails_credentials" diff driver in .gitattributes.
Additionally since Git requires the driver itself to be set up in a config file
that isn't tracked Rails automatically ensures it's configured when running
`credentials:edit`.
Otherwise each co-worker would have to run enable manually, including on each new
repo clone.

If you don't have rails credentials:diff...
It is possible to merge them, but you will have to decrypt them.
When dealing with merge conflicts, you can run git mergetool and it should generate 4 files:
config/credentials.yml_BACKUP_84723.enc
config/credentials.yml_LOCAL_84723.enc
config/credentials.yml_BASE_84723.enc
config/credentials.yml_LOCAL_84723.enc
You may need to run git mergetool in one terminal window, and in another, run this script:
Note that this will expose your credentials on the local machine.
# Temporarily move credentials file to another location
mv config/credentials.yml.enc ~/Desktop/credentials_temp.yml.enc
# Copy local file to original location
cp config/credentials.yml_LOCAL_* config/credentials.yml.enc
# Decrypt and send decrypted credentials to desktop
rails credentials:show > ~/Desktop/credentials_local.yaml
# Delete the copied local file
rm config/credentials.yml.enc
# Copy remote file to original location
cp config/credentials.yml_REMOTE_* config/credentials.yml.enc
# Decrypt and send decrypted credentials to desktop
rails credentials:show > ~/Desktop/credentials_remote.yaml
# Delete the copied remote file
rm config/credentials.yml.enc
# Move credentials file back
mv ~/Desktop/credentials_temp.yml.enc config/credentials.yml.enc
# See diffs or open both
diff ~/Desktop/credentials_local.yaml ~/Desktop/credentials_remote.yaml
# Delete the decrypted files
rm ~/Desktop/credentials_local.yaml ~/Desktop/credentials_remote.yaml
Local is on the left. Remote is on the right.
Enjoy.

Generally it is recommended to ignore credentials in version control i.e. .gitignore and configure them via environment variable.

Related

How to set up 1-way sync from Bitbucket Cloud to a local folder

This might sound like a stupid question, and the use-case is rather simple, but I haven't been able to find a decent and simple solution.
In short:
I have a Bitbucket repo that I want to have synced to a local folder on my local server.
So whenever there's an upstream change, the most updated version of the file must be copied to the local folder. There is never a push/commit from local-to-cloud, it's merely a 1-way read-only sync.
Thanks in advance for any suggestions! (maybe the solution is so obvious that I don't see it?)
You don't explain what software is running on your local server, but assuming this is some flavor of UNIX/Linux/macOS and you have crontab access, the easiest thing is probably to just schedule a cron job to pull updates.
A command like the following will schedule a git update every 60 seconds, logging the output to a file:
echo '* * * * * cd $HOME/path/to/git/workdir && git pull -q --ff-only >> update-log 2>&1' | crontab
Note 1: This assumes your user currently has an empty crontab on the server, if you don't then you should instead use crontab -e to manually append the directive to your existing crontab.
Note 2: You'll need to ensure your account on the server has permission to access the BitBucket repo without a tty connection (e.g. without SSH agent forwarding), so you might need to fiddle with authentication to set that up (which is beyond the scope of this answer). For a public BitBucket repo, cloning via HTTPS without a user name is probably the simplest approach, since no authentication is required.
Note 3: The first * in the directive above can be adjusted to select a different polling frequency, e.g. 0,15,30,45 for every 15 minutes. If you omit the 2>&1 then you should get an email for any errors (assuming SMTP is configured on the server).
Note 4: The git command embedded above assumes you never rewrite history in the upstream git repo or manually modify the local directory. If either is a possibility, then you might instead want to use git pull -q --rebase or even git fetch && git reset --hard '#{upstream}'

How to properly build a private Go project? [duplicate]

I'm searching for the way to get $ go get work with private repository, after many google try.
The first try:
$ go get -v gitlab.com/secmask/awserver-go
Fetching https://gitlab.com/secmask/awserver-go?go-get=1
https fetch failed.
Fetching http://gitlab.com/secmask/awserver-go?go-get=1
Parsing meta tags from http://gitlab.com/secmask/awserver-go?go-get=1 (status code 200)
import "gitlab.com/secmask/awserver-go": parse http://gitlab.com/secmask/awserver-go?go-get=1: no go-import meta tags
package gitlab.com/secmask/awserver-go: unrecognized import path "gitlab.com/secmask/awserver-go
Yep, it did not see the meta tags because I could not know how to provide login information.
The second try:
Follow https://gist.github.com/shurcooL/6927554. Add config to .gitconfig.
[url "ssh://git#gitlab.com/"]
insteadOf = https://gitlab.com/
$ go get -v gitlab.com/secmask/awserver-go --> not work
$ go get -v gitlab.com/secmask/awserver-go.git --> work but I got src/gitlab.com/secmask/awserer-go.git
Yes it work but with .git extension with my project name, I can rename it to original but do it everytime $ go get is not so good, is there an otherway?
You have one thing to configure. The example is based on GitHub but this shouldn't change the process:
$ git config --global url.git#github.com:.insteadOf https://github.com/
$ cat ~/.gitconfig
[url "git#github.com:"]
insteadOf = https://github.com/
$ go get github.com/private/repo
For Go modules to work (with Go 1.11 or newer), you'll also need to set the GOPRIVATE variable, to avoid using the public servers to fetch the code:
export GOPRIVATE=github.com/private/repo
The proper way is to manually put the repository in the right place. Once the repository is there, you can use go get -u to update the package and go install to install it. A package named
github.com/secmask/awserver-go
goes into
$GOPATH/src/github.com/secmask/awserver-go
The commands you type are:
cd $GOPATH/src/github.com/secmask
git clone git#github.com:secmask/awserver-go.git
I had a problem with go get using private repository on gitlab from our company.
I lost a few minutes trying to find a solution. And I did find this one:
You need to get a private token at:
https://gitlab.mycompany.com/profile/account
Configure you git to add extra header with your private token:
$ git config --global http.extraheader "PRIVATE-TOKEN: YOUR_PRIVATE_TOKEN"
Configure your git to convert requests from http to ssh:
$ git config --global url."git#gitlab.mycompany.com:".insteadOf "https://gitlab.mycompany.com/"
Finally you can use your go get normally:
$ go get gitlab.com/company/private_repo
For people using private GitLabs, here's a snippet that may help: https://gist.github.com/MicahParks/1ba2b19c39d1e5fccc3e892837b10e21
Also pasted below:
Problem
The go command line tool needs to be able to fetch dependencies from your private GitLab, but authenticaiton is required.
This assumes your private GitLab is hosted at privategitlab.company.com.
Environment variables
The following environment variables are recommended:
export GO111MODULE=on
export GOPRIVATE=privategitlab.company.com # this is comma delimited if using multiple private repos
The above lines might fit best in your shell startup, like a ~/.bashrc.
Explanation
GO111MODULE=on tells Golang command line tools you are using modules. I have not tested this with projects not using
Golang modules on a private GitLab.
GOPRIVATE=privategitlab.company.com tells Golang command line tools to not use public internet resources for the hostnames
listed (like the public module proxy).
Get a personal access token from your private GitLab
To future proof these instructions, please follow this guide from the GitLab docs.
I know that the read_api scope is required for Golang command line tools to work, and I may suspect read_repository as
well, but have not confirmed this.
Set up the ~/.netrc
In order for the Golang command line tools to authenticate to GitLab, a ~/.netrc file is best to use.
To create the file if it does not exist, run the following commands:
touch ~/.netrc
chmod 600 ~/.netrc
Now edit the contents of the file to match the following:
machine privategitlab.company.com login USERNAME_HERE password TOKEN_HERE
Where USERNAME_HERE is replaced with your GitLab username and TOKEN_HERE is replaced with the access token aquired in the
previous section.
Common mistakes
Do not set up a global git configuration with something along the lines of this:
git config --global url."git#privategitlab.company.com:".insteadOf "https://privategitlab.company.com"
I beleive at the time of writing this, the SSH git is not fully supported by Golang command line tools and this may cause
conflicts with the ~/.netrc.
Bonus: SSH config file
For regular use of the git tool, not the Golang command line tools, it's convient to have a ~/.ssh/config file set up.
In order to do this, run the following commands:
mkdir ~/.ssh
chmod 700 ~/.ssh
touch ~/.ssh/config
chmod 600 ~/.ssh/config
Please note the permissions on the files and directory above are essentail for SSH to work in it's default configuration on
most Linux systems.
Then, edit the ~/.ssh/config file to match the following:
Host privategitlab.company.com
Hostname privategitlab.company.com
User USERNAME_HERE
IdentityFile ~/.ssh/id_rsa
Please note the spacing in the above file matters and will invalidate the file if it is incorrect.
Where USERNAME_HERE is your GitLab username and ~/.ssh/id_rsa is the path to your SSH private key in your file system.
You've already uploaded its public key to GitLab. Here are some instructions.
All of the above did not work for me. Cloning the repo was working correctly but I was still getting an unrecognized import error.
As it stands for Go v1.13, I found in the doc that we should use the GOPRIVATE env variable like so:
$ GOPRIVATE=github.com/ORGANISATION_OR_USER_NAME go get -u github.com/ORGANISATION_OR_USER_NAME/REPO_NAME
Generate a github oauth token here and export your github token as an environment variable:
export GITHUB_TOKEN=123
Set git config to use the basic auth url:
git config --global url."https://$GITHUB_TOKEN:x-oauth-basic#github.com/".insteadOf "https://github.com/"
Now you can go get your private repo.
If you've already got git using SSH, this answer by Ammar Bandukwala is a simple workaround:
$ go get uses git internally. The following one liners will make git and consequently $ go get clone your package via SSH.
Github:
$ git config --global url."git#github.com:".insteadOf "https://github.com/"
BitBucket:
$ git config --global url."git#bitbucket.org:".insteadOf "https://bitbucket.org/"
I came across .netrc and found it relevant to this.
Create a file ~/.netrc with the following content:
machine github.com
login <github username>
password <github password or Personal access tokens >
Done!
Additionally, for latest GO versions, you might need to add this to the environment variables GOPRIVATE=github.com
(I've added it to my .zshrc)
netrc also makes my development environment setup better as my personal github access for HTTPS is been configured now to be used across the machine (just like my SSH configuration).
Generate GitHub personal access tokens: https://github.com/settings/tokens
See this answer for its use with Git on Windows specifically
Ref: netrc man page
If you want to stick with the SSH authentication, then mask the request to use ssh forcefully
git config --global url."git#github.com:".insteadOf "https://github.com/"
More methods for setting up git access: https://gist.github.com/technoweenie/1072829#gistcomment-2979908
That looks like the GitLab issue 5769.
In GitLab, since the repositories always end in .git, I must specify .git at the end of the repository name to make it work, for example:
import "example.org/myuser/mygorepo.git"
And:
$ go get example.org/myuser/mygorepo.git
Looks like GitHub solves this by appending ".git".
It is supposed to be resolved in “Added support for Go's repository retrieval. #5958”, provided the right meta tags are in place.
Although there is still an issue for Go itself: “cmd/go: go get cannot discover meta tag in HTML5 documents”.
After trying multiple solutions my problem still persisted. The final solution after setting up the ~/.netrc and SSH config file, was to add the following line to my ~/.bash_profile
export GOPRIVATE="github.com/[organization]"
I have created a user specific ssh-config, so my user automatically logs in with the correct credentials and key.
First I needed to generate an key-pair
ssh-keygen -t rsa -b 4096 -C "my#email.here"
and saved it to e.g ~/.ssh/id_my_domain. Note that this is also the keypair (private and public) I've connected to my Github account, so mine is stored in~/.ssh/id_github_com.
I have then created (or altered) a file called ~/.ssh/config with an entry:
Host github.com
HostName github.com
User git
IdentityFile ~/.ssh/id_github_com
On another server, the "ssh-url" is admin#domain.com:username/private-repo.git and the entry for this server would have been:
Host domain.com
HostName domain.com
User admin
IdentityFile ~/.ssh/id_domain_com
Just to clarify that you need ensure that the User, Host and HostName is set correctly.
Now I can just browse into the go path and then go get <package>, e.g go get main where the file main/main.go includes the package (from last example above) domain.com:username/private-repo.git.
For me, the solutions offered by others still gave the following error during go get
git#gl.nimi24.com: Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
What this solution required
As stated by others:
git config --global url."git#github.com:".insteadOf "https://github.com/"
Removing the passphrase from my ./ssh/id_rsa key which was used for authenticating the connection to the repository. This can be done by entering an empty password when prompted as a response to:
ssh-keygen -p
Why this works
This is not a pretty workaround as it is always better to have a passphrase on your private key, but it was causing issues somewhere inside OpenSSH.
go get uses internally git, which uses openssh to open the connection. OpenSSH takes the certs necessary for authentication from .ssh/id_rsa. When executing git commands from the command line an agent can take care of opening the id_rsa file for you so that you do not have to specify the passphrase every time, but when executed in the belly of go get, this did not work somewhy in my case. OpenSSH wants to prompt you then for a password but since it is not possible due to how it was called, it prints to its debug log:
read_passphrase: can't open /dev/tty: No such device or address
And just fails. If you remove the passphrase from the key file, OpenSSH will get to your key without that prompt and it works
This might be caused by Go fetching modules concurrently and opening multiple SSH connections to Github at the same time (as described in this article). This is somewhat supported by the fact that OpenSSH debug log showed the initial connection to the repository succeed, but later tried it again for some reason and this time opted to ask for a passphrase.
However the solution of using SSH connection multiplexing as put forward in the mentioned article did not work for me. For the record, the author suggested adding the collowing conf to the ssh config file for the affected host:
ControlMaster auto
ControlPersist 3600
ControlPath ~/.ssh/%r#%h:%p
But as stated, for me it did not work, maybe I did it wrong
After setting up GOPRIVATE and git config ...
People may still meeting problems like this when fetching private source:
https fetch: Get "https://private/user/repo?go-get=1": EOF
They can't use private repo without .git extension.
The reason is the go tool has no idea about the VCS protocol of this repo, git or svn or any other, unlike github.com or golang.org them are hardcoded into go's source.
Then the go tool will do a https query before fetching your private repo:
https://private/user/repo?go-get=1
If your private repo has no support for https request, please use replace to tell it directly :
require private/user/repo v1.0.0
...
replace private/user/repo => private.server/user/repo.git v1.0.0
https://golang.org/cmd/go/#hdr-Remote_import_paths
first I tried
[url "ssh://git#github.com/"]
insteadOf = https://github.com/
but it didn't worked for my local.
I tried
ssh -t git#github.com
and it shows my ssh is fine.
finally, I fix the problem to tell the go get to consider all as private and use ssh instead of HTTPS.
adding export GOPRIVATE=*
Make sure you remove your previous gitconfigs, I had the same issue.
Previously I executed gitconfig whose token was expired, when you execute the command next time with new token make sure to delete previous one.
For standalone/final repos, an as a quick fix, why don't just to name the module within the go.mod as a package using your company's domain ... ?
module go.yourcompany.tld/the_repo
go.yourcompany.tld don't even have to exist as a valid (sub)domain...
Also, in the same go.mod you can use replacement block/lines to use private repos previously cloned the same way (within a respective folder cloned also in $GOPATH/src/go.yourcompany.tld) (why do we have to depend too much in GitHub?)
Edit
Needless to say that a private repo usually shall be a private repo, typically a standard git repo, right? With that, why not just to git clone and then go get within the cloned folder?
It's Hard Code In Go Get. Not The Git Reason. So Modify Go Source.
Reason:
repoRootForImportDynamic Will Request: https://....go-get
// RepoRootForImportPath analyzes importPath to determine the
// version control system, and code repository to use.
func RepoRootForImportPath(importPath string, mod ModuleMode, security web.SecurityMode) (*RepoRoot, error) {
rr, err := repoRootFromVCSPaths(importPath, security, vcsPaths)
if err == errUnknownSite {
rr, err = repoRootForImportDynamic(importPath, mod, security)
if err != nil {
err = importErrorf(importPath, "unrecognized import path %q: %v", importPath, err)
}
}
if err != nil {
rr1, err1 := repoRootFromVCSPaths(importPath, security, vcsPathsAfterDynamic)
if err1 == nil {
rr = rr1
err = nil
}
}
So add gitlab domain to vcsPaths will ok.
Download go source code:
vi ./src/cmd/go/internal/vcs/vcs.go
Look for code below:
var vcsPaths = []*vcsPath{
// GitHub
{
pathPrefix: "github.com",
regexp: lazyregexp.New(`^(?P<root>github\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`),
vcs: "git",
repo: "https://{root}",
check: noVCSSuffix,
},
add Code As Follow,XXXX Is Your Domain:
// GitLab
{
pathPrefix: "gitlab.xxxx.com",
regexp: lazyregexp.New(`^(?P<root>gitlab.xxxx\.com/[A-Za-z0-9_.\-]+/[A-Za-z0-9_.\-]+)(/[A-Za-z0-9_.\-]+)*$`),
vcs: "git",
repo: "https://{root}",
check: noVCSSuffix,
},
compile and replace go.

Bitbucket/Github: permission denied public key

when I am trying to clone a rails app repo I have got permission to, I am getting this issue.
Permission denied (publickey).
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.
Even after adding public key by generating one, I am unable to solve this.
Although I am able to clone using he https method but after making changes, the same error comes while I try to push the code.
Please suggest an answer for this.
First, cd into your .ssh directory. Open up the terminal and run:
cd ~/.ssh && ssh-keygen
Second, you need to copy this to your clipboard:
cat id_rsa.pub | pbcopy # On OSX
cat id_rsa.pub | xclip # On Linux
Third, add your newly generated ssh key to your account via the github/bitbucket website (just paste there).
Next, setup your git config:
git config --global user.name 'your_user_name'
git config --global user.email 'your_email'
Finally, restart your command line to make sure the config is reloaded.
Now, you should be able to clone and push from/to your github repository.
For more information on this, see this github page or this bitbucket page.
When attempting to clone, push, or pull over SSH with Git, you may receive one of these messages if Bitbucket couldn't authenticate with the keys that your SSH agent offered.
Here are the most common reasons why you may see these messages:
You used sudo when attempting the connection
You shouldn't use sudo when cloning, pushing, or pulling because the ssh-agent runs on the user level, not the root level.
Your public key isn't loaded into Bitbucket
To check if your public key is loaded into Bitbucket, do the following:
From Bitbucket, choose Personal settings from your avatar in the lower left.
The Account settings page displays.
Click SSH keys.
The SSH keys page shows a list of any existing keys.
If you don't have any keys listed, you can follow our Set up an SSH key documentation to set one up.
Your key isn't loaded into your SSH agent
If your SSH agent doesn't know to offer Bitbucket a key, the connection fails. You may run into this issue if you've recently restarted your system.
You can refer to this Article for more informations:
https://support.atlassian.com/bitbucket-cloud/docs/troubleshoot-ssh-issues/
Check few things.
Is the generated new key is the one your ssh agent using when trying to ssh to server.
(Your ssh agent might be using a different key than the one you generated)
use this to list currently loaded keys by agent.
ssh-add -L
You properly added public key to your repository hosting location.
The keys corresponding to above 1 and 2 should match.
Please see this article: GitHub: Generating SSH Keys. What happens when you run:
ssh -T git#bitbucket.org
?
You may have added the wrong key to authenticate with.
I faced this error when I created another repository in my local. My ssh-keys were already set up and I was trying to push code through vs code.
The issue got resolved when I git push-ed through git bash like I was doing before.
For bit bucket I think I have tried everything with ssh. I have tried the answer from this stackoverflow question as well. But it doesn't work. So finally I just changed the clone command from SSH to HTTPS and it worked. Only then it asked for password for my account.

ruby on rails git permission denied

I am following this guide to set ruby on rails environment on my Mac El Captain.
I followed upto installing homebrew, ruby latest version 2.2.3 with rbenv. Now, I was setting up git.
Followed up first few commands
git config --global color.ui true
git config --global user.name "YOUR NAME"
git config --global user.email "YOUR#EMAIL.com"
ssh-keygen -t rsa -C "YOUR#EMAIL.com"
Now, I have been asked to save the generated key. I saved it to ~ directory with a name file. I have now two files namely file and file.pub.
I went to this link to copy ssh key. I clicked on Add SSH key option there. Named the key ROR SSH Key.
The key in file.pub looks like
ssh-rss asfjasfhjalsfdhaskfdhalsdfsdf\asdf\as\dg\sa\fasdfas\f\asdf---so on random numbers---adfasdfasfa myemail#gmail.com
and I pasted the key there in github and saved the key.
Then, I went back to terminal and typed the below command.
ssh -T git#github.com
but I didn't received any message saying "Hi excid3! You've successfully authenticated, but GitHub does not provide shell access."
I got a message saying
The authenticity of host 'github.com (192.30.251.130)' can't be established.
RSA key fingerprint is SHA256:nThbg6sdfgdfgsdfgGOCspRomTxdCARLviKw6E5SY8.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'github.com,192.30.251.130' (RSA) to the list of known hosts.
Permission denied (publickey).
Here above I have change few characters in SHA256 key. Just for security. Also, I have changed IP address a little bit for the same. But, the idea behind it is same.
Please guide me what's wrong. Thanks.
By default, ssh will look in the ~/.ssh folder for your private keys. Since you saved it in ~ instead, it can't find it.
You can either:
Move the file and file.pub files into ~/.ssh and rename to id_rsa and id_rsa.pub, as OS X will automatically use those files for any ssh command (if you hadn't manually entered a filename, this is where ssh-keygen would have saved them).
Use the ssh-add -K file command to permanently add your key to the OS X Keychain.
Note that GitHub's own instructions say they "strongly suggest keeping the default settings" instead of saving the private/public key somewhere else.

How to export credentials from one jenkins instance to another?

I am using the credentials plugin in Jenkins to manage credentials for git and database access for my team's builds. I would like to copy the credentials from one jenkins instance to another, independent jenkins instance. How would I go about doing this?
UPDATE: TL;DR Follow the link provided below in a comment by Filip Stachowiak it is the easiest way to do it. In case it doesn't work for you go on reading.
Copying the $HUDSON_HOME/credentials.xml is not the solution because Jenkins encrypts paswords and these can't be decrypted by another instance unless both share a common key.
So, either you use the same encription keys in both Jenkins instances (Where's the encryption key stored in Jenkins? ) or what you can do is:
Create the same user/password, you need to share, in the 2nd Jenkins instance so that a valid password is generated
What is really important is that user ids in both credentials.xml are the same. For that (see the credentials.xml example below) for user: Jenkins the identifier <id>c4855f57-5107-4b69-97fd-298e56a9977d</id> must be the same in both credentials.xml
<com.cloudbees.plugins.credentials.SystemCredentialsProvider plugin="credentials#1.22">
<domainCredentialsMap class="hudson.util.CopyOnWriteMap$Hash">
<entry>
<com.cloudbees.plugins.credentials.domains.Domain>
<specifications/>
</com.cloudbees.plugins.credentials.domains.Domain>
<java.util.concurrent.CopyOnWriteArrayList>
<com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
<scope>GLOBAL</scope>
<id>c4855f57-5107-4b69-97fd-298e56a9977d</id>
<description>Para SVN</description>
<username>jenkins</username>
<password>J1ztA2vSXHbm60k5PjLl5jg70ZooSFKF+kRAo08UVts=
</password>
</com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl>
</java.util.concurrent.CopyOnWriteArrayList>
</entry>
</domainCredentialsMap>
</com.cloudbees.plugins.credentials.SystemCredentialsProvider>
I was also facing the same problem. What worked for me is I copied the credentials.xml, config.xml and the secrets folder from existing jenkins to the new instance. After the restart of jenkins things worked fine.
This is what worked for me.
Create a job in Jenkins that takes the credentials and writes them to output. If Jenkins replaces the password in the output with ****, just obfuscate it first (add a space between each character, reverse the characters, base64 encode it, etc.)
I used a Powershell job to base64 encode it:
[convert]::ToBase64String([text.encoding]::Default.GetBytes($mysecret))
And then used Powershell to convert the base64 string back to a regular string:
[text.encoding]::Default.GetString([convert]::FromBase64String("bXlzZWNyZXQ="))
After trying quite a few things for several days this is the best solution I found for migrating my secrets from a Jenkins 2.176 to a new clean Jenkins 2.249.1 jenkins-cli was the best approach for me.
The process is quite simple just dump the credentials from the old instance to a local machine, or Docker pod with java installed, as a XML file (unencrypted) and then uploaded to the new instance.
Before starting you should verify the following:
Access to the credentials section on both Jenkins instances
Download the jenkins-ccli.jar from one of the instances (https://www.your-jenkins-url.com/cli/)
Have User and Password/Token at hand.
Notice: In case your jenkins uses an oAuth service you will need to
create a token for your user. Once logged into jenkins at the top
right if you click your profile you can verify both username and
generate password.
Now for the special sauce, you have to execute both parts from the same machine/pod:
Notice: If your instances are using valid Certificates and you want to
secure your connection you must remove the -noCertificateCheck
flag from both commands.
# OLD JENKINS DUMP # 
export USER=madox#example.com
export TOKEN=f561banana6ead83b587a4a8799c12c307
export SERVER=https://old-jenkins-url.com/
java -jar jenkins-cli.jar -noCertificateCheck -s $SERVER -auth $USER:$TOKEN list-credentials-as-xml "system::system::jenkins" > /tmp/jenkins_credentials.xml
# NEW JENKINS IMPORT # 
export USER=admin
export TOKEN=admin
export SERVER=https://new-jenkins-url.com/
java -jar jenkins-cli.jar -noCertificateCheck -s $SERVER -auth $USER:$TOKEN import-credentials-as-xml "system::system::jenkins" < /tmp/jenkins_credentials.xml
If you have the credentials.xml available and the old Jenkins instance still running, there is a way to decrypt individual credentials so you can enter them in the new Jenkins instance via the UI.
The approach is described over at the DevOps stackexchange by kenorb.
This does not convert all the credentials for an easy, automated migration, but helps when you have only few credentials to migrate (manually).
To summarize, you visit the /script page over at the old Jenkins instance, and use the encrypted credential from the credentials.xml file in the following line:
println(hudson.util.Secret.decrypt("{EncryptedCredentialFromCredentialsXml=}"))
To migrate all credentials to a new server, from Jenkins: Migrating credentials:
Stop Jenkins on new server.
new-server # /etc/init.d/jenkins stop
Remove the identity.key.enc file on new server:
new-server # rm identity.key.enc
Copy secret* and credentials.xml to new server.
current-server # cd /var/lib/jenkins
current-server # tar czvf /tmp/credentials.tgz secret* credentials.xml
current-server # scp credentials.tgz $user#$new-server:/tmp/
new-server # cd /var/lib/jenkins
new-server # tar xzvf /tmp/credentials.tgz -C ./
Start Jenkins.
new-server # /etc/init.d/jenkins start
Migrating users from a Jenkins instance to another Jenkins on a new server -
I tried following https://stackoverflow.com/a/35603191 which lead to https://itsecureadmin.com/2018/03/26/jenkins-migrating-credentials/. However I did not succeed in following these steps.
Further, I experimented exporting /var/lib/jenkins/users (or {JENKINS_HOME}/users) directory to the new instance on new server. After restarting the Jenkins on new server - it looks like all the user credentials are available on new server.
Additionally, I cross-checked if the users can log in to the new Jenkins instance. It works for now.
PS: This code is for redhat servers
Old server:
cd /var/lib/jeknins
or cd into wherever your Jenkins home is
tar cvzf users.tgz ./users
New server:
cd /var/lib/jeknins
scp <user>#<oldserver>:/var/lib/jenkins/user.tgz ~/var/lib/jenkins/.
sudo tar xvzf users.tgz
systemctl restart jenkins
Did you try to copy the $JENKINS_HOME/users folder and the $JENKINS_HOME/credentials.xml file to the other Jenkins instance?

Resources