debian-mirror-gitlab/app/services/google_cloud/service_accounts_service.rb

69 lines
2.2 KiB
Ruby
Raw Normal View History

2021-12-11 22:18:48 +05:30
# frozen_string_literal: true
module GoogleCloud
##
# GCP keys used to store Google Cloud Service Accounts
GCP_KEYS = %w[GCP_PROJECT_ID GCP_SERVICE_ACCOUNT GCP_SERVICE_ACCOUNT_KEY].freeze
##
# This service deals with GCP Service Accounts in GitLab
class ServiceAccountsService < ::BaseService
##
# Find GCP Service Accounts in a GitLab project
#
# This method looks up GitLab project's CI vars
# and returns Google Cloud Service Accounts combinations
# aligning GitLab project and environment to GCP projects
def find_for_project
group_vars_by_environment.map do |environment_scope, value|
{
environment: environment_scope,
gcp_project: value['GCP_PROJECT_ID'],
service_account_exists: value['GCP_SERVICE_ACCOUNT'].present?,
service_account_key_exists: value['GCP_SERVICE_ACCOUNT_KEY'].present?
}
end
end
2022-03-02 08:16:31 +05:30
def add_for_project(environment, gcp_project_id, service_account, service_account_key, is_protected)
2022-01-26 12:08:38 +05:30
project_var_create_or_replace(
environment,
'GCP_PROJECT_ID',
2022-03-02 08:16:31 +05:30
gcp_project_id,
is_protected
2022-01-26 12:08:38 +05:30
)
project_var_create_or_replace(
environment,
'GCP_SERVICE_ACCOUNT',
2022-03-02 08:16:31 +05:30
service_account,
is_protected
2022-01-26 12:08:38 +05:30
)
project_var_create_or_replace(
environment,
'GCP_SERVICE_ACCOUNT_KEY',
2022-03-02 08:16:31 +05:30
service_account_key,
is_protected
2022-01-26 12:08:38 +05:30
)
end
2021-12-11 22:18:48 +05:30
private
def group_vars_by_environment
2022-03-02 08:16:31 +05:30
filtered_vars = project.variables.filter { |variable| GCP_KEYS.include? variable.key }
2021-12-11 22:18:48 +05:30
filtered_vars.each_with_object({}) do |variable, grouped|
grouped[variable.environment_scope] ||= {}
grouped[variable.environment_scope][variable.key] = variable.value
end
end
2022-01-26 12:08:38 +05:30
2022-03-02 08:16:31 +05:30
def project_var_create_or_replace(environment_scope, key, value, is_protected)
2022-01-26 12:08:38 +05:30
params = { key: key, filter: { environment_scope: environment_scope } }
2022-03-02 08:16:31 +05:30
existing_variable = ::Ci::VariablesFinder.new(project, params).execute.first
2022-01-26 12:08:38 +05:30
existing_variable.destroy if existing_variable
2022-03-02 08:16:31 +05:30
project.variables.create!(key: key, value: value, environment_scope: environment_scope, protected: is_protected)
2022-01-26 12:08:38 +05:30
end
2021-12-11 22:18:48 +05:30
end
end