In a microservice application, the code for each service has its own git repository. However, how do deploy without duplicating the Gitlab agents ?

In Gitlab, you can share an agent between several projects to deploy the application on a Kubernetes cluster !

Define and configure the main project

The main project contains the agent for deploying the application. It installs in the usual way, without any difference. To declare the agent, see the article: Connect a Kubernetes cluster to GitLab

To authorize other projects to access the agent, you must configure the main project:

  • In the project repository, create a folder .gitlab/agents
  • In .gitlab/agents, add a directory with the same name as the agent you want to share. (You can see the list of agents in Operate > Kubernetes Cluster)
  • In the previous folder, create a file named config.yaml

The config.yaml file

To allow access to a group of project, add this configuration into the config.yaml:

ci_access:
  groups:
    - id: path/to/my_group

With this code, all the projects into my_group can use the agent to deploy into the Kubernetes cluster.

To allow acces to projects define this configuration into the config.yaml:

ci_access:
  projects:
    - id: path/to/my_project
    - id: path/to/my_second_project

This code allows specific projects to use the agent. By the way, all authorized projects must be listed one by one.

Using the agent from an authorized project

Projects or groups authorized by the main project can therefore use the agent to deploy. For more information about deployment, see the article : Deploy an application with GitLab CI/CD

To target the main project agent, set the right path when defining the context in the before_script:

deploy:
  before_script:
  - kubectl config use-context path/to/main/project:agent-name
  

The path used in the “kubectl config use-context”, corresponds to the main project path, followed by : and the name of the agent in the main project.

Conclusion

In conclusion, it is perfectly possible to share an agent between several projects. This is particularly useful when an application is split into several git projects. As a result, maintenance is simpler because there’s only one agent to keep up to date.