0
votes

My company has a self-hosted GitLab server. I'm writing an Ansible playbook that configures a server by using several projects from our GitLab server.

In order to have the target server clone the projects automatically (non-interactively), I'm using deploy tokens.

First, on our GitLab server's web interface, I went to my first project and generated a deploy key for it. I can configure the target server to use the deploy key using ansible with something like this:

- name: Have git store credentials on disk
  community.general.git_config:
    name: credential.helper
    scope: global
    value: store

- name: Add credentials for project A
  copy:
      dest: /root/.git-credentials
      content: "https://{{ gitlab_project_A_deploy_username }}:{{ gitlab_project_A_deploy_password }}@company_gitlab_server.com"

- name: Clone Project A git repo
  git:
    repo: 'https://company_gitlab_server.com/USER/Project_A.git'
    dest: /some/dir/

I set gitlab_project_A_deploy_username and gitlab_project_A_deploy_password in the ansible vault. This works great, except that in /root/.git-credentials, the credentials are not git-repo specific - they are server specific.

When I get a deploy key for Project B, it has a completely different username and password, but the server is the same. Even if I add both sets of credentials to /root/.git-credentials, the git ansible module, or even just the regular git binary would have no idea which credentials to use when cloning a project.

Is there a way to somehow specify one deploy key for one project, and a different deploy key for a different project?

2

2 Answers

2
votes

Why not just set the credentials directly into the repo path?

- name: Clone Project A git repo
  git:
    repo: 'https://{{ gitlab_project_A_deploy_username }}:{{ gitlab_project_A_deploy_password }}@company_gitlab_server.com/USER/Project_A.git'
    dest: /some/dir/
1
votes

If you want to use a helper for the credentials (whether store or cache) you can use the credential.useHttpPath option to make it match on the path too.

Then, for the store helper, save

https://{{ gitlab_project_A_deploy_username }}:{{ gitlab_project_A_deploy_password }}@company_gitlab_server.com/USER/Project_A.git
https://{{ gitlab_project_B_deploy_username }}:{{ gitlab_project_B_deploy_password }}@company_gitlab_server.com/USER/Project_B.git

in the credentials store.