Class: Chef::Provisioning::AzureRM::Driver

Inherits:
Driver
  • Object
show all
Defined in:
lib/chef/provisioning/azurerm/driver.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(driver_url, config) ⇒ Driver

Returns a new instance of Driver.



57
58
59
60
61
62
63
64
65
66
# File 'lib/chef/provisioning/azurerm/driver.rb', line 57

def initialize(driver_url, config)
  super
  scheme, subscription_id = driver_url.split(":", 2)
  self.subscription_id = subscription_id
  @subscription = Credentials.new.azure_credentials_for_subscription(subscription_id)
  if !subscription
    raise "Driver #{driver_url} has a subscription ID, but the system has no credentials configured for it!  If you have access to this subscription, you can use `azure account download` and `azure account import` in the Azure CLI to get the credentials, or set azure_subscriptions to [ { subscription_id: '...', management_credentials: ... }] in your Chef configuration."
  end
  Chef::Config.chef_provisioning ||= {}
end

Instance Attribute Details

#regionObject (readonly)

Returns the value of attribute region.



29
30
31
# File 'lib/chef/provisioning/azurerm/driver.rb', line 29

def region
  @region
end

#subscriptionObject (readonly)

Returns the value of attribute subscription.



68
69
70
# File 'lib/chef/provisioning/azurerm/driver.rb', line 68

def subscription
  @subscription
end

#subscription_idObject

Returns the value of attribute subscription_id.



69
70
71
# File 'lib/chef/provisioning/azurerm/driver.rb', line 69

def subscription_id
  @subscription_id
end

Class Method Details

.canonicalize_url(driver_url, config) ⇒ Object



40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/chef/provisioning/azurerm/driver.rb', line 40

def self.canonicalize_url(driver_url, config)
  scheme,  = driver_url.split(":", 2)
  if .nil? || .empty?
    subscription = Credentials.new
    subscription.azure_credentials_for_subscription(subscription_id)
    if !subscription
      raise "Driver #{driver_url} did not specify a subscription ID, and no default subscription was found.  Have you downloaded the Azure CLI and used `azure account download` and `azure account import` to set up Azure?  Alternately, you can set azure_subscriptions to [ { subscription_id: '...', management_credentials: ... }] in your Chef configuration."
    end
    config = Cheffish::MergedConfig.new({ azure_subscriptions: subscription }, config)
  end
  if subscription
    [ "#{scheme}:#{subscription[:subscription_id]}", config ]
  else
    [ driver_url, config]
  end
end

.from_url(driver_url, config) ⇒ AzureDriver

Construct an AzureDriver object from a URL - used to parse existing URL data to hydrate a driver object. URL scheme: azure:subscription_id

Returns:

  • (AzureDriver)

    A chef-provisioning Azure driver object for the given URL



36
37
38
# File 'lib/chef/provisioning/azurerm/driver.rb', line 36

def self.from_url(driver_url, config)
  Driver.new(driver_url, config)
end

Instance Method Details

#allocate_machine(action_handler, machine_spec, machine_options) ⇒ Object

Allocate a new machine with the Azure API and start it up, without blocking to wait for it. Creates any needed resources to get a machine up and running.



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
# File 'lib/chef/provisioning/azurerm/driver.rb', line 89

def allocate_machine(action_handler, machine_spec, machine_options)
  existing_vm = vm_for(machine_spec)

  # We don't need to do anything if the existing VM is found
  return if existing_vm

  bootstrap_options = (machine_options[:bootstrap_options] || {}).dup
  vm_name = machine_spec.name
  location = bootstrap_options[:location] || machine_options[:location]
  resource_group_name = bootstrap_options[:resource_group_name]
  availability_set = bootstrap_options[:availability_set]
  osProfile = bootstrap_options[:osProfile]
  network_security_group_name = bootstrap_options[:network_security_group_name]
  tags = bootstrap_options[:tags]
  raise "location not provided, where the virtual machine should be created" unless location
  raise "resource_group_name not provided, where the virtual machine should be created" unless resource_group_name
  raise "osProfile properties not provided in bootstrap_options" unless osProfile
  computerName = osProfile[:computerName]
  adminPassword = osProfile[:adminPassword]
  adminUsername = osProfile[:adminUsername]
  linuxConfiguration = osProfile[:linuxConfiguration]
  raise "adminUsername under osProfile properties not provided in bootstrap_options" unless adminUsername

  Chef::Log.debug "Azure machine_options: #{machine_options.inspect}"
  action_handler.report_progress "Creating #{machine_spec.name} in #{location} with supplied parameters..."

  if availability_set
    action_handler.report_progress "Looking for availability_set #{availability_set}."
    availability_set_id = azure_vm_service.availability_sets.get(resource_group_name, availability_set).id
    raise "availability_set #{availability_set}  under resource group #{resource_group_name} was not found." unless availability_set_id
    availabilitySet = MsRestAzure::SubResource.new.tap do |subResource|
      subResource.id = availability_set_id
    end
  end

  action_handler.report_progress "Preparing OS disk for the VM #{vm_name}..."
  begin
    os_disk_exist = azure_vm_service.disks.get(resource_group_name, "#{vm_name}_os_disk")
  rescue MsRestAzure::AzureOperationError
    os_disk_exist = nil
  end
  if os_disk_exist
    action_handler.report_progress "OS disk with the name #{vm_name}_os_disk already exist."
    action_handler.report_progress "checking attached status..."
    if os_disk_exist.owner_id.nil?
      action_handler.report_progress "OS disk #{vm_name} not attached to any VM. Using this..."
      os_disk = Azure::ARM::Compute::Models::OSDisk.new.tap do |os_disk|
        os_disk.create_option = 'attach'
        os_disk.os_type = machine_spec.reference['is_windows'] ? 'Windows' : 'Linux'
        os_disk.managed_disk = Azure::ARM::Compute::Models::ManagedDiskParameters.new.tap do |managedDisk|
          managedDisk.id = os_disk_exist.id
        end
      end
    else
      raise "OS disk #{vm_name} attached to a VM. Contact your cloud administrator or change VM name."
    end
  else
    os_disk = Azure::ARM::Compute::Models::OSDisk.new.tap do |os_disk|
      os_disk.name = "#{vm_name}_os_disk"
      os_disk.create_option = Azure::ARM::Compute::Models::DiskCreateOptionTypes::FromImage
      os_disk.managed_disk = Azure::ARM::Compute::Models::ManagedDiskParameters.new.tap do |managedDisk|
        managedDisk. = bootstrap_options[:storageProfile][:storage_account_type]
      end
    end
  end

  begin
    subnet = azure_net_service.subnets.get(resource_group_name, bootstrap_options[:virtual_network_name], bootstrap_options[:subnet_name])
  rescue MsRestAzure::AzureOperationError => e
    raise e.message
  end
  action_handler.report_progress "Creating a network interface for the VM #{vm_name}"
  begin
    nic_exist = azure_net_service.network_interfaces.get(resource_group_name, vm_name)
  rescue MsRestAzure::AzureOperationError
    nic_exist = nil
  end
  if nic_exist
    action_handler.report_progress "network interface with the name #{vm_name} already exist."
    action_handler.report_progress "checking attached status..."
    if nic_exist.virtual_machine.nil?
      action_handler.report_progress "network interface #{vm_name} not attached to any VM. Using this..."
      nic = nic_exist
    else
      raise "network interface #{vm_name} attached to a VM. Contact your cloud administrator or change VM name."
    end
  else
    begin
      network_security_group = azure_net_service.network_security_groups.get(resource_group_name, network_security_group_name) if network_security_group_name
    rescue MsRestAzure::AzureOperationError => e
      raise e.message
    end
    nic = azure_net_service.network_interfaces.create_or_update(
      resource_group_name,
      vm_name,
      Azure::ARM::Network::Models::NetworkInterface.new.tap do |interface|
        interface.location = location
        interface.network_security_group = network_security_group if network_security_group_name
        interface.ip_configurations = [
          Azure::ARM::Network::Models::NetworkInterfaceIPConfiguration.new.tap do |nic_conf|
            nic_conf.name = vm_name
            nic_conf.private_ipallocation_method = Azure::ARM::Network::Models::IPAllocationMethod::Dynamic
            nic_conf.subnet = subnet
          end
        ]
      end
      )
  end

  vm_create_params = Azure::ARM::Compute::Models::VirtualMachine.new.tap do |vm|
    vm.location = location
    vm.availability_set = availabilitySet if availability_set && availability_set_id
    vm.tags = tags if tags
    vm.os_profile = Azure::ARM::Compute::Models::OSProfile.new.tap do |os_profile|
      os_profile.computer_name = computerName if computerName
      os_profile.admin_username = adminUsername
      os_profile.admin_password = adminPassword if adminPassword
      os_profile.linux_configuration = Azure::ARM::Compute::Models::LinuxConfiguration.new.tap do |linux|
        linux.disable_password_authentication = linuxConfiguration[:disablePasswordAuthentication].nil? ? true : linuxConfiguration[:disablePasswordAuthentication]
        if ssh = linuxConfiguration[:ssh]
          linux.ssh = Azure::ARM::Compute::Models::SshConfiguration.new.tap do |ssh_config|
            if publicKeys = ssh[:publicKeys]
              public_keys = []
              publicKeys.each do |publicKey|
                sshPublicKey = Azure::ARM::Compute::Models::SshPublicKey.new.tap do |pub_key|
                  pub_key.path = publicKey[:path] || "/home/#{adminUsername}/.ssh/authorized_keys"
                  if publicKey[:keyData]
                    pub_key.key_data = publicKey[:keyData]
                  else
                    raise "public key keyData not provided"
                  end
                end
                public_keys << sshPublicKey
              end
              ssh_config.public_keys = public_keys
            end
          end
        end
      end if linuxConfiguration
    end unless os_disk_exist

    vm.storage_profile = Azure::ARM::Compute::Models::StorageProfile.new.tap do |store_profile|
      store_profile.image_reference = Azure::ARM::Compute::Models::ImageReference.new.tap do |ref|
        ref.publisher = bootstrap_options[:storageProfile][:imageReference][:publisher]
        ref.offer = bootstrap_options[:storageProfile][:imageReference][:offer]
        ref.sku = bootstrap_options[:storageProfile][:imageReference][:sku]
        ref.version = bootstrap_options[:storageProfile][:imageReference][:version]
      end unless os_disk_exist
      store_profile.os_disk = os_disk
    end

    vm.hardware_profile = Azure::ARM::Compute::Models::HardwareProfile.new.tap do |hardware|
      hardware.vm_size = bootstrap_options[:hardwareProfile][:vmSize]
    end

    vm.network_profile = Azure::ARM::Compute::Models::NetworkProfile.new.tap do |net_profile|
      net_profile.network_interfaces = [
        Azure::ARM::Compute::Models::NetworkInterfaceReference.new.tap do |ref|
          ref.id = nic.id
          ref.primary = true
        end
      ]
    end
  end

  vm = azure_vm_service.virtual_machines.create_or_update(resource_group_name, machine_spec.name, vm_create_params)

  machine_spec.reference = {
    "driver_version" => Chef::Provisioning::AzureRM::VERSION,
    "allocated_at" => Time.now.utc.to_s,
    "host_node" => action_handler.host_node,
    "location" => location,
    "resource_group_name" => resource_group_name,
    "adminUsername" => adminUsername
  }
  machine_spec.driver_url = driver_url
  machine_spec.reference['key_name'] = bootstrap_options[:key_name] if bootstrap_options[:key_name]
  machine_spec.reference['transport_address_location'] = machine_options[:transport_address_location] if machine_options[:transport_address_location]
  machine_spec.reference['vm_name'] = machine_spec.name
  case vm.storage_profile.os_disk.os_type.downcase
  when 'windows'
    machine_spec.reference['is_windows'] = true
  else
    machine_spec.reference['is_windows'] = false
  end
  action_handler.report_progress "Created #{machine_spec.name} in #{location}..."
end

#connect_to_machine(name, chef_server = nil) ⇒ Object



277
278
279
280
281
282
283
284
285
# File 'lib/chef/provisioning/azurerm/driver.rb', line 277

def connect_to_machine(name, chef_server = nil)
  if name.is_a?(MachineSpec)
    machine_spec = name
  else
    machine_spec = Chef::Provisioning::ChefMachineSpec.get(name, chef_server)
  end

  machine_for(machine_spec, machine_spec.reference)
end

#deep_symbolize_keys(hash_like) ⇒ Object



71
72
73
74
75
76
77
78
79
80
81
# File 'lib/chef/provisioning/azurerm/driver.rb', line 71

def deep_symbolize_keys(hash_like)
  if hash_like.nil? || hash_like.empty?
  return {}
  end
  r = {}
  hash_like.each do |key, value|
    value = deep_symbolize_keys(value) if value.respond_to?(:values)
    r[key.to_sym] = value
  end
  r
end

#destroy_machine(action_handler, machine_spec, machine_options) ⇒ Object



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
# File 'lib/chef/provisioning/azurerm/driver.rb', line 314

def destroy_machine(action_handler, machine_spec, machine_options)
  vm = vm_for(machine_spec)
  vm_name = machine_spec.name
  resource_group_name = machine_spec.reference["resource_group_name"]
  # Check if we need to proceed
  return if vm.nil? || vm_name.nil? || resource_group_name.nil?
  # Skip if we don't actually need to do anything
  return unless action_handler.should_perform_actions

  # TODO: action_handler.do |block| ?
  action_handler.report_progress "Destroying VM #{machine_spec.name}"
  azure_vm_service.virtual_machines.delete(resource_group_name, vm_name)
  action_handler.report_progress "Destroying OS disk for machine #{vm_name}"
  azure_vm_service.disks.delete(resource_group_name, "#{vm_name}_os_disk")
  action_handler.report_progress "Destroying network interface #{machine_spec.name}"
  azure_net_service.network_interfaces.delete(resource_group_name, vm_name)
  action_handler.report_progress "Destroyed VM #{machine_spec.name}"
end

#ready_machine(action_handler, machine_spec, machine_options) ⇒ Object



288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
# File 'lib/chef/provisioning/azurerm/driver.rb', line 288

def ready_machine(action_handler, machine_spec, machine_options)
  machine_options = deep_symbolize_keys(machine_options)
  vm = vm_for(machine_spec)

  if vm.nil?
    raise "Machine #{machine_spec.name} does not have a VM associated with it, or the VM does not exist."
  end

  case machine_power_state(vm)
  when 'running'
    action_handler.report_progress "#{machine_spec.name} is ready"
  when 'stopped'
    action_handler.report_progress "#{machine_spec.name} is stopped. Driver can't start it, please contact admin"
    raise "#{machine_spec.name} is stopped"
    #TODO: start the VM
  when nil
    raise "Could not find power state of #{machine_spec.name}"
  else
    action_handler.report_progress "Waiting for #{machine_spec.name} to become ready..."
    wait_until_ready(action_handler, machine_spec)
  end
  wait_for_transport(action_handler, machine_spec, machine_options)
  machine_for(machine_spec, machine_options, vm)
end