-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgitlab_variable_editor
More file actions
executable file
·394 lines (324 loc) · 12.4 KB
/
Copy pathgitlab_variable_editor
File metadata and controls
executable file
·394 lines (324 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
#!/usr/bin/env ruby
require 'gitlab'
require 'yaml'
require 'thor'
$stdout.sync = true
class GitLabVariableEditor < Thor
class_option :endpoint, type: :string, required: true, aliases: '-e', desc: 'GitLab API endpoint (e.g., https://gitlab.example.com/api/v4)'
class_option :token, type: :string, required: true, aliases: '-t', desc: 'GitLab access token'
class_option :project, type: :string, aliases: '-p', desc: 'Project ID or path (required for export/import, e.g., my-group/my-project)'
desc 'export OUTPUT_FILE', 'Export all CI/CD variables from a GitLab project to a YAML file'
def export(output_file)
require_project!
configure_client
puts "Fetching CI/CD variables from project: #{options[:project]}"
begin
variables = @client.variables(options[:project])
if variables.empty?
puts "No variables found for project #{options[:project]}"
return
end
# Convert to hash format suitable for YAML
variables_data = variables.map do |var|
{
'key' => var.key,
'value' => var.value,
'variable_type' => var.variable_type,
'protected' => var.protected,
'masked' => var.masked,
'hidden' => var.respond_to?(:hidden) ? var.hidden : false,
'raw' => var.respond_to?(:raw) ? var.raw : false,
'environment_scope' => var.environment_scope,
'description' => var.respond_to?(:description) ? var.description : nil
}
end
# Save to YAML file
File.write(output_file, YAML.dump(variables_data))
puts "Successfully exported #{variables.count} variable(s) to #{output_file}"
rescue Gitlab::Error::Error => e
puts "Error: #{e.message}"
exit 1
end
end
desc 'import INPUT_FILE', 'Import CI/CD variables from a YAML file to a GitLab project'
option :force, type: :boolean, default: false, aliases: '-f', desc: 'Skip confirmation prompts'
option :'delete-other', type: :boolean, default: false, desc: 'Delete variables that exist in GitLab but not in the import file'
def import(input_file)
require_project!
configure_client
unless File.exist?(input_file)
puts "Error: File '#{input_file}' not found"
exit 1
end
puts "Loading variables from #{input_file}"
begin
variables_data = YAML.load_file(input_file)
unless variables_data.is_a?(Array)
puts "Error: Invalid YAML format. Expected an array of variables."
exit 1
end
# Fetch existing variables
puts "Fetching existing variables from project: #{options[:project]}"
existing_variables = @client.variables(options[:project])
existing_keys = existing_variables.map(&:key)
# Separate new and existing variables
new_vars = []
update_vars = []
variables_data.each do |var|
if existing_keys.include?(var['key'])
update_vars << var
else
new_vars << var
end
end
# Show summary
puts "\nSummary:"
puts " New variables to create: #{new_vars.count}"
puts " Existing variables to update: #{update_vars.count}"
puts " Total variables to process: #{variables_data.count}"
# Compute variables to delete
import_keys = variables_data.map { |v| v['key'] }
delete_vars = existing_variables.reject { |ev| import_keys.include?(ev.key) }
if delete_vars.any?
puts " Variables to delete: #{delete_vars.count}"
end
if update_vars.any? && !options[:force]
puts "\nThe following variables will be OVERWRITTEN:"
update_vars.each { |v| puts " - #{v['key']}" }
print "\nDo you want to continue? (yes/no): "
response = (STDIN.gets || '').chomp.downcase
unless ['yes', 'y'].include?(response)
puts "Import cancelled."
exit 0
end
end
if delete_vars.any? && options[:'delete-other'] && !options[:force]
puts "\nThe following variables will be DELETED:"
delete_vars.each { |v| puts " - #{v.key}" }
print "\nDo you want to continue? (yes/no): "
response = (STDIN.gets || '').chomp.downcase
unless ['yes', 'y'].include?(response)
puts "Import cancelled."
exit 0
end
end
# Import variables
puts "\nImporting variables..."
created_count = 0
updated_count = 0
error_count = 0
variables_data.each do |var|
begin
# Prepare options
var_options = {
variable_type: var['variable_type'] || 'env_var',
protected: var['protected'] || false,
masked: var['masked'] || false,
raw: var.key?('raw') ? var['raw'] : false,
environment_scope: var['environment_scope'] || '*'
}
# Add description if present
var_options[:description] = var['description'] if var['description']
# Add hidden if present (GitLab 17.4+)
var_options[:hidden] = var['hidden'] if var.key?('hidden')
if existing_keys.include?(var['key'])
# Update existing variable
@client.update_variable(options[:project], var['key'], var['value'], **var_options)
puts " ✓ Updated: #{var['key']}"
updated_count += 1
else
# Create new variable
@client.create_variable(options[:project], var['key'], var['value'], **var_options)
puts " ✓ Created: #{var['key']}"
created_count += 1
end
rescue Gitlab::Error::Error => e
puts " ✗ Failed: #{var['key']} - #{e.message}"
error_count += 1
end
end
# Delete variables that exist in GitLab but not in the import file
deleted_count = 0
if delete_vars.any? && options[:'delete-other']
puts "\nDeleting variables..."
delete_vars.each do |var|
begin
@client.delete_variable(options[:project], var.key)
puts " ✓ Deleted: #{var.key}"
deleted_count += 1
rescue Gitlab::Error::Error => e
puts " ✗ Failed to delete: #{var.key} - #{e.message}"
end
end
end
puts "\nImport completed:"
puts " Created: #{created_count}"
puts " Updated: #{updated_count}"
puts " Deleted: #{deleted_count}"
puts " Failed: #{error_count}"
rescue Psych::SyntaxError => e
puts "Error: Invalid YAML syntax - #{e.message}"
exit 1
rescue Gitlab::Error::Error => e
puts "Error: #{e.message}"
exit 1
end
end
desc 'batch-update KEY [VALUE]', 'Update one CI/CD variable across all projects visible to the token (VALUE is read from stdin when omitted or empty)'
option :type, type: :string, default: 'env_var', enum: %w[env_var file], desc: 'Variable kind'
option :scope, type: :string, default: '*', aliases: '-s', desc: 'Environment scope to target. When "*", variables with the same key and type in OTHER scopes are DELETED'
option :'set-missing', type: :boolean, default: false, aliases: '-m', desc: 'Create the variable in projects where it is missing instead of skipping them'
option :force, type: :boolean, default: false, aliases: '-f', desc: 'Skip confirmation prompts'
def batch_update(key, value = nil)
configure_client
if key.to_s.strip.empty?
puts 'Error: Variable key must not be empty'
exit 1
end
var_type = options[:type]
scope = options[:scope]
@stdin_consumed = false
if value.nil? || value.strip.empty?
puts 'Reading variable value from stdin...'
value = $stdin.read
value = value.sub(/\r?\n\z/, '') # drop one trailing newline added by echo/pipes
@stdin_consumed = true
end
puts "\nSettings:"
puts " Key: #{key}"
puts " Type: #{var_type}"
puts " Scope: #{scope}#{' (default)' if scope == '*'}"
begin
puts 'Fetching projects from GitLab instance...'
projects = @client.projects(per_page: 100).auto_paginate
puts "Scanning #{projects.count} project(s) for variable '#{key}' (#{var_type})..."
plan = []
projects.each do |project|
begin
vars = @client.variables(project.id)
rescue Gitlab::Error::Error, SocketError, SystemCallError => e
puts "\n ! Skipping #{project.path_with_namespace}: cannot read variables (#{e.message})"
next
end
same_key = vars.select { |v| v.key == key && v.variable_type == var_type }
target = same_key.find { |v| v.environment_scope == scope }
others = same_key.reject { |v| v.environment_scope == scope }
will_write = !target.nil? || options[:'set-missing']
delete_scopes = (scope == '*' && will_write) ? others.map(&:environment_scope) : []
plan << {
id: project.id,
path: project.path_with_namespace,
action: will_write ? :write : :skip,
had_existing: !target.nil?,
delete_scopes: delete_scopes
}
print '.'
end
rescue Gitlab::Error::Error, SocketError, SystemCallError => e
puts "\nError: #{e.message}"
exit 1
end
puts ''
to_write = plan.select { |p| p[:action] == :write }
skipped_count = plan.count { |p| p[:action] == :skip }
to_delete_total = plan.sum { |p| p[:delete_scopes].count }
puts "\nSummary:"
puts " Projects scanned: #{projects.count}"
puts " Projects to update/create: #{to_write.count}"
puts " Projects skipped (variable missing): #{skipped_count}"
puts " Other-scope variables to DELETE: #{to_delete_total}"
if to_delete_total.positive?
puts "\nWARNING: Environment scope \"*\" was requested."
puts 'The following variables with the same key and type in other scopes will be PERMANENTLY DELETED:'
plan.each do |p|
p[:delete_scopes].each { |s| puts " - #{p[:path]}: #{key} (scope: #{s})" }
end
end
if to_write.empty? && to_delete_total.zero?
puts "\nNothing to do."
return
end
unless confirm_batch_update?
puts 'Batch update cancelled.'
exit 0
end
puts "\nApplying changes..."
updated_count = 0
created_count = 0
deleted_count = 0
failed_count = 0
plan.each do |p|
next if p[:action] == :skip
begin
if p[:had_existing]
@client.update_variable(p[:id], key, value, filter: { environment_scope: scope })
puts " ✓ Updated: #{p[:path]} (scope: #{scope})"
updated_count += 1
else
@client.create_variable(p[:id], key, value, variable_type: var_type, environment_scope: scope)
puts " ✓ Created: #{p[:path]} (scope: #{scope})"
created_count += 1
end
p[:delete_scopes].each do |s|
begin
@client.remove_variable(p[:id], key, filter: { environment_scope: s })
puts " ✓ Deleted: #{p[:path]} (scope: #{s})"
deleted_count += 1
rescue Gitlab::Error::Error => e
puts " ✗ Failed to delete: #{p[:path]} (scope: #{s}) - #{e.message}"
failed_count += 1
end
end
rescue Gitlab::Error::Error => e
puts " ✗ Failed: #{p[:path]} - #{e.message}"
failed_count += 1
end
end
puts "\nBatch update completed:"
puts " Updated: #{updated_count}"
puts " Created: #{created_count}"
puts " Deleted: #{deleted_count}"
puts " Skipped: #{skipped_count}"
puts " Failed: #{failed_count}"
end
private
def require_project!
return unless options[:project].to_s.strip.empty?
puts 'Error: Missing required option: --project (-p)'
exit 1
end
def confirm_batch_update?
return true if options[:force]
print "\nDo you want to continue? (yes/no): "
io =
if @stdin_consumed
open_tty
else
$stdin
end
if io.nil?
puts "\nError: Cannot prompt for confirmation: stdin was used for the variable value and no terminal is available. Re-run with --force."
exit 1
end
response = (io.gets || '').chomp.downcase
io.close unless io.equal?($stdin)
%w[yes y].include?(response)
end
def open_tty
File.open('/dev/tty', 'r')
rescue SystemCallError, IOError
nil
end
def configure_client
@client = Gitlab.client(
endpoint: options[:endpoint],
private_token: options[:token]
)
rescue => e
puts "Error configuring GitLab client: #{e.message}"
exit 1
end
end
if __FILE__ == $0
GitLabVariableEditor.start(ARGV)
end