Managing self-hosted GitLab with Terraform

May 16, 2021 – Samuli Seppänen

GitLab has an extensive API which allows managing its internal configuration such as users, groups and projects. The official GitLab Terraform provider builds on top of this API.

It assumed here that the Terraform controller (e.g. your laptop) is able to reach your GitLab instance's TCP port 443 - if it can't there's no way Terraform's API calls will work. The same approach should work with - you can probably (=untested) skip the base_url parameter in that case.

The first step is to create a GitLab Personal Access Token. As the token is personal you should create it for the GitLab root user, or some other user that has sufficient permissions in GitLab to do the operations Terraform requires. That said, for security reasons try to limit the permissions the token has.

Once the token is ready basic Terraform setup is quite straightforward. First add this to the "terraform { ... }" block in your root module:

  required_providers {
    gitlab = {
      source  = "gitlabhq/gitlab"
      version = "3.6.0"

Then configure the GitLab provider

variable "gitlab_token" {
  type = string

# If you're using Letsencrypt
 for GitLab you may need "insecure = true"
provider "gitlab" {
  base_url = ""
  insecure = true
  token    = var.gitlab_token

At this point you should be able to do "terraform init" to initialize the GitLab provider. If so, try adding a resource to your Terraform code:

resource "gitlab_group" "devops" {
  name        = "devops"
  path        = "devops"
  description = "Group for Devops"

Then set the "gitlab_token" variable with TF_VAR_gitlab_token=<token> and do a "terraform apply". It should create the resource. If it did not, there's probably a connectivity, TLS, permission or Terraform version issue somewhere.

Once you're able to create resources check the official provider documentation to see what you can do with it. If your GitLab instance gets users from an external source (e.g. Keycloak) use the gitlab_user data source to get their properties. Those properties are needed to, for example, to join users to groups with the gitlab_group_attachment resource.

Want to talk to an expert?

If you want to reach us, just send us a message or book a free call!