Class: Environments::CreateService

Inherits:
BaseService show all
Defined in:
app/services/environments/create_service.rb

Constant Summary collapse

ALLOWED_ATTRIBUTES =
%i[name description external_url tier cluster_agent kubernetes_namespace
flux_resource_path auto_stop_setting].freeze

Constants inherited from BaseService

BaseService::UnauthorizedError

Instance Attribute Summary

Attributes inherited from BaseService

#current_user, #params, #project

Instance Method Summary collapse

Methods inherited from BaseService

#initialize

Methods included from BaseServiceUtility

#deny_visibility_level, #event_service, #log_error, #log_info, #notification_service, #system_hook_service, #todo_service, #visibility_level

Methods included from Gitlab::Allowable

#can?, #can_all?, #can_any?

Constructor Details

This class inherits a constructor from BaseService

Instance Method Details

#executeObject



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
# File 'app/services/environments/create_service.rb', line 8

def execute
  unless can?(current_user, :create_environment, project)
    return ServiceResponse.error(
      message: _('Unauthorized to create an environment'),
      payload: { environment: nil }
    )
  end

  # Note: We skip checking the cluster agent authorization if the `skip_agent_auth`
  # parameter is present. This allows creating environments that reference a cluster agent
  # before the agent has connected for the first time.
  # This is necessary to support the bootstrapping workflow, where environments
  # are created before the agent has connected for the first time.
  # See https://gitlab.com/gitlab-org/cli/-/issues/7786 for context.
  if params[:skip_agent_auth].blank? && unauthorized_cluster_agent?
    return ServiceResponse.error(
      message: _('Unauthorized to access the cluster agent in this project'),
      payload: { environment: nil })
  end

  begin
    environment = project.environments.new(**params.slice(*ALLOWED_ATTRIBUTES))
    environment.ensure_environment_tier
    environment.set_default_auto_stop_setting unless params[:auto_stop_setting]
    environment.save!
    ServiceResponse.success(payload: { environment: environment })
  rescue ActiveRecord::RecordInvalid => err
    ServiceResponse.error(message: err.record.errors.full_messages, payload: { environment: nil })
  rescue ArgumentError => err
    ServiceResponse.error(message: [err.message], payload: { environment: nil })
  end
end