Module: Morpheus::Cli::ProvisioningHelper

Included in:
Apps, ArchivesCommand, BlueprintsCommand, Clusters, ContainersCommand, Hosts, ImageBuilderCommand, InstanceTypes, Instances
Defined in:
lib/morpheus/cli/mixins/provisioning_helper.rb

Overview

Provides common methods for provisioning instances

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(klass) ⇒ Object



7
8
9
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 7

def self.included(klass)
  klass.send :include, Morpheus::Cli::PrintHelper
end

Instance Method Details

#api_clientObject



11
12
13
14
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 11

def api_client
  raise "#{self.class} has not defined @api_client" if @api_client.nil?
  @api_client
end

#find_cloud_by_id_for_provisioning(group_id, val) ⇒ Object



93
94
95
96
97
98
99
100
101
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 93

def find_cloud_by_id_for_provisioning(group_id, val)
  clouds = get_available_clouds(group_id)
  cloud = clouds.find {|it| it["id"].to_s == val.to_s }
  if !cloud
    print_red_alert "Cloud not found by id #{val}"
    exit 1
  end
  return cloud
end

#find_cloud_by_name_for_provisioning(group_id, val) ⇒ Object



103
104
105
106
107
108
109
110
111
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 103

def find_cloud_by_name_for_provisioning(group_id, val)
  clouds = get_available_clouds(group_id)
  cloud = clouds.find {|it| it["name"].to_s.downcase == val.to_s.downcase }
  if !cloud
    print_red_alert "Cloud not found by name #{val}"
    exit 1
  end
  return cloud
end

#find_cloud_by_name_or_id_for_provisioning(group_id, val) ⇒ Object



113
114
115
116
117
118
119
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 113

def find_cloud_by_name_or_id_for_provisioning(group_id, val)
  if val.to_s =~ /\A\d{1,}\Z/
    return find_cloud_by_id_for_provisioning(group_id, val)
  else
    return find_cloud_by_name_for_provisioning(group_id, val)
  end
end

#find_group_by_id_for_provisioning(val) ⇒ Object



65
66
67
68
69
70
71
72
73
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 65

def find_group_by_id_for_provisioning(val)
  groups = get_available_groups()
  group = groups.find {|it| it["id"].to_s == val.to_s }
  if !group
    print_red_alert "Group not found by id #{val}"
    exit 1
  end
  return group
end

#find_group_by_name_for_provisioning(val) ⇒ Object



75
76
77
78
79
80
81
82
83
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 75

def find_group_by_name_for_provisioning(val)
  groups = get_available_groups()
  group = groups.find {|it| it["name"].to_s.downcase == val.to_s.downcase }
  if !group
    print_red_alert "Group not found by name #{val}"
    exit 1
  end
  return group
end

#find_group_by_name_or_id_for_provisioning(val) ⇒ Object



85
86
87
88
89
90
91
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 85

def find_group_by_name_or_id_for_provisioning(val)
  if val.to_s =~ /\A\d{1,}\Z/
    return find_group_by_id_for_provisioning(val)
  else
    return find_group_by_name_for_provisioning(val)
  end
end

#find_instance_by_id(id) ⇒ Object



187
188
189
190
191
192
193
194
195
196
197
198
199
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 187

def find_instance_by_id(id)
  begin
    json_response = instances_interface.get(id.to_i)
    return json_response['instance']
  rescue RestClient::Exception => e
    if e.response && e.response.code == 404
      print_red_alert "Instance not found by id #{id}"
      exit 1
    else
      raise e
    end
  end
end

#find_instance_by_name(name) ⇒ Object



201
202
203
204
205
206
207
208
209
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 201

def find_instance_by_name(name)
  json_results = instances_interface.get({name: name.to_s})
  if json_results['instances'].empty?
    print_red_alert "Instance not found by name #{name}"
    exit 1
  end
  instance = json_results['instances'][0]
  return instance
end

#find_instance_by_name_or_id(val) ⇒ Object



179
180
181
182
183
184
185
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 179

def find_instance_by_name_or_id(val)
  if val.to_s =~ /\A\d{1,}\Z/
    return find_instance_by_id(val)
  else
    return find_instance_by_name(val)
  end
end

#find_instance_type_by_code(code) ⇒ Object



135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 135

def find_instance_type_by_code(code)
  results = instance_types_interface.list({code: code})
  instance_types = results['instanceTypes']
  if instance_types.empty?
    print_red_alert "Instance Type not found by code #{code}"
    return nil
  end
  if instance_types.size() > 1
    print as_pretty_table(instance_types, [:id,:name,:code], {color:red})
    print_red_alert "Try using ID instead"
    return nil
  end
  # return instance_types[0]
  # fetch by ID to get full details
  # could also use ?details-true with search
  return find_instance_type_by_id(instance_types[0]['id'])
end

#find_instance_type_by_id(id) ⇒ Object



121
122
123
124
125
126
127
128
129
130
131
132
133
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 121

def find_instance_type_by_id(id)
  begin
    json_response = instance_types_interface.get(id.to_i)
    return json_response['instanceType']
  rescue RestClient::Exception => e
    if e.response && e.response.code == 404
      print_red_alert "Instance Type not found by id #{id}"
      return nil
    else
      raise e
    end
  end
end

#find_instance_type_by_name(name) ⇒ Object



153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 153

def find_instance_type_by_name(name)
  results = instance_types_interface.list({name: name})
  instance_types = results['instanceTypes']
  if instance_types.empty?
    print_red_alert "Instance Type not found by name #{name}"
    return nil
  end
  if instance_types.size() > 1
    print as_pretty_table(instance_types, [:id,:name,:code], {color:red})
    print_red_alert "Try using ID instead"
    return nil
  end
  # return instance_types[0]
  # fetch by ID to get full details
  # could also use ?details-true with search
  return find_instance_type_by_id(instance_types[0]['id'])
end

#find_instance_type_by_name_or_id(val) ⇒ Object



171
172
173
174
175
176
177
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 171

def find_instance_type_by_name_or_id(val)
  if val.to_s =~ /\A\d{1,}\Z/
    return find_instance_type_by_id(val)
  else
    return find_instance_type_by_name(val)
  end
end

#find_workflow_by_id(id) ⇒ Object



219
220
221
222
223
224
225
226
227
228
229
230
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 219

def find_workflow_by_id(id)
  begin
    json_response = @task_sets_interface.get(id.to_i)
    return json_response['taskSet']
  rescue RestClient::Exception => e
    if e.response && e.response.code == 404
      print_red_alert "Workflow not found by id #{id}"
    else
      raise e
    end
  end
end

#find_workflow_by_name(name) ⇒ Object



232
233
234
235
236
237
238
239
240
241
242
243
244
245
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 232

def find_workflow_by_name(name)
  workflows = @task_sets_interface.get({name: name.to_s})['taskSets']
  if workflows.empty?
    print_red_alert "Workflow not found by name #{name}"
    return nil
  elsif workflows.size > 1
    print_red_alert "#{workflows.size} workflows by name #{name}"
    print_workflows_table(workflows, {color: red})
    print reset,"\n\n"
    return nil
  else
    return workflows[0]
  end
end

#find_workflow_by_name_or_id(val) ⇒ Object



211
212
213
214
215
216
217
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 211

def find_workflow_by_name_or_id(val)
  if val.to_s =~ /\A\d{1,}\Z/
    return find_workflow_by_id(val)
  else
    return find_workflow_by_name(val)
  end
end

#get_available_clouds(group_id, refresh = false) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 45

def get_available_clouds(group_id, refresh=false)
  if !group_id
    option_results = options_interface.options_for_source('clouds', {})
    return option_results['data'].collect {|it|
      {"id" => it["value"], "name" => it["name"], "value" => it["value"], "zoneTypeId" => it["zoneTypeId"]}
    }
  end
  group = find_group_by_id_for_provisioning(group_id)
  if !group
    return []
  end
  if !group["clouds"] || refresh
    option_results = options_interface.options_for_source('clouds', {groupId: group_id})
    group["clouds"] = option_results['data'].collect {|it|
      {"id" => it["value"], "name" => it["name"], "value" => it["value"], "zoneTypeId" => it["zoneTypeId"]}
    }
  end
  return group["clouds"]
end

#get_available_environments(refresh = false) ⇒ Object



1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1310

def get_available_environments(refresh=false)
  if !@available_environments || refresh
    begin
      option_results = options_interface.options_for_source('environments',{})
      @available_environments = option_results['data'].collect {|it|
        {"code" => (it["code"] || it["value"]), "name" => it["name"], "value" => it["value"]}
      }
    rescue RestClient::Exception => e
      # if e.response && e.response.code == 404
        Morpheus::Logging::DarkPrinter.puts "Unable to determine available environments, using default options" if Morpheus::Logging.debug?
        @available_environments = get_static_environments()
      # else
      #   raise e
      # end
    end
  end
  return @available_environments
end

#get_available_groups(refresh = false) ⇒ Object



34
35
36
37
38
39
40
41
42
43
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 34

def get_available_groups(refresh=false)
  if !@available_groups || refresh
    option_results = options_interface.options_for_source('groups',{})
    @available_groups = option_results['data'].collect {|it|
      {"id" => it["value"], "name" => it["name"], "value" => it["value"]}
    }
  end
  #puts "get_available_groups() rtn: #{@available_groups.inspect}"
  return @available_groups
end

#get_provision_type_for_zone_type(zone_type_id) ⇒ Object



247
248
249
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 247

def get_provision_type_for_zone_type(zone_type_id)
  @clouds_interface.cloud_type(zone_type_id)['zoneType']['provisionTypes'].first rescue nil
end

#get_static_environmentsObject



1329
1330
1331
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1329

def get_static_environments
  [{'name' => 'Dev', 'value' => 'dev'}, {'name' => 'Test', 'value' => 'qa'}, {'name' => 'Staging', 'value' => 'staging'}, {'name' => 'Production', 'value' => 'production'}]
end

#instance_types_interfaceObject



28
29
30
31
32
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 28

def instance_types_interface
  # @api_client.instance_types
  raise "#{self.class} has not defined @instance_types_interface" if @instance_types_interface.nil?
  @instance_types_interface
end

#instances_interfaceObject



16
17
18
19
20
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 16

def instances_interface
  # @api_client.instances
  raise "#{self.class} has not defined @instances_interface" if @instances_interface.nil?
  @instances_interface
end

#options_interfaceObject



22
23
24
25
26
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 22

def options_interface
  # @api_client.options
  raise "#{self.class} has not defined @options_interface" if @options_interface.nil?
  @options_interface
end

#prompt_evars(options = {}) ⇒ Object

Prompts user for environment variables for new instance returns array of evar objects null, name: “VAR”, value: “somevalue”



1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1157

def prompt_evars(options={})
  #puts "Configure Environment Variables:"
  no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))
  evars = []
  evar_index = 0
  has_another_evar = options[:options] && options[:options]["evar#{evar_index}"]
  add_another_evar = has_another_evar || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add an environment variable?", {default: false}))
  while add_another_evar do
    field_context = "evar#{evar_index}"
    evar = {}
    evar['id'] = nil
    evar_label = evar_index == 0 ? "ENV" : "ENV [#{evar_index+1}]"
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => "#{evar_label} Name", 'required' => true, 'description' => 'Environment Variable Name.', 'defaultValue' => evar['name']}], options[:options])
    evar['name'] = v_prompt[field_context]['name']
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'value', 'type' => 'text', 'fieldLabel' => "#{evar_label} Value", 'required' => true, 'description' => 'Environment Variable Value', 'defaultValue' => evar['value']}], options[:options])
    evar['value'] = v_prompt[field_context]['value']
    evars << evar
    evar_index += 1
    has_another_evar = options[:options] && options[:options]["evar#{evar_index}"]
    add_another_evar = has_another_evar || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add another environment variable?", {default: false}))
  end

  return evars
end

#prompt_instance_load_balancer(instance, default_lb_id, options) ⇒ Object

Prompts user for load balancer settings returns Hash of parameters like “-1”, etc



1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1243

def prompt_instance_load_balancer(instance, default_lb_id, options)
  #puts "Configure Environment Variables:"
  no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))
  payload = {}
  api_params = {}
  if instance['id']
    api_params['instanceId'] = instance['id']
  end
  if instance['zone']
    api_params['zoneId'] = instance['zone']['id']
  elsif instance['cloud']
    api_params['zoneId'] = instance['cloud']['id']
  end
  if instance['group']
    api_params['siteId'] = instance['group']['id']
  elsif instance['site']
    api_params['siteId'] = instance['site']['id']
  end
  if instance['plan']
    api_params['planId'] = instance['plan']['id']
  end
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'loadBalancerId', 'type' => 'select', 'fieldLabel' => "Load Balancer", 'optionSource' => 'loadBalancers', 'required' => true, 'description' => 'Select Load Balancer for instance', 'defaultValue' => default_lb_id || ''}], options[:options], api_client, api_params)
  lb_id = v_prompt['loadBalancerId']
  payload['loadBalancerId'] = lb_id

  # todo: finish implmenting this

  # loadBalancerId
  # loadBalancerProxyProtocol
  # loadBalancerName
  # loadBalancerDescription
  # loadBalancerSslCert
  # loadBalancerScheme
  
  return payload
end

#prompt_metadata(options = {}) ⇒ Object

Prompts user for environment variables for new instance returns array of metadata objects null, name: “MYTAG”, value: “myvalue”



1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1184

def (options={})
  #puts "Configure Environment Variables:"
  no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))
   = []
   = 0
   = options[:options] && options[:options]["metadata#{}"]
   =  || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add a metadata tag?", {default: false}))
  while  do
    field_context = "metadata#{}"
     = {}
    ['id'] = nil
     =  == 0 ? "Metadata Tag" : "Metadata Tag [#{+1}]"
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => "#{} Name", 'required' => true, 'description' => 'Metadata Tag Name.', 'defaultValue' => ['name']}], options[:options])
    # todo: metadata.type ?
    ['name'] = v_prompt[field_context]['name']
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'value', 'type' => 'text', 'fieldLabel' => "#{} Value", 'required' => true, 'description' => 'Metadata Tag Value', 'defaultValue' => ['value']}], options[:options])
    ['value'] = v_prompt[field_context]['value']
     << 
     += 1
     = options[:options] && options[:options]["metadata#{}"]
     =  || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add another metadata tag?", {default: false}))
  end

  return 
end

#prompt_network_interfaces(zone_id, provision_type_id, pool_id, options = {}) ⇒ Object

This recreates the behavior of multi_networks.js This is used by both ‘instances add` and `hosts add` returns array of networkInterfaces based on provision type and cloud settings



1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1041

def prompt_network_interfaces(zone_id, provision_type_id, pool_id, options={})
  #puts "Configure Networks:"
  no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))
  network_interfaces = []
  api_params = {zoneId: zone_id, provisionTypeId: provision_type_id}
  if pool_id.to_s =~ /\A\d{1,}\Z/
    api_params[:poolId] = pool_id 
  end
  zone_network_options_json = api_client.options.options_for_source('zoneNetworkOptions', api_params)
  # puts "zoneNetworkOptions JSON"
  # puts JSON.pretty_generate(zone_network_options_json)
  zone_network_data = zone_network_options_json['data'] || {}
  networks = zone_network_data['networks']
  network_groups = zone_network_data['networkGroups']
  if network_groups
    networks = network_groups + networks
  end
  network_interface_types = (zone_network_data['networkTypes'] || []).sort { |x,y| x['displayOrder'] <=> y['displayOrder'] }
  enable_network_type_selection = (zone_network_data['enableNetworkTypeSelection'] == 'on' || zone_network_data['enableNetworkTypeSelection'] == true)
  has_networks = zone_network_data["hasNetworks"] == true
  max_networks = (zone_network_data["maxNetworks"].to_i > 0) ? zone_network_data["maxNetworks"].to_i : nil

  # skip unless provision type supports networks
  if !has_networks
    return nil
  end

  # no networks available, shouldn't happen
  if networks.empty?
    return network_interfaces
  end

  network_options = []
  networks.each do |opt|
    if !opt.nil?
      network_options << {'name' => opt['name'], 'value' => opt['id']}
    end
  end

  network_interface_type_options = []
  network_interface_types.each do |opt|
    if !opt.nil?
      network_interface_type_options << {'name' => opt['name'], 'value' => opt['id']}
    end
  end

  interface_index = 0
  add_another_interface = true
  while add_another_interface do
    # if !no_prompt
    #   if interface_index == 0
    #     puts "Configure Network Interface"
    #   else
    #     puts "Configure Network Interface #{interface_index+1}"
    #   end
    # end

    field_context = interface_index == 0 ? "networkInterface" : "networkInterface#{interface_index+1}"
    network_interface = {}
    if options[:options] && options[:options]['networkInterfaces'] && options[:options]['networkInterfaces'][interface_index]
      network_interface = options[:options]['networkInterfaces'][interface_index]
    end

    # choose network
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'networkId', 'type' => 'select', 'fieldLabel' => "Network", 'selectOptions' => network_options, 'required' => true, 'skipSingleOption' => false, 'description' => 'Choose a network for this interface.', 'defaultValue' => network_interface['networkId']}], options[:options])
    network_interface['network'] = {}
    network_interface['network']['id'] = v_prompt[field_context]['networkId'].to_s
    selected_network = networks.find {|it| it["id"].to_s == network_interface['network']['id'] }

    if !selected_network
      print_red_alert "Network not found by id #{network_interface['network']['id']}!"
      exit 1
    end

    # choose network interface type
    if enable_network_type_selection && !network_interface_type_options.empty?
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'networkInterfaceTypeId', 'type' => 'select', 'fieldLabel' => "Network Interface Type", 'selectOptions' => network_interface_type_options, 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a network interface type.', 'defaultValue' => network_interface['networkInterfaceTypeId']}], options[:options])
      network_interface['networkInterfaceTypeId'] = v_prompt[field_context]['networkInterfaceTypeId'].to_i
    end

    # choose IP unless network has a pool configured
    ip_required = true
    if selected_network['id'].to_s.include?('networkGroup')
      #puts "IP Address: Using network group." if !no_prompt
      ip_required = false
    elsif selected_network['pool']
      #puts "IP Address: Using pool '#{selected_network['pool']['name']}'" if !no_prompt
      ip_required = false
    elsif selected_network['dhcpServer']
      #puts "IP Address: Using DHCP" if !no_prompt
      ip_required = false
    end
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'ipAddress', 'type' => 'text', 'fieldLabel' => "IP Address", 'required' => ip_required, 'description' => 'Enter an IP for this network interface. x.x.x.x', 'defaultValue' => network_interface['ipAddress']}], options[:options])
    if v_prompt[field_context] && !v_prompt[field_context]['ipAddress'].to_s.empty?
      network_interface['ipAddress'] = v_prompt[field_context]['ipAddress']
    end

    network_interfaces << network_interface
    interface_index += 1
    if options[:options] && options[:options]['networkInterfaces'] && options[:options]['networkInterfaces'][interface_index]
      add_another_interface = true
    elsif max_networks && network_interfaces.size >= max_networks
      add_another_interface = false
    else
      has_another_interface = options[:options] && options[:options]["networkInterface#{interface_index+1}"]
      add_another_interface = has_another_interface || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add another network interface?", {:default => false}))
    end

  end

  return network_interfaces

end

#prompt_new_instance(options = {}) ⇒ Object

prompts user for all the configuartion options for a particular instance returns payload of data for a new instance



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
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 253

def prompt_new_instance(options={})
  #puts "prompt_new_instance() #{options}"
  print reset # clear colors
  options[:options] ||= {}
  # Group
  group_id = nil
  group = options[:group] ? find_group_by_name_or_id_for_provisioning(options[:group]) : nil
  if group
    group_id = group["id"]
  else
    # print_red_alert "Group not found or specified!"
    # exit 1
    group_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'group', 'type' => 'select', 'fieldLabel' => 'Group', 'selectOptions' => get_available_groups(), 'required' => true, 'description' => 'Select Group.'}],options[:options],api_client,{})
    group_id = group_prompt['group']
  end

  # Cloud
  cloud_id = nil
  cloud = options[:cloud] ? find_cloud_by_name_or_id_for_provisioning(group_id, options[:cloud]) : nil
  if cloud
    cloud_id = cloud["id"]
  else
    # print_red_alert "Cloud not specified!"
    # exit 1
    available_clouds = get_available_clouds(group_id)
    cloud_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'cloud', 'type' => 'select', 'fieldLabel' => 'Cloud', 'selectOptions' => get_available_clouds(group_id), 'required' => true, 'description' => 'Select Cloud.', 'defaultValue' => options[:default_cloud] ? options[:default_cloud] : nil}],options[:options],api_client,{groupId: group_id})
    cloud_id = cloud_prompt['cloud']
    cloud = available_clouds.find {|it| it['id'] == cloud_id.to_i || it['name'] == cloud_id.to_s }
  end
  # Instance Type
  instance_type_code = nil
  if options[:instance_type_code]
    instance_type_code = options[:instance_type_code]
  else
    instance_type_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'type', 'type' => 'select', 'fieldLabel' => 'Type', 'optionSource' => 'instanceTypes', 'required' => true, 'description' => 'Select Instance Type.'}],options[:options],api_client,{groupId: group_id})
    instance_type_code = instance_type_prompt['type']
  end
  if instance_type_code.to_s =~ /\A\d{1,}\Z/
    instance_type = find_instance_type_by_id(instance_type_code)
  else
    instance_type = find_instance_type_by_code(instance_type_code)
  end
  exit 1 if !instance_type

  # Instance Name
  instance_name = nil
  if options[:instance_name]
    options[:options]['name'] = options[:instance_name]
  elsif options[:options]['instance'] && options[:options]['instance']['name']
    options[:options]['name'] = options[:options]['instance']['name']
  end
  name_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'name', 'fieldLabel' => 'Instance Name', 'type' => 'text', 'required' => options[:name_required]}], options[:options])
  instance_name = name_prompt['name']
  

  payload = {
    'zoneId' => cloud_id,
    # 'siteId' => siteId,
    'instance' => {
      'name' => instance_name,
      'cloud' => cloud['name'],
      'site' => {
        'id' => group_id
      },
      'type' => instance_type_code,
      'instanceType' => {
        'code' => instance_type_code
      }
    }
  }

  # allow arbitrary -O values passed by the user
  if options[:options]
    arbitrary_options = (options[:options] || {}).reject {|k,v| k.is_a?(Symbol) }
    # remove some things that are being prompted for
    arbitrary_options.delete('group')
    arbitrary_options.delete('cloud')
    arbitrary_options.delete('type')
    arbitrary_options.delete('name')
    arbitrary_options.delete('version')
    arbitrary_options.delete('layout')
    arbitrary_options.delete('servicePlan')
    arbitrary_options.delete('description')
    arbitrary_options.delete('environment')
    arbitrary_options.delete('instanceContext')
    arbitrary_options.delete('tags')
    payload.deep_merge!(arbitrary_options)
  end

  # Description
  if options[:description]
    options[:options]['description'] = options[:description]
  end
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'description', 'fieldLabel' => 'Description', 'type' => 'text', 'required' => false}], options[:options])
  payload['instance']['description'] = v_prompt['description'] if !v_prompt['description'].empty?

  # Environment
  if options[:environment]
    options[:options]['environment'] = options[:environment]
  elsif options[:options]['instanceContext'] && !options[:options]['environment']
    options[:options]['environment'] = options[:options]['instanceContext']
  end
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'environment', 'fieldLabel' => 'Environment', 'type' => 'select', 'required' => false, 'selectOptions' => get_available_environments()}], options[:options])
  payload['instance']['instanceContext'] = v_prompt['environment'] if !v_prompt['environment'].empty?

  # Tags
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'tags', 'fieldLabel' => 'Tags', 'type' => 'text', 'required' => false}], options[:options])
  payload['instance']['tags'] = v_prompt['tags'].split(',').collect {|it| it.to_s.strip }.compact.uniq if !v_prompt['tags'].empty?

  # Version and Layout

  available_versions = options_interface.options_for_source('instanceVersions',{groupId: group_id, cloudId: cloud_id, instanceTypeId: instance_type['id']})['data']
  default_version_value = payload['instance']['version'] ? payload['instance']['version'] : payload['version']
  default_layout_value = payload['instance']['layout'] ? payload['instance']['layout'] : payload['layout']
  if default_layout_value && default_layout_value.is_a?(Hash)
    default_layout_value = default_layout_value['id']
  end
  # JD: version is always nil because it is not stored in the blueprint or config !!
  # so for now, infer the version from the layout
  # requires api 3.6.2 to get "layouts" from /options/versions
  if default_layout_value && default_version_value.to_s.empty?
    available_versions.each do |available_version|
      if available_version["layouts"]
        selected_layout = available_version["layouts"].find {|it| it["value"].to_s == default_layout_value.to_s || it["id"].to_s == default_layout_value.to_s || it["code"].to_s == default_layout_value.to_s }
        if selected_layout
          default_version_value = available_version["value"]
          break
        end
      end
    end
  end

  # do not require version if a layout is passed
  version_value = default_version_value
  version_is_required = default_layout_value.nil?
  if default_layout_value.nil? && options[:options]["layout"].nil? && options[:always_prompt] != true
    #version_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'version', 'type' => 'select', 'fieldLabel' => 'Version', 'optionSource' => 'instanceVersions', 'required' => true, 'skipSingleOption' => true, 'autoPickOption' => true, 'description' => 'Select which version of the instance type to be provisioned.', 'defaultValue' => default_version_value}],options[:options],api_client,{groupId: group_id, cloudId: cloud_id, instanceTypeId: instance_type['id']})
    version_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'version', 'type' => 'select', 'fieldLabel' => 'Version', 'selectOptions' => available_versions, 'required' => version_is_required, 'skipSingleOption' => true, 'autoPickOption' => true, 'description' => 'Select which version of the instance type to be provisioned.', 'defaultValue' => default_version_value}],options[:options],api_client,{groupId: group_id, cloudId: cloud_id, instanceTypeId: instance_type['id']})
    version_value = version_prompt['version']
  end
  # JD: there is a bug here, the version needs to be passed perhaps? or the optionSource methods need updating...
  # could just allow for now ...
  # if options[:options]["layout"]
  #   layout_id = options[:options]["layout"]
  #   ...
  # end
  layout_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'layout', 'type' => 'select', 'fieldLabel' => 'Layout', 'optionSource' => 'layoutsForCloud', 'required' => true, 'description' => 'Select which configuration of the instance type to be provisioned.', 'defaultValue' => default_layout_value}],options[:options],api_client,{groupId: group_id, cloudId: cloud_id, instanceTypeId: instance_type['id'], version: version_value})
  layout_id = layout_prompt['layout']
  layout = instance_type['instanceTypeLayouts'].find{ |lt| lt['id'] == layout_id.to_i}
  if !layout
    print_red_alert "Layout not found by id #{layout_id}"
    exit 1
  end
  payload['instance']['layout'] = {'id' => layout['id']}

  # prompt for service plan
  service_plans_json = @instances_interface.service_plans({zoneId: cloud_id, layoutId: layout_id, siteId: group_id})
  service_plans = service_plans_json["plans"]
  service_plans_dropdown = service_plans.collect {|sp| {'name' => sp["name"], 'value' => sp["id"], 'code' => sp['code']} } # already sorted
  default_plan = nil
  if payload['plan']
    default_plan = payload['plan']
  elsif payload['instance'] && payload['instance']['plan']
    default_plan = payload['instance']['plan']
  end
  default_plan_value = default_plan.is_a?(Hash) ? default_plan['id'] : default_plan
  plan_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldName' => 'servicePlan', 'type' => 'select', 'fieldLabel' => 'Plan', 'selectOptions' => service_plans_dropdown, 'required' => true, 'description' => 'Choose the appropriately sized plan for this instance', 'defaultValue' => default_plan_value}],options[:options])
  plan_id = plan_prompt['servicePlan']
  service_plan = service_plans.find {|sp| sp["id"] == plan_id.to_i }
  if !service_plan
    print_red_alert "Plan not found by id #{plan_id}"
    exit 1
  end
  #todo: consolidate these, instances api looks for instance.plan.id and apps looks for plan.id
  payload['plan'] = {'id' => service_plan["id"], 'code' => service_plan["code"], 'name' => service_plan["name"]}
  payload['instance']['plan'] = {'id' => service_plan["id"], 'code' => service_plan["code"], 'name' => service_plan["name"]}

  # determine provision_type
  # provision_type = (layout && layout['provisionType'] ? layout['provisionType'] : nil) || get_provision_type_for_zone_type(cloud['zoneType']['id'])

  # build option types
  option_type_list = []
  if !layout['optionTypes'].nil? && !layout['optionTypes'].empty?
    option_type_list += layout['optionTypes']
  end
  if !instance_type['optionTypes'].nil? && !instance_type['optionTypes'].empty?
    option_type_list += instance_type['optionTypes']
  end
  if !layout['provisionType'].nil? && !layout['provisionType']['optionTypes'].nil? && !layout['provisionType']['optionTypes'].empty?
    option_type_list += layout['provisionType']['optionTypes']
  end
  if !payload['volumes'].empty?
    option_type_list = reject_volume_option_types(option_type_list)
  end
  # remove networkId option if networks were configured above
  if !payload['networkInterfaces'].empty?
    option_type_list = reject_networking_option_types(option_type_list)
  end

  # prompt for resource pool
  pool_id = nil
  resource_pool = nil
  has_zone_pools = layout["provisionType"] && layout["provisionType"]["id"] && layout["provisionType"]["hasZonePools"]
  if has_zone_pools
    # pluck out the resourcePoolId option type to prompt for
    resource_pool_option_type = option_type_list.find {|opt| ['resourcePool','resourcePoolId','azureResourceGroupId'].include?(opt['fieldName']) }
    option_type_list = option_type_list.reject {|opt| ['resourcePool','resourcePoolId','azureResourceGroupId'].include?(opt['fieldName']) }
    resource_pool_option_type ||= {'fieldContext' => 'config', 'fieldName' => 'resourcePoolId', 'type' => 'select', 'fieldLabel' => 'Resource Pool', 'optionSource' => 'zonePools', 'required' => true, 'skipSingleOption' => true, 'description' => 'Select resource pool.'}
    resource_pool_prompt = Morpheus::Cli::OptionTypes.prompt([resource_pool_option_type],options[:options],api_client,{groupId: group_id, siteId: group_id, zoneId: cloud_id, cloudId: cloud_id, instanceTypeId: instance_type['id'], planId: service_plan["id"], layoutId: layout["id"]})
    resource_pool_prompt.deep_compact!
    payload.deep_merge!(resource_pool_prompt)
    resource_pool = Morpheus::Cli::OptionTypes.get_last_select()
    if resource_pool_option_type['fieldContext'] && resource_pool_prompt[resource_pool_option_type['fieldContext']]
      pool_id = resource_pool_prompt[resource_pool_option_type['fieldContext']][resource_pool_option_type['fieldName']]
    elsif resource_pool_prompt[resource_pool_option_type['fieldName']]
      pool_id = resource_pool_prompt[resource_pool_option_type['fieldName']]
    end
  end

  # remove host selection for kubernetes
  if resource_pool && resource_pool['providerType'] == 'kubernetes'
    option_type_list = option_type_list.reject {|opt|
      ['provisionServerId'].include?(opt['fieldName'])
    }
  end

  # plan_info has this property already..
  # has_datastore = layout["provisionType"] && layout["provisionType"]["id"] && layout["provisionType"]["hasDatastore"]
  # service_plan['hasDatastore'] = has_datastore

  # prompt for volumes
  # if payload['volumes'].nil?
    volumes = prompt_volumes(service_plan, options, api_client, {zoneId: cloud_id, layoutId: layout_id, siteId: group_id})
    if !volumes.empty?
      payload['volumes'] = volumes
    end
  # end

  # if payload['networkInterfaces'].nil?
    if layout["provisionType"] && layout["provisionType"]["id"] && layout["provisionType"]["hasNetworks"]
      # prompt for network interfaces (if supported)
      begin
        network_interfaces = prompt_network_interfaces(cloud_id, layout["provisionType"]["id"], pool_id, options)
        if !network_interfaces.empty?
          payload['networkInterfaces'] = network_interfaces
        end
      rescue RestClient::Exception => e
        print yellow,"Unable to load network options. Proceeding...",reset,"\n"
        print_rest_exception(e, options) if Morpheus::Logging.debug?
      end
    end
  # end

  # Security Groups
  # prompt for multiple security groups
  sg_option_type = option_type_list.find {|opt| ((opt['code'] == 'provisionType.amazon.securityId') || (opt['name'] == 'securityId')) }
  option_type_list = option_type_list.reject {|opt| ((opt['code'] == 'provisionType.amazon.securityId') || (opt['name'] == 'securityId')) }
  # ok.. seed data has changed and serverTypes do not have this optionType anymore...
  if sg_option_type.nil?
    if layout["provisionType"] && (layout["provisionType"]["code"] == 'amazon')
      sg_option_type = {'fieldContext' => 'config', 'fieldName' => 'securityId', 'type' => 'select', 'fieldLabel' => 'Security Group', 'optionSource' => 'amazonSecurityGroup', 'required' => true, 'description' => 'Select security group.'}
    end
  end
  has_security_groups = !!sg_option_type
  if options[:security_groups]
    payload['securityGroups'] = options[:security_groups].collect {|sg_id| {'id' => sg_id} }
  else
    if has_security_groups
      security_groups_array = prompt_security_groups(sg_option_type, {zoneId: cloud_id, poolId: pool_id}, options)
      if !security_groups_array.empty?
        payload['securityGroups'] = security_groups_array.collect {|sg_id| {'id' => sg_id} }
      end
    end
  end


  # prompt for option types
  api_params = {groupId: group_id, cloudId: cloud_id, zoneId: cloud_id, instanceTypeId: instance_type['id'], version: version_value}
  api_params['config'] = payload['config'] if payload['config']
  api_params['poolId'] = payload['config']['resourcePoolId'] if payload['config'] && payload['config']['resourcePoolId']

  instance_config_payload = Morpheus::Cli::OptionTypes.prompt(option_type_list, options[:options], @api_client, api_params)
  payload.deep_merge!(instance_config_payload)

  ## Advanced Options

  # scale factor

  # prompt for environment variables
  evars = prompt_evars(options)
  if !evars.empty?
    payload['evars'] = evars
  end

  # prompt for metadata variables
   = (options)
  if !.empty?
    payload['metadata'] = 
  end

  return payload
end

#prompt_resize_volumes(current_volumes, plan_info, options = {}) ⇒ Object

This recreates the behavior of multi_disk.js returns array of volumes based on service plan options (plan_info)



763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 763

def prompt_resize_volumes(current_volumes, plan_info, options={})
#puts "Configure Volumes:"
no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))

current_root_volume = current_volumes[0]

volumes = []

plan_size = nil
if plan_info['maxStorage']
  plan_size = plan_info['maxStorage'].to_i / (1024 * 1024 * 1024)
end

root_storage_types = []
if plan_info['rootStorageTypes']
  plan_info['rootStorageTypes'].each do |opt|
    if !opt.nil?
      root_storage_types << {'name' => opt['name'], 'value' => opt['id']}
    end
  end
end

storage_types = []
if plan_info['storageTypes']
  plan_info['storageTypes'].each do |opt|
    if !opt.nil?
      storage_types << {'name' => opt['name'], 'value' => opt['id']}
    end
  end
end

datastore_options = []
if plan_info['supportsAutoDatastore']
  if plan_info['autoOptions']
    plan_info['autoOptions'].each do |opt|
      if !opt.nil?
        datastore_options << {'name' => opt['name'], 'value' => opt['id']}
      end
    end
  end
end
if plan_info['datastores']
  plan_info['datastores'].each do |k, v|
    v.each do |opt|
      if !opt.nil?
        datastore_options << {'name' => "#{k}: #{opt['name']}", 'value' => opt['id']}
      end
    end
  end
end

#puts "Configure Root Volume"

field_context = "rootVolume"

if root_storage_types.empty?
  # this means there's no configuration, just send a single root volume to the server
  storage_type_id = nil
  storage_type = nil
else
  #v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => 'Root Storage Type', 'selectOptions' => root_storage_types, 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.'}], options[:options])
  #storage_type_id = v_prompt[field_context]['storageType']
  storage_type_id = current_root_volume['type'] || current_root_volume['storageType']
  storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }
end

# sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form
root_custom_size_options = []
if plan_info['rootCustomSizeOptions'] && plan_info['rootCustomSizeOptions'][storage_type_id.to_s]
  plan_info['rootCustomSizeOptions'][storage_type_id.to_s].each do |opt|
    if !opt.nil?
      root_custom_size_options << {'name' => opt['value'], 'value' => opt['key']}
    end
  end
end

volume = {
  'id' => current_root_volume['id'],
  'rootVolume' => true,
  'name' => current_root_volume['name'],
  'size' => current_root_volume['size'] > plan_size ? current_root_volume['size'] : plan_size,
  'sizeId' => nil,
  'storageType' => storage_type_id,
  'datastoreId' => current_root_volume['datastoreId']
}

if plan_info['rootDiskCustomizable'] && storage_type && storage_type['customLabel']
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Root Volume Label', 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume['name']}], options[:options])
  volume['name'] = v_prompt[field_context]['name']
end
if plan_info['rootDiskCustomizable'] && storage_type && storage_type['customSize']
  if root_custom_size_options.empty?
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => 'Root Volume Size (GB)', 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => volume['size']}], options[:options])
    volume['size'] = v_prompt[field_context]['size']
    volume['sizeId'] = nil #volume.delete('sizeId')
  else
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => 'Root Volume Size', 'selectOptions' => root_custom_size_options, 'required' => true, 'description' => 'Choose a volume size.'}], options[:options])
    volume['sizeId'] = v_prompt[field_context]['sizeId']
    volume['size'] = nil #volume.delete('size')
  end
else
  # might need different logic here ? =o
  volume['size'] = plan_size
  volume['sizeId'] = nil #volume.delete('sizeId')
end
# if !datastore_options.empty?
#   v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => 'Root Datastore', 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.'}], options[:options])
#   volume['datastoreId'] = v_prompt[field_context]['datastoreId']
# end

volumes << volume

# modify or delete existing data volumes
(1..(current_volumes.size-1)).each do |volume_index|
  current_volume = current_volumes[volume_index]
  if current_volume

    field_context = "dataVolume#{volume_index}"

    if no_prompt
      volume_action = 'keep'
    else
      action_options = [{'name' => 'Modify', 'value' => 'modify'}, {'name' => 'Keep', 'value' => 'keep'}, {'name' => 'Delete', 'value' => 'delete'}]
      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'action', 'type' => 'select', 'fieldLabel' => "Modify/Keep/Delete volume '#{current_volume['name']}'", 'selectOptions' => action_options, 'required' => true, 'description' => 'Modify, Keep or Delete existing data volume?'}], options[:options])
      volume_action = v_prompt[field_context]['action']
    end

    if volume_action == 'delete'
      # deleted volume is just excluded from post params
      next
    elsif volume_action == 'keep'
      volume = {
        'id' => current_volume['id'].to_i,
        'rootVolume' => false,
        'name' => current_volume['name'],
        'size' => current_volume['size'] > plan_size ? current_volume['size'] : plan_size,
        'sizeId' => nil,
        'storageType' => (current_volume['type'] || current_volume['storageType']),
        'datastoreId' => current_volume['datastoreId']
      }
      volumes << volume
    else
      # v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => "Disk #{volume_index} Storage Type", 'selectOptions' => storage_types, 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.'}], options[:options])
      # storage_type_id = v_prompt[field_context]['storageType']
      storage_type_id = current_volume['type'] || current_volume['storageType']
      storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }
      # sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form
      custom_size_options = []
      if plan_info['customSizeOptions'] && plan_info['customSizeOptions'][storage_type_id.to_s]
        plan_info['customSizeOptions'][storage_type_id.to_s].each do |opt|
          if !opt.nil?
            custom_size_options << {'name' => opt['value'], 'value' => opt['key']}
          end
        end
      end

      volume = {
        'id' => current_volume['id'].to_i,
        'rootVolume' => false,
        'name' => current_volume['name'],
        'size' => current_volume['size'] > plan_size ? current_volume['size'] : plan_size,
        'sizeId' => nil,
        'storageType' => (current_volume['type'] || current_volume['storageType']),
        'datastoreId' => current_volume['datastoreId']
      }

      if plan_info['customizeVolume'] && storage_type['customLabel']
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => "Disk #{volume_index} Volume Label", 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume['name']}], options[:options])
        volume['name'] = v_prompt[field_context]['name']
      end
      if plan_info['customizeVolume'] && storage_type['customSize']
        if custom_size_options.empty?
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => "Disk #{volume_index} Volume Size (GB)", 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => volume['size']}], options[:options])
          volume['size'] = v_prompt[field_context]['size']
          volume['sizeId'] = nil #volume.delete('sizeId')
        else
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => "Disk #{volume_index} Volume Size", 'selectOptions' => custom_size_options, 'required' => true, 'description' => 'Choose a volume size.'}], options[:options])
          volume['sizeId'] = v_prompt[field_context]['sizeId']
          volume['size'] = nil #volume.delete('size')
        end
      else
        # might need different logic here ? =o
        volume['size'] = plan_size
        volume['sizeId'] = nil #volume.delete('sizeId')
      end
      # if !datastore_options.empty?
      #   v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => "Disk #{volume_index} Datastore", 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.'}], options[:options])
      #   volume['datastoreId'] = v_prompt[field_context]['datastoreId']
      # end

      volumes << volume

    end

  end
end


if plan_info['addVolumes']
  volume_index = current_volumes.size
  has_another_volume = options[:options] && options[:options]["dataVolume#{volume_index}"]
  add_another_volume = has_another_volume || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add data volume?"))
  while add_another_volume do
      #puts "Configure Data #{volume_index} Volume"

      field_context = "dataVolume#{volume_index}"

      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => "Disk #{volume_index} Storage Type", 'selectOptions' => storage_types, 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.'}], options[:options])
      storage_type_id = v_prompt[field_context]['storageType']
      storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }

      # sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form
      custom_size_options = []
      if plan_info['customSizeOptions'] && plan_info['customSizeOptions'][storage_type_id.to_s]
        plan_info['customSizeOptions'][storage_type_id.to_s].each do |opt|
          if !opt.nil?
            custom_size_options << {'name' => opt['value'], 'value' => opt['key']}
          end
        end
      end

      volume_label = (volume_index == 1 ? 'data' : "data #{volume_index}")
      volume = {
        'id' => -1,
        'rootVolume' => false,
        'name' => volume_label,
        'size' => plan_size,
        'sizeId' => nil,
        'storageType' => storage_type_id,
        'datastoreId' => nil
      }

      if plan_info['customizeVolume'] && storage_type['customLabel']
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => "Disk #{volume_index} Volume Label", 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume_label}], options[:options])
        volume['name'] = v_prompt[field_context]['name']
      end
      if plan_info['customizeVolume'] && storage_type['customSize']
        if custom_size_options.empty?
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => "Disk #{volume_index} Volume Size (GB)", 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => plan_size}], options[:options])
          volume['size'] = v_prompt[field_context]['size']
          volume['sizeId'] = nil #volume.delete('sizeId')
        else
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => "Disk #{volume_index} Volume Size", 'selectOptions' => custom_size_options, 'required' => true, 'description' => 'Choose a volume size.'}], options[:options])
          volume['sizeId'] = v_prompt[field_context]['sizeId']
          volume['size'] = nil #volume.delete('size')
        end
      else
        # might need different logic here ? =o
        volume['size'] = plan_size
        volume['sizeId'] = nil #volume.delete('sizeId')
      end
      if !datastore_options.empty?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => "Disk #{volume_index} Datastore", 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.'}], options[:options])
        volume['datastoreId'] = v_prompt[field_context]['datastoreId']
      end

      volumes << volume

      # todo: should maxDisk check consider the root volume too?
      if plan_info['maxDisk'] && volume_index >= plan_info['maxDisk']
        add_another_volume = false
      else
        volume_index += 1
        has_another_volume = options[:options] && options[:options]["dataVolume#{volume_index}"]
        add_another_volume = has_another_volume || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add another data volume?"))
      end

    end

  end

  return volumes
end

#prompt_security_groups(sg_option_type, api_params, options) ⇒ Object



1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1210

def prompt_security_groups(sg_option_type, api_params, options)
  no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))
  security_groups_array = []

  sg_required = sg_option_type['required']
  sg_index = 0
  add_another_sg = sg_required || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add a security group?", {default: false}))
  while add_another_sg do
    cur_sg_option_type = sg_option_type.merge({'required' => (sg_index == 0 ? sg_required : false)})
    field_context = cur_sg_option_type['fieldContext']
    field_name = cur_sg_option_type['fieldName']
    v_prompt = Morpheus::Cli::OptionTypes.prompt([cur_sg_option_type], options[:options], api_client, api_params)
    has_another_sg = false
    if field_context
      if v_prompt[field_context] && !v_prompt[field_context][field_name].to_s.empty?
        security_groups_array << v_prompt[field_context][field_name]
      end
      has_another_sg = options[:options] && options[:options][field_context] && options[:options][field_context]["#{field_name}#{sg_index+2}"]
    else
      if !v_prompt[field_name].to_s.empty?
        security_groups_array << v_prompt[field_name]
      end
      has_another_sg = options[:options] && options[:options]["#{field_name}#{sg_index+2}"]
    end
    add_another_sg = has_another_sg || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add another security group?", {default: false}))
    sg_index += 1
  end

  return security_groups_array
end

#prompt_volumes(plan_info, options = {}, api_client = nil, api_params = {}) ⇒ Object

This recreates the behavior of multi_disk.js returns array of volumes based on service plan options (plan_info)



558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 558

def prompt_volumes(plan_info, options={}, api_client=nil, api_params={})
#puts "Configure Volumes:"
no_prompt = (options[:no_prompt] || (options[:options] && options[:options][:no_prompt]))

volumes = []

plan_size = nil
if plan_info['maxStorage']
  plan_size = plan_info['maxStorage'].to_i / (1024 * 1024 * 1024)
end
root_storage_types = []
if plan_info['rootStorageTypes']
  plan_info['rootStorageTypes'].sort {|x,y| x['displayOrder'] <=> y['displayOrder'] }.each do |opt|
    if !opt.nil?
      root_storage_types << {'name' => opt['name'], 'value' => opt['id']}
    end
  end
end

storage_types = []
if plan_info['storageTypes']
  plan_info['storageTypes'].sort {|x,y| x['displayOrder'] <=> y['displayOrder'] }.each do |opt|
    if !opt.nil?
      storage_types << {'name' => opt['name'], 'value' => opt['id']}
    end
  end
end

datastore_options = []
if plan_info['supportsAutoDatastore']
  if plan_info['autoOptions']
    plan_info['autoOptions'].each do |opt|
      if !opt.nil?
        datastore_options << {'name' => opt['name'], 'value' => opt['id']}
      end
    end
  end
end
if plan_info['datastores']
  plan_info['datastores'].each do |k, v|
    v.each do |opt|
      if !opt.nil?
        datastore_options << {'name' => "#{k}: #{opt['name']}", 'value' => opt['id']}
      end
    end
  end
end
# api does not always return datastores, so go get them if needed..
if plan_info['hasDatastore'] && datastore_options.empty?
  option_results = options_interface.options_for_source('datastores', api_params)
  option_results['data'].each do |it|
      datastore_options << {"id" => it["value"] || it["id"], "name" => it["name"], "value" => it["value"] || it["id"]}
  end
end

#puts "Configure Root Volume"

field_context = "rootVolume"

volume_label = 'root'
volume = {
  'id' => -1,
  'rootVolume' => true,
  'name' => volume_label,
  'size' => plan_size,
  'sizeId' => nil,
  'storageType' => nil,
  'datastoreId' => nil
}
if options[:options] && options[:options]['volumes'] && options[:options]['volumes'][0]
  volume = options[:options]['volumes'][0]
end

if root_storage_types.empty?
  # this means there's no configuration, just send a single root volume to the server
  storage_type_id = nil
  storage_type = nil
else
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => 'Root Storage Type', 'selectOptions' => root_storage_types, 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.', 'defaultValue' => volume['storageType']}], options[:options])
  storage_type_id = v_prompt[field_context]['storageType']
  storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }
  volume['storageType'] = storage_type_id
end

# sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form
root_custom_size_options = []
if plan_info['rootCustomSizeOptions'] && plan_info['rootCustomSizeOptions'][storage_type_id.to_s]
  plan_info['rootCustomSizeOptions'][storage_type_id.to_s].each do |opt|
    if !opt.nil?
      root_custom_size_options << {'name' => opt['value'], 'value' => opt['key']}
    end
  end
end

if plan_info['rootDiskCustomizable'] && storage_type && storage_type['customLabel']
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => 'Root Volume Label', 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume['name']}], options[:options])
  volume['name'] = v_prompt[field_context]['name']
end
if plan_info['rootDiskCustomizable'] && storage_type && storage_type['customSize']
  if root_custom_size_options.empty?
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => 'Root Volume Size (GB)', 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => volume['size']}], options[:options])
    volume['size'] = v_prompt[field_context]['size']
    volume['sizeId'] = nil #volume.delete('sizeId')
  else
    v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => 'Root Volume Size', 'selectOptions' => root_custom_size_options, 'required' => true, 'description' => 'Choose a volume size.', 'defaultValue' => volume['sizeId']}], options[:options])
    volume['sizeId'] = v_prompt[field_context]['sizeId']
    volume['size'] = nil #volume.delete('size')
  end
else
  # might need different logic here ? =o
  #volume['size'] = plan_size
  #volume['sizeId'] = nil #volume.delete('sizeId')
end
if !datastore_options.empty?
  v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => 'Root Datastore', 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.', 'defaultValue' => volume['datastoreId']}], options[:options])
  volume['datastoreId'] = v_prompt[field_context]['datastoreId']
end

volumes << volume

if plan_info['addVolumes']
  volume_index = 1
  has_another_volume = (options[:options] && options[:options]["dataVolume#{volume_index}"]) || (options[:options] && options[:options]['volumes'] && options[:options]['volumes'][volume_index])
  add_another_volume = has_another_volume || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add data volume?", {:default => (options[:defaultAddFirstDataVolume] == true && volume_index == 1)}))
  while add_another_volume do
      #puts "Configure Data #{volume_index} Volume"

      field_context = "dataVolume#{volume_index}"

      volume_label = (volume_index == 1 ? 'data' : "data #{volume_index}")
      volume = {
        #'id' => -1,
        'rootVolume' => false,
        'name' => volume_label,
        'size' => plan_size,
        'sizeId' => nil,
        'storageType' => nil,
        'datastoreId' => nil
      }
      if options[:options] && options[:options]['volumes'] && options[:options]['volumes'][volume_index]
        volume = options[:options]['volumes'][volume_index]
      end

      v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'storageType', 'type' => 'select', 'fieldLabel' => "Disk #{volume_index} Storage Type", 'selectOptions' => storage_types, 'required' => true, 'skipSingleOption' => true, 'description' => 'Choose a storage type.', 'defaultValue' => volume['storageType']}], options[:options])
      storage_type_id = v_prompt[field_context]['storageType']
      volume['storageType'] = storage_type_id
      storage_type = plan_info['storageTypes'].find {|i| i['id'] == storage_type_id.to_i }

      # sometimes the user chooses sizeId from a list of size options (AccountPrice) and other times it is free form
      custom_size_options = []
      if plan_info['customSizeOptions'] && plan_info['customSizeOptions'][storage_type_id.to_s]
        plan_info['customSizeOptions'][storage_type_id.to_s].each do |opt|
          if !opt.nil?
            custom_size_options << {'name' => opt['value'], 'value' => opt['key']}
          end
        end
      end

      if plan_info['customizeVolume'] && storage_type['customLabel']
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'name', 'type' => 'text', 'fieldLabel' => "Disk #{volume_index} Volume Label", 'required' => true, 'description' => 'Enter a volume label.', 'defaultValue' => volume['name']}], options[:options])
        volume['name'] = v_prompt[field_context]['name']
      end
      if plan_info['customizeVolume'] && storage_type['customSize']
        if custom_size_options.empty?
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'size', 'type' => 'number', 'fieldLabel' => "Disk #{volume_index} Volume Size (GB)", 'required' => true, 'description' => 'Enter a volume size (GB).', 'defaultValue' => volume['size']}], options[:options])
          volume['size'] = v_prompt[field_context]['size']
          volume['sizeId'] = nil #volume.delete('sizeId')
        else
          v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'sizeId', 'type' => 'select', 'fieldLabel' => "Disk #{volume_index} Volume Size", 'selectOptions' => custom_size_options, 'required' => true, 'description' => 'Choose a volume size.', 'defaultValue' => volume['sizeId']}], options[:options])
          volume['sizeId'] = v_prompt[field_context]['sizeId']
          volume['size'] = nil #volume.delete('size')
        end
      else
        # might need different logic here ? =o
        volume['size'] = plan_size
        volume['sizeId'] = nil #volume.delete('sizeId')
      end
      if !datastore_options.empty?
        v_prompt = Morpheus::Cli::OptionTypes.prompt([{'fieldContext' => field_context, 'fieldName' => 'datastoreId', 'type' => 'select', 'fieldLabel' => "Disk #{volume_index} Datastore", 'selectOptions' => datastore_options, 'required' => true, 'description' => 'Choose a datastore.', 'defaultValue' => volume['datastoreId']}], options[:options])
        volume['datastoreId'] = v_prompt[field_context]['datastoreId']
      end

      volumes << volume

      volume_index += 1
      if options[:options] && options[:options]['volumes'] && options[:options]['volumes'][volume_index]
        add_another_volume = true
      elsif plan_info['maxDisk'] && volume_index >= plan_info['maxDisk']
        # todo: should maxDisk check consider the root volume too?
        add_another_volume = false
      else
        has_another_volume = options[:options] && options[:options]["dataVolume#{volume_index}"]
        add_another_volume = has_another_volume || (!no_prompt && Morpheus::Cli::OptionTypes.confirm("Add another data volume?", {:default => false}))
      end

    end

  end

  return volumes
end

#reject_networking_option_types(option_types) ⇒ Object

reject old networking option types these will eventually get removed from the associated optionTypes



1293
1294
1295
1296
1297
1298
1299
1300
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1293

def reject_networking_option_types(option_types)
  option_types.reject {|opt|
    ['networkId', 'networkType', 'ipAddress', 'netmask', 'gateway', 'nameservers',
     'vmwareNetworkType', 'vmwareIpAddress', 'vmwareNetmask', 'vmwareGateway', 'vmwareNameservers',
     'subnetId'
     ].include?(opt['fieldName'])
  }
end

#reject_service_plan_option_types(option_types) ⇒ Object

reject old option types that now come from the selected service plan these will eventually get removed from the associated optionTypes



1304
1305
1306
1307
1308
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1304

def reject_service_plan_option_types(option_types)
  option_types.reject {|opt|
    ['cpuCount', 'memorySize', 'memory'].include?(opt['fieldName'])
  }
end

#reject_volume_option_types(option_types) ⇒ Object

reject old volume option types these will eventually get removed from the associated optionTypes



1282
1283
1284
1285
1286
1287
1288
1289
# File 'lib/morpheus/cli/mixins/provisioning_helper.rb', line 1282

def reject_volume_option_types(option_types)
  option_types.reject {|opt|
    ['osDiskSize', 'osDiskType',
     'diskSize', 'diskType',
     'datastoreId', 'storagePodId'
     ].include?(opt['fieldName'])
  }
end