Gitlab Terraform Provider

Hey together,

I try to use Gitlab Terraform Provider, to configure Gitlab Kubernetes Agent (KAS) and generate an agent token.
Is it possible to use $CI_JOB_TOKEN with the terraform provider to create the token?
Each time I run this in a pipeline I get the following error:

Planning failed. Terraform encountered an error while generating this plan.
╷
│ Error: GET https://git.domain.com/api/v4/user: 401 {message: 401 Unauthorized}
│ 
│   with provider["registry.terraform.io/gitlabhq/gitlab"],
│   on provider.tf line 6, in provider "gitlab":
│    6: provider "gitlab" {
│ 

Following GitLab CI/CD job token | GitLab the user running/triggering the pipeline needs to have appropriate permissions to create the token. Terraform Registry says that maintainer permissions are required. I would guess that a different token is required, i.e. a project access token.

Can you show the terraform code and CI/CD configuration that executes tf plan, and the user permissions that run the pipeline?

So this is the terraform code:

provider "gitlab" {
  base_url = "https://git.domain.com/api/v4/"
}

resource "gitlab_cluster_agent" "cluster_agent" {
  project = data.gitlab_project.infrastructure.id
  name    = "gke-test-${var.environment}"
}

resource "gitlab_cluster_agent_token" "gitlab_cluster_agent_token" {
  name        = "Gitlab Agent Token"
  project     = data.gitlab_project.infrastructure.id
  agent_id    = gitlab_cluster_agent.cluster_agent.agent_id
  description = "Token for the agent used with `gitlab-agent` Helm Chart"
}

.gitlab-ci.yml:

terraform:validate:
  extends: .terraform:validate
  stage: terraform-validate
  variables:
    WORKDIR: "."
    TF_INIT_ARGS: -backend=false

terraform:plan:
  extends: .terraform:plan
  stage: terraform-plan
  environment: $ENVIRONMENT
  variables:
    WORKDIR: "."
    TF_INIT_ARGS: -reconfigure -backend-config=stages/${ENVIRONMENT}.tfbackend
    TF_PLAN_ARGS: -var-file=stages/${ENVIRONMENT}.tfvars
  rules:
    - changes:
        - helm/**/*
        - "*.tf"
        - stages/${ENVIRONMENT}.tfvars
        - stages/${ENVIRONMENT}.tfbackend

And it is my user that is owner (inherited from parent group).

@dcardellino where do you specify credentials to your GitLab instance for the TF GitLab provider?

I use a CI/CD Variable and set

GITLAB_TOKEN = $CI_JOB_TOKEN with Expand variable reference enabled.

As mentioned by @dnsmichi CI_JOB_TOKEN does not have permissions to create what you want. If you want to use it in Pipelines you need to create Personal/Project/Group token with required role Maintainer and use that.

1 Like

Alright, then I will create a token that fits my needs :slight_smile: Thanks for your help.

Using a project access token with maintainer permissions is sufficient :+1:

1 Like