From c3de9f94ab6e4dc9aaa6161897579038369b7aa0 Mon Sep 17 00:00:00 2001
From: dali546 <35352237+dali546@users.noreply.github.com>
Date: Thu, 1 Feb 2024 20:35:29 +0000
Subject: [PATCH] fix(terraform): Replace correct currentValue match in
 constraint with new value (#26867)

Co-authored-by: Sebastian Poxhofer <secustor@users.noreply.github.com>
---
 .../manager/terraform/lockfile/index.spec.ts  | 26 +++++++++++++++++++
 .../manager/terraform/lockfile/index.ts       |  4 +--
 2 files changed, 28 insertions(+), 2 deletions(-)

diff --git a/lib/modules/manager/terraform/lockfile/index.spec.ts b/lib/modules/manager/terraform/lockfile/index.spec.ts
index a49a2dadd1..df8ad45196 100644
--- a/lib/modules/manager/terraform/lockfile/index.spec.ts
+++ b/lib/modules/manager/terraform/lockfile/index.spec.ts
@@ -1118,6 +1118,32 @@ describe('modules/manager/terraform/lockfile/index', () => {
       ).toBe('>= 2.36.0, 2.46.0');
     });
 
+    it('update constraint when current version is matched multiple times', () => {
+      expect(
+        getNewConstraint(
+          {
+            currentValue: '2.41.0',
+            newValue: '2.46.0',
+            newVersion: '2.46.0',
+          },
+          '>= 2.41.0, 2.41.0',
+        ),
+      ).toBe('>= 2.41.0, 2.46.0');
+    });
+
+    it('update constraint when current version is in a complicated constraint', () => {
+      expect(
+        getNewConstraint(
+          {
+            currentValue: '<= 2.41.0',
+            newValue: '<= 2.46.0',
+            newVersion: '2.46.0',
+          },
+          '>= 2.41.0, <= 2.41.0, >= 2.0.0',
+        ),
+      ).toBe('>= 2.41.0, <= 2.46.0, >= 2.0.0');
+    });
+
     it('create constraint with full version', () => {
       expect(
         getNewConstraint(
diff --git a/lib/modules/manager/terraform/lockfile/index.ts b/lib/modules/manager/terraform/lockfile/index.ts
index 70f9e8739e..11ff172002 100644
--- a/lib/modules/manager/terraform/lockfile/index.ts
+++ b/lib/modules/manager/terraform/lockfile/index.ts
@@ -99,8 +99,8 @@ export function getNewConstraint(
     );
     //remove surplus .0 version
     return oldConstraint.replace(
-      regEx(`${escapeRegExp(currentValue)}(\\.0)*`),
-      newValue,
+      regEx(`(,\\s|^)${escapeRegExp(currentValue)}(\\.0)*`),
+      `$1${newValue}`,
     );
   }
 
-- 
GitLab