Skip to content

Commit

Permalink
Stop PRs to same repo interfering with each other
Browse files Browse the repository at this point in the history
Previously the branch name was static,
which caused issues when terraform opens PRs to multiple target branches
to the same repository.
This is because the terraform run for each target branch
was trying to work on the same branch,
and opening PRs from the same branch.
This was observed in repos when we maintain multiple branches
(eg. snap-tempest with main, stable/caracal, stable/bobcat, etc.).

This fixes it by including the target branch name in the PR branch,
ensuring that each PR in a target repository will use its own branch,
and there won't be any more cross interference.

Fixes: #88
  • Loading branch information
samuelallan72 committed Sep 19, 2024
1 parent 6214497 commit 1c83f19
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 6 deletions.
12 changes: 8 additions & 4 deletions terraform-plans/modules/GitHub/templates/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -49,12 +49,16 @@ locals {
}
}

locals {
pr_branch = "${var.pr_branch_prefix}-${var.branch}"
}

# Create a new branch only if there are changed files
resource "github_branch" "managed_files_branch" {
count = length(local.changed_files) > 0 ? 1 : 0

repository = var.repository
branch = var.pr_branch
branch = local.pr_branch
source_branch = var.branch
}

Expand All @@ -79,11 +83,11 @@ data "github_repository_pull_requests" "open" {
}

locals {
pr_exists = length([for pr in data.github_repository_pull_requests.open.results : pr if pr.head_ref == var.pr_branch]) > 0
pr_exists = length([for pr in data.github_repository_pull_requests.open.results : pr if pr.head_ref == local.pr_branch]) > 0
}

locals {
existing_pr = local.pr_exists ? [for pr in data.github_repository_pull_requests.open.results : pr if pr.head_ref == var.pr_branch][0] : null
existing_pr = local.pr_exists ? [for pr in data.github_repository_pull_requests.open.results : pr if pr.head_ref == local.pr_branch][0] : null
}

locals {
Expand Down Expand Up @@ -125,7 +129,7 @@ output "pr_created" {
}

output "pr_branch" {
value = var.pr_branch
value = local.pr_branch
}

output "pr_url" {
Expand Down
4 changes: 2 additions & 2 deletions terraform-plans/modules/GitHub/templates/variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ variable "branch" {
default = "main"
}

variable "pr_branch" {
variable "pr_branch_prefix" {
type = string
description = "Pull request branch name."
description = "Pull request branch name prefix."
default = "automation/update-managed-files"
}

Expand Down

0 comments on commit 1c83f19

Please sign in to comment.