jschnasse
jschnasse

Reputation: 9518

Create Gitlab Repo and Provide Basic Setup over API

I want to achieve the following task by script:

  1. Create a new Project/Repo on Gitlab
  2. Create two protected branches: main and stable
  3. Choose merge strategy: "Semilinear with Merge Commits"
  4. Allow maintainers to push into main (Jenkins-CI will access the repo as maintainer)
  5. Allow developers+maintainers to merge
  6. Discussions must be resolved before merge
  7. Verify build must succeed before merge
  8. Disallow to merge into stable

Upvotes: 0

Views: 1100

Answers (1)

jschnasse
jschnasse

Reputation: 9518

I came up with this approach:

Creation

git init
git remote add origin [email protected]/....
git checkout -b main
git commit -a --allow-empty -m"Initial Commit!"
git push origin main
git checkout -b stable
git push origin stable

Configuration

#! /bin/bash 

GITLAB_PROJECT_ID=$1
GITLAB_TOKEN=$2

repo_config=$(cat <<EOF
{
   "merge_method" : "rebase_merge",   
   "auto_devops_enabled" : false,
   "only_allow_merge_if_pipeline_succeeds" : true,
   "merge_requests_enabled" : true,   
   "allow_merge_on_skipped_pipeline" : false,
   "only_allow_merge_if_all_discussions_are_resolved" : true,
   "visibility" : "internal"
}
EOF
)

main_branch_config=$(cat <<EOF
{
      "name": "main",
      "allowed_to_push": [{"access_level": 40}],
      "allowed_to_merge": [{
          "access_level": 30
        },{
          "access_level": 40
        }
      ]}
EOF
)

stable_branch_config=$(cat <<EOF
{
      "name": "stable",
      "allowed_to_push": [{"access_level": 40}],
      "allowed_to_merge": [{"access_level": 0}]
}
EOF
)

curl "https://gitlab.com/api/v4/projects/$GITLAB_PROJECT_ID" \
-i \
-X PUT \
-H "content-type:application/json" \
-H "PRIVATE-TOKEN: $GITLAB_TOKEN" \
-d "$repo_config" 

curl "https://gitlab.com/api/v4/projects/$GITLAB_PROJECT_ID/protected_branches" \
-X POST \
-i \
-H "content-type:application/json" \
-H "PRIVATE-TOKEN: $GITLAB_TOKEN" \
-d "$main_branch_config" 

curl "https://gitlab.com/api/v4/projects/$GITLAB_PROJECT_ID/protected_branches" \
-i \
-X POST \
-H "content-type:application/json" \
-H "PRIVATE-TOKEN: $GITLAB_TOKEN" \
-d "$stable_branch_config" 

Note that the setup of permissions on the protected branches is only supported for "premium" installations.

Upvotes: 1

Related Questions