Class: Kitchen::Driver::Ec2
- Inherits:
-
Base
- Object
- Base
- Kitchen::Driver::Ec2
- Includes:
- Mixins::DedicatedHosts
- Defined in:
- lib/kitchen/driver/ec2.rb
Overview
Amazon EC2 driver for Test Kitchen.
Constant Summary collapse
- INTERFACE_TYPES =
Mapping from the
interfaceconfig value to the EC2 instance attribute holding that address, in the order they are preferred when no interface was requested. { "dns" => "public_dns_name", "public" => "public_ip_address", "private" => "private_ip_address", "private_dns" => "private_dns_name", "id" => "id", }.freeze
Class Method Summary collapse
-
.validation_error(driver, old_key, new_key) ⇒ void
Report that a config key has been removed, and stop.
-
.validation_warn(driver, old_key, new_key) ⇒ void
Warn that a config key is deprecated but still honored.
Instance Method Summary collapse
-
#actual_platform ⇒ Kitchen::Driver::Aws::StandardPlatform?
The platform detected from the image actually being used.
-
#attach_network_interface(state) ⇒ void
Attach a pre-existing elastic network interface to the instance.
-
#config ⇒ Hash
The driver config.
-
#create(state) ⇒ void
Create an EC2 instance and wait until it can be connected to.
-
#create_ec2_json(state) ⇒ void
Write the Ohai EC2 hint file on the instance.
-
#create_key(state) ⇒ void
private
Create a temporary SSH key pair for this instance.
-
#create_security_group(state) ⇒ void
private
Create a temporary security group for this instance.
-
#default_ami ⇒ String?
Search for an image matching the requested platform.
-
#default_instance_type ⇒ String
The instance type to use when the user did not choose one.
-
#default_windows_user_data ⇒ String
The default PowerShell user data script for Windows instances.
-
#delete_key(state) ⇒ void
private
Clean up a temporary SSH key pair for this instance.
-
#delete_security_group(state) ⇒ void
private
Clean up a temporary security group for this instance.
-
#desired_platform ⇒ Kitchen::Driver::Aws::StandardPlatform?
The platform requested by the Test Kitchen platform name.
-
#destroy(state) ⇒ void
Terminate the instance and clean up everything created alongside it.
-
#ec2 ⇒ Kitchen::Driver::Aws::Client
The EC2 client wrapper, configured from the driver config.
-
#expand_config(conf, key) ⇒ Array<Hash>
Expand a config whose value for
keyis a list into one config per element. -
#fetch_windows_admin_password(server, state) ⇒ void
Wait for and decrypt the generated Windows administrator password.
-
#finalize_config!(instance) ⇒ self
Finalize the driver config and install transport overrides.
-
#hostname(server, interface_type = nil) ⇒ String?
Lookup hostname of provided server.
-
#image ⇒ Aws::EC2::Image
The EC2 image this instance will be created from.
-
#image_info(image) ⇒ String
A one-line summary of the attributes that drive image selection.
-
#initialize(*args, &block) ⇒ Ec2
constructor
A new instance of Ec2.
-
#instance_generator ⇒ Kitchen::Driver::Aws::InstanceGenerator
A generator for the RunInstances payload.
-
#show_chosen_image ⇒ void
Log which image was chosen and what platform was detected on it.
-
#submit_server ⇒ Aws::EC2::Instance
Request a single on-demand instance.
-
#submit_spot ⇒ Aws::EC2::Instance
Request a single spot instance for the current config.
-
#submit_spots ⇒ Aws::EC2::Instance
Request a spot instance, trying each viable configuration in turn.
-
#sudo_command ⇒ String
Returns the sudo command to use or empty string if sudo is not configured.
-
#update_username(state) ⇒ void
Record the platform's default SSH username in the instance state.
-
#wait_until_ready(server, state) ⇒ void
Wait until an instance is genuinely usable.
-
#wait_with_destroy(server, state, status_msg) {|aws_instance| ... } ⇒ void
Poll until a block returns true, destroying the instance if it never does.
-
#with_request_limit_backoff(state) ⇒ Object
Retry a block with quadratic backoff when EC2 throttles the request.
Methods included from Mixins::DedicatedHosts
#allocate_host, #allow_allocate_host?, #allow_deallocate_host?, #deallocate_host, #host_available?, #host_for_id, #host_unused?, #hosts_managed, #hosts_with_capacity, #instance_family_from_type, #instance_size_from_type, #metal_instance_type?
Constructor Details
#initialize(*args, &block) ⇒ Ec2
Returns a new instance of Ec2.
113 114 115 |
# File 'lib/kitchen/driver/ec2.rb', line 113 def initialize(*args, &block) super end |
Class Method Details
.validation_error(driver, old_key, new_key) ⇒ void
This method returns an undefined value.
Report that a config key has been removed, and stop.
Continuing would silently ignore a setting the user believes is in
effect, which for keys like ebs_volume_size changes the shape of the
instance that gets built.
138 139 140 141 142 |
# File 'lib/kitchen/driver/ec2.rb', line 138 def self.validation_error(driver, old_key, new_key) warn "ERROR: The driver[#{driver.class.name}] config key `#{old_key}` " \ "has been removed, please use `#{new_key}`" exit! end |
.validation_warn(driver, old_key, new_key) ⇒ void
This method returns an undefined value.
Warn that a config key is deprecated but still honored.
123 124 125 126 |
# File 'lib/kitchen/driver/ec2.rb', line 123 def self.validation_warn(driver, old_key, new_key) driver.warn "WARN: The driver[#{driver.class.name}] config key `#{old_key}` " \ "is deprecated, please use `#{new_key}`" end |
Instance Method Details
#actual_platform ⇒ Kitchen::Driver::Aws::StandardPlatform?
The platform detected from the image actually being used.
This can differ from #desired_platform: the user asks for "ubuntu" and gets whichever Ubuntu release the search matched. It is the source of the default SSH username.
441 442 443 |
# File 'lib/kitchen/driver/ec2.rb', line 441 def actual_platform @actual_platform ||= Aws::StandardPlatform.from_image(self, image) if image end |
#attach_network_interface(state) ⇒ void
This method returns an undefined value.
Attach a pre-existing elastic network interface to the instance.
Attached at device index 1, leaving index 0 for the primary interface. An interface that is already attached is left alone, and one that does not exist is reported without failing the run, since the instance itself is already up by this point.
1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 |
# File 'lib/kitchen/driver/ec2.rb', line 1133 def attach_network_interface(state) info("Attaching Network interface <#{config[:elastic_network_interface_id]}> with the instance <#{state[:server_id]}> .") client = ::Aws::EC2::Client.new(region: config[:region]) begin check_eni = client.describe_network_interface_attribute({ attribute: "attachment", network_interface_id: config[:elastic_network_interface_id], }) if check_eni..nil? unless state[:server_id].nil? client.attach_network_interface({ device_index: 1, instance_id: state[:server_id], network_interface_id: config[:elastic_network_interface_id], }) info("Attached Network interface <#{config[:elastic_network_interface_id]}> with the instance <#{state[:server_id]}> .") end else puts "ENI #{config[:elastic_network_interface_id]} already attached." end rescue ::Aws::EC2::Errors::InvalidNetworkInterfaceIDNotFound => e warn(e) end end |
#config ⇒ Hash
The driver config.
#submit_spots overrides this with a rewritten config while trying each instance type and subnet combination, so the generator and the rest of the driver see the variant currently being attempted.
541 542 543 544 545 |
# File 'lib/kitchen/driver/ec2.rb', line 541 def config return super unless @config @config end |
#create(state) ⇒ void
This method returns an undefined value.
Create an EC2 instance and wait until it can be connected to.
Auto-creates a security group and key pair when none were configured,
allocates a dedicated host if tenancy: host requires one, requests
either an on-demand or a spot instance, then waits for the instance to
exist, become ready, and accept a transport connection.
Any failure destroys the instance and everything auto-created alongside it, so that a failed create does not leave billable resources behind.
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 |
# File 'lib/kitchen/driver/ec2.rb', line 256 def create(state) return if state[:server_id] update_username(state) info(Kitchen::Util.outdent!(" If you are not using an account that qualifies under the AWS\n free-tier, you may be charged to run these suites. The charge\n should be minimal, but neither Test Kitchen nor its maintainers\n are responsible for your incurred costs.\n END\n\n # If no security group IDs are specified, create one automatically.\n unless config[:security_group_ids] || config[:security_group_filter]\n create_security_group(state)\n config[:security_group_ids] = [state[:auto_security_group_id]]\n end\n\n # If no SSH key pair name is specified, create one automatically.\n # If `_disabled`, nullify the key ID to avoid associating the instance with\n # an AWS-managed key pair.\n case config[:aws_ssh_key_id]\n when nil\n create_key(state)\n # Don't set aws_ssh_key_id if using Instance Connect\n config[:aws_ssh_key_id] = state[:auto_key_id] unless config[:use_instance_connect]\n when \"_disable\"\n info(\"Disabling AWS-managed SSH key pairs for this EC2 instance.\")\n info(\"The key pairs for the kitchen transport config and the AMI must match.\")\n config[:aws_ssh_key_id] = nil\n end\n\n # Allocate new dedicated hosts if needed and allowed\n if config[:tenancy] == \"host\"\n unless host_available? || allow_allocate_host?\n warn \"ERROR: tenancy `host` requested but no suitable host and allocation not allowed (set `allocate_dedicated_host` setting)\"\n exit!\n end\n\n allocate_host unless host_available?\n\n info(\"Auto placement on one dedicated host out of: \#{hosts_with_capacity.map(&:host_id).join(\", \")}\")\n end\n\n server = if config[:spot_price]\n # Spot instance when a price is set\n with_request_limit_backoff(state) { submit_spots }\n else\n # On-demand instance\n with_request_limit_backoff(state) { submit_server }\n end\n info(\"Instance <\#{server.id}> requested.\")\n with_request_limit_backoff(state) do\n logging_proc = ->(attempts) { info(\"Polling AWS for existence, attempt \#{attempts}...\") }\n server.wait_until_exists(before_attempt: logging_proc)\n end\n\n state[:server_id] = server.id\n info(\"EC2 instance <\#{state[:server_id]}> created.\")\n\n # See https://github.com/aws/aws-sdk-ruby/issues/859\n # Waiting can fail, so we have to retry on that.\n Retryable.retryable(\n tries: 10,\n sleep: ->(n) { [2**n, 30].min },\n on: ::Aws::EC2::Errors::InvalidInstanceIDNotFound\n ) do |_r, _|\n wait_until_ready(server, state)\n end\n\n info(\"EC2 instance <\#{state[:server_id]}> ready (hostname: \#{state[:hostname]}).\")\n\n if config[:use_instance_connect]\n instance_connect_setup_ready(state)\n elsif config[:use_ssm_session_manager]\n ssm_session_manager_setup_ready(state)\n end\n\n instance.transport.connection(state).wait_until_ready\n attach_network_interface(state) unless config[:elastic_network_interface_id].nil?\n create_ec2_json(state) if /chef/i.match?(instance.provisioner.name)\n debug(\"ec2:create '\#{state[:hostname]}'\")\nrescue Exception => e\n # Clean up the instance and any auto-created security groups or keys on the way out.\n destroy(state)\n raise \"\#{e.message} in the specified region \#{config[:region]}. Please check this AMI is available in this region.\"\nend\n")) unless config[:skip_cost_warning] |
#create_ec2_json(state) ⇒ void
This method returns an undefined value.
Write the Ohai EC2 hint file on the instance.
Chef's ec2 Ohai plugin only collects EC2 metadata when this hint file
is present, so it is created for Chef provisioners.
880 881 882 883 884 885 886 887 888 |
# File 'lib/kitchen/driver/ec2.rb', line 880 def create_ec2_json(state) if windows_os? cmd = 'New-Item -Force C:\\chef\\ohai\\hints\\ec2.json -ItemType File' else debug "Using sudo_command='#{sudo_command}' for ohai hints" cmd = "#{sudo_command} mkdir -p /etc/chef/ohai/hints; #{sudo_command} touch /etc/chef/ohai/hints/ec2.json" end instance.transport.connection(state).execute(cmd) end |
#create_key(state) ⇒ void
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This method returns an undefined value.
Create a temporary SSH key pair for this instance.
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 |
# File 'lib/kitchen/driver/ec2.rb', line 1080 def create_key(state) return if state[:auto_key_id] # Encode a bunch of metadata into the name because that's all we can # set for a key pair. name_parts = [ instance.name.gsub(/\W/, ""), (Etc.getlogin || "nologin").gsub(/\W/, ""), Socket.gethostname.gsub(/\W/, "")[0..20], Time.now.utc.iso8601, Array.new(8) { rand(36).to_s(36) }.join, ] # In a perfect world this would generate the key locally and use ImportKey # instead for better security, but given the use case that is very likely # to rapidly exhaust local entropy by creating a lot of keys. So this is # probably fine. If you want very high security, probably don't use this # feature anyway. resp = ec2.client.create_key_pair( key_name: "kitchen-#{name_parts.join("-")}", key_type: config[:aws_ssh_key_type], tag_specifications: [ { resource_type: "key-pair", tags: [ { key: "created-by", value: "test-kitchen", }, ], }, ] ) state[:auto_key_id] = resp.key_name info("Created automatic key pair #{state[:auto_key_id]}") # Write the key out with safe permissions key_path = "#{config[:kitchen_root]}/.kitchen/#{instance.name}.pem" File.open(key_path, File::WRONLY | File::CREAT | File::EXCL, 00600) do |f| f.write(resp.key_material) end # Inject the key into the state to be used by the SSH transport, or for # the Windows password decrypt above in {#fetch_windows_admin_password}. state[:ssh_key] = key_path end |
#create_security_group(state) ⇒ void
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This method returns an undefined value.
Create a temporary security group for this instance.
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 1036 1037 1038 1039 1040 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 |
# File 'lib/kitchen/driver/ec2.rb', line 1000 def create_security_group(state) return if state[:auto_security_group_id] # Work out which VPC, if any, we are creating in. vpc_id = if config[:subnet_id] # Get the VPC ID for the subnet. subnets = ec2.client.describe_subnets(filters: [{ name: "subnet-id", values: [config[:subnet_id]] }]).subnets raise "Subnet #{config[:subnet_id]} not found during security group creation" if subnets.empty? subnets.first.vpc_id elsif config[:subnet_filter] filters = [config[:subnet_filter]].flatten r = { filters: [] } filters.each do |subnet_filter| r[:filters] << { name: "tag:#{subnet_filter[:tag]}", values: [subnet_filter[:value]], } end subnets = ec2.client.describe_subnets(r).subnets raise "Subnets with tags '#{filters}' not found during security group creation" if subnets.empty? subnets.first.vpc_id else # Try to check for a default VPC. vpcs = ec2.client.describe_vpcs(filters: [{ name: "isDefault", values: ["true"] }]).vpcs if vpcs.empty? # No default VPC so assume EC2-Classic ¯\_(ツ)_/¯ nil else # I don't actually know if you can have more than one default VPC? vpcs.first.vpc_id end end # Create the SG. params = { group_name: "kitchen-#{Array.new(8) { rand(36).to_s(36) }.join}", description: "Test Kitchen for #{instance.name} by #{Etc.getlogin || "nologin"} on #{Socket.gethostname}", tag_specifications: [ { resource_type: "security-group", tags: [ { key: "created-by", value: "test-kitchen", }, ], }, ], } params[:vpc_id] = vpc_id if vpc_id resp = ec2.client.create_security_group(params) state[:auto_security_group_id] = resp.group_id info("Created automatic security group #{state[:auto_security_group_id]}") debug(" in VPC #{vpc_id || "none"}") # Set up SG rules. ec2.client.( group_id: state[:auto_security_group_id], # Allow SSH and WinRM (both plain and TLS). ip_permissions: [22, 3389, 5985, 5986].map do |port| { ip_protocol: "tcp", from_port: port, to_port: port, ip_ranges: Array(config[:security_group_cidr_ip]).map do |cidr_ip| { cidr_ip: } end, } end ) end |
#default_ami ⇒ String?
Search for an image matching the requested platform.
Falls back to searching for Ubuntu when the platform name is not
recognized, so that kitchen create still does something useful.
466 467 468 469 470 471 472 473 |
# File 'lib/kitchen/driver/ec2.rb', line 466 def default_ami @default_ami ||= begin search_platform = desired_platform || Aws::StandardPlatform.from_platform_string(self, "ubuntu") image_search = config[:image_search] || search_platform.image_search search_platform.find_image(image_search) end end |
#default_instance_type ⇒ String
The instance type to use when the user did not choose one.
t3 instances require a hardware-virtualized image, so a paravirtual image falls back to the older t1 family.
422 423 424 425 426 427 428 429 430 431 |
# File 'lib/kitchen/driver/ec2.rb', line 422 def default_instance_type @instance_type ||= if image && image.virtualization_type == "hvm" info("instance_type not specified. Using free tier t3.micro instance ...") "t3.micro" else info("instance_type not specified. Using free tier t1.micro instance since" \ " image is paravirtual (pick an hvm image to use the superior t3.micro!) ...") "t1.micro" end end |
#default_windows_user_data ⇒ String
The default PowerShell user data script for Windows instances.
Enables PS remoting, opens the WinRM firewall port and configures WinRM limits, without which a freshly created Windows instance cannot be connected to. Handles both EC2Launch (2016+) and the older EC2Config service, which log to different paths.
When the transport uses an account other than Administrator, a matching local account is created and password complexity is relaxed first, since a generated password may not satisfy the default policy.
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 |
# File 'lib/kitchen/driver/ec2.rb', line 902 def default_windows_user_data base_script = Kitchen::Util.outdent!(" $OSVersion = (get-itemproperty -Path \"HKLM:\\\\SOFTWARE\\\\Microsoft\\\\Windows NT\\\\CurrentVersion\" -Name ProductName).ProductName\n If($OSVersion.contains('2016') -Or $OSVersion.contains('2019') -Or $OSVersion -eq 'Windows Server Datacenter') {\n New-Item -ItemType Directory -Force -Path 'C:\\\\ProgramData\\\\Amazon\\\\EC2-Windows\\\\Launch\\\\Log'\n $logfile='C:\\\\ProgramData\\\\Amazon\\\\EC2-Windows\\\\Launch\\\\Log\\\\kitchen-ec2.log'\n # EC2Launch doesn't init extra disks by default\n C:\\\\ProgramData\\\\Amazon\\\\EC2-Windows\\\\Launch\\\\Scripts\\\\InitializeDisks.ps1\n } Else {\n New-Item -ItemType Directory -Force -Path 'C:\\\\Program Files\\\\Amazon\\\\Ec2ConfigService\\\\Logs'\n $logfile='C:\\\\Program Files\\\\Amazon\\\\Ec2ConfigService\\\\Logs\\\\kitchen-ec2.log'\n }\n\n # Logfile fail-safe in case the directory does not exist\n New-Item $logfile -Type file -Force\n\n # Allow script execution\n Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Force\n #PS Remoting and & winrm.cmd basic config\n $enableArgs=@{Force=$true}\n $command=Get-Command Enable-PSRemoting\n if($command.Parameters.Keys -contains \"skipnetworkprofilecheck\"){\n $enableArgs.skipnetworkprofilecheck=$true\n }\n Enable-PSRemoting @enableArgs\n & winrm.cmd set winrm/config '@{MaxTimeoutms=\"1800000\"}' >> $logfile\n & winrm.cmd set winrm/config/winrs '@{MaxMemoryPerShellMB=\"1024\"}' >> $logfile\n & winrm.cmd set winrm/config/winrs '@{MaxShellsPerUser=\"50\"}' >> $logfile\n & winrm.cmd set winrm/config/winrs '@{MaxMemoryPerShellMB=\"1024\"}' >> $logfile\n #Firewall Config\n & netsh advfirewall firewall set rule name=\"Windows Remote Management (HTTP-In)\" profile=public protocol=tcp localport=5985 remoteip=localsubnet new remoteip=any >> $logfile\n Set-ItemProperty -Name LocalAccountTokenFilterPolicy -Path HKLM:\\\\software\\\\Microsoft\\\\Windows\\\\CurrentVersion\\\\Policies\\\\system -Value 1\n EOH\n\n # Preparing custom static admin user if we defined something other than Administrator\n custom_admin_script = \"\"\n if instance.transport[:username] !~ /administrator/i && instance.transport[:password]\n custom_admin_script = Kitchen::Util.outdent!(<<-EOH)\n \"Disabling Complex Passwords\" >> $logfile\n $seccfg = [IO.Path]::GetTempFileName()\n & secedit.exe /export /cfg $seccfg >> $logfile\n (Get-Content $seccfg) | Foreach-Object {$_ -replace \"PasswordComplexity\\\\s*=\\\\s*1\", \"PasswordComplexity = 0\"} | Set-Content $seccfg\n & secedit.exe /configure /db $env:windir\\\\security\\\\new.sdb /cfg $seccfg /areas SECURITYPOLICY >> $logfile\n & cp $seccfg \"c:\\\\\"\n & del $seccfg\n $username=\"\#{instance.transport[:username]}\"\n $password=\"\#{instance.transport[:password]}\"\n \"Creating static user: $username\" >> $logfile\n & net.exe user /y /add $username $password >> $logfile\n \"Adding $username to Administrators\" >> $logfile\n & net.exe localgroup Administrators /add $username >> $logfile\n EOH\n end\n\n # Returning the fully constructed PowerShell script to user_data\n Kitchen::Util.outdent!(<<-EOH)\n <powershell>\n \#{base_script}\n \#{custom_admin_script}\n </powershell>\n EOH\nend\n") |
#delete_key(state) ⇒ void
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This method returns an undefined value.
Clean up a temporary SSH key pair for this instance.
1176 1177 1178 1179 1180 1181 1182 1183 |
# File 'lib/kitchen/driver/ec2.rb', line 1176 def delete_key(state) return unless state[:auto_key_id] info("Removing automatic key pair #{state[:auto_key_id]}") ec2.client.delete_key_pair(key_name: state[:auto_key_id]) state.delete(:auto_key_id) File.unlink("#{config[:kitchen_root]}/.kitchen/#{instance.name}.pem") end |
#delete_security_group(state) ⇒ void
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
This method returns an undefined value.
Clean up a temporary security group for this instance.
1163 1164 1165 1166 1167 1168 1169 |
# File 'lib/kitchen/driver/ec2.rb', line 1163 def delete_security_group(state) return unless state[:auto_security_group_id] info("Removing automatic security group #{state[:auto_security_group_id]}") ec2.client.delete_security_group(group_id: state[:auto_security_group_id]) state.delete(:auto_security_group_id) end |
#desired_platform ⇒ Kitchen::Driver::Aws::StandardPlatform?
The platform requested by the Test Kitchen platform name.
449 450 451 452 453 454 455 456 457 458 |
# File 'lib/kitchen/driver/ec2.rb', line 449 def desired_platform @desired_platform ||= begin platform = Aws::StandardPlatform.from_platform_string(self, instance.platform.name) if platform debug("platform name #{instance.platform.name} appears to be a standard platform." \ " Searching for #{platform} ...") end platform end end |
#destroy(state) ⇒ void
This method returns an undefined value.
Terminate the instance and clean up everything created alongside it.
An instance that no longer exists is treated as success, since kitchen destroy is also how a failed create is cleaned up. Termination is
waited on only when an auto-created security group needs removing, as
the group cannot be deleted while an instance still references it.
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 |
# File 'lib/kitchen/driver/ec2.rb', line 353 def destroy(state) if state[:server_id] server = ec2.get_instance(state[:server_id]) unless server.nil? instance.transport.connection(state).close begin server.terminate rescue ::Aws::EC2::Errors::InvalidInstanceIDNotFound => e warn("Received #{e}, instance was probably already destroyed. Ignoring") end end # If we are going to clean up an automatic security group, we need # to wait for the instance to shut down. This slightly breaks the # subsystem encapsulation, sorry not sorry. if state[:auto_security_group_id] && server && ec2.instance_exists?(state[:server_id]) wait_log = proc do |attempts| c = attempts * config[:retryable_sleep] t = config[:retryable_tries] * config[:retryable_sleep] info "Waited #{c}/#{t}s for instance <#{server.id}> to terminate." end server.wait_until_terminated( max_attempts: config[:retryable_tries], delay: config[:retryable_sleep], before_attempt: wait_log ) end info("EC2 instance <#{state[:server_id]}> destroyed.") state.delete(:server_id) state.delete(:hostname) end # Clean up any auto-created security groups or keys. delete_security_group(state) delete_key(state) # Clean up dedicated hosts matching instance_type and unused (if allowed) return unless config[:tenancy] == "host" && allow_deallocate_host? empty_hosts = hosts_with_capacity.select { |host| host_unused?(host) } empty_hosts.each { |host| deallocate_host(host.host_id) } end |
#ec2 ⇒ Kitchen::Driver::Aws::Client
The EC2 client wrapper, configured from the driver config.
500 501 502 503 504 505 506 507 508 |
# File 'lib/kitchen/driver/ec2.rb', line 500 def ec2 @ec2 ||= Aws::Client.new( config[:region], config[:shared_credentials_profile], config[:http_proxy], config[:retry_limit], config[:ssl_verify_peer] ) end |
#expand_config(conf, key) ⇒ Array<Hash>
Expand a config whose value for key is a list into one config per
element.
Used to turn instance_type: [a, b] into two candidate configs to try
in turn. The original config is cloned rather than mutated.
557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 |
# File 'lib/kitchen/driver/ec2.rb', line 557 def (conf, key) configs = [] if conf[key].is_a?(Array) values = conf[key] values.each do |value| new_config = conf.clone new_config[key] = value configs.push new_config end else configs.push conf end configs end |
#fetch_windows_admin_password(server, state) ⇒ void
This method returns an undefined value.
Wait for and decrypt the generated Windows administrator password.
EC2 returns blank password data until the password is available, so this polls first and then decrypts with the instance's private key.
779 780 781 782 783 784 785 786 787 788 789 790 791 792 |
# File 'lib/kitchen/driver/ec2.rb', line 779 def fetch_windows_admin_password(server, state) wait_with_destroy(server, state, "to fetch windows admin password") do |_aws_instance| enc = server.client.get_password_data( instance_id: state[:server_id] ).password_data # Password data is blank until password is available !enc.nil? && !enc.empty? end pass = with_request_limit_backoff(state) do server.decrypt_windows_password(File.(state[:ssh_key] || instance.transport[:ssh_key])) end state[:password] = pass info("Retrieved Windows password for instance <#{state[:server_id]}>.") end |
#finalize_config!(instance) ⇒ self
Finalize the driver config and install transport overrides.
Instance Connect and SSM Session Manager both work by wrapping the transport's connection handling, which has to happen before the transport is first used.
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 |
# File 'lib/kitchen/driver/ec2.rb', line 1193 def finalize_config!(instance) super # Set up Instance Connect transport override if configured if config[:use_instance_connect] debug("[AWS EC2 Instance Connect] Setting up Instance Connect overrides") instance_connect_setup_override(instance) instance_connect_setup_inspec_override(instance) elsif config[:use_ssm_session_manager] debug("[AWS SSM Session Manager] Setting up SSM Session Manager overrides") ssm_session_manager_setup_override(instance) ssm_session_manager_setup_inspec_override(instance) end self end |
#hostname(server, interface_type = nil) ⇒ String?
Lookup hostname of provided server. If interface_type is provided use that interface to lookup hostname. Otherwise, try ordered list of options.
The address to connect to an instance on.
With no interface type, INTERFACE_TYPES is walked in order and the first populated value wins. AWS returns an empty string rather than nil for an address that is not assigned yet, so empty values are skipped.
846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 |
# File 'lib/kitchen/driver/ec2.rb', line 846 def hostname(server, interface_type = nil) if interface_type interface_type = INTERFACE_TYPES.fetch(interface_type) do raise Kitchen::UserError, "Invalid interface [#{interface_type}]" end server.send(interface_type) else potential_hostname = nil INTERFACE_TYPES.each_value do |type| potential_hostname ||= server.send(type) # AWS returns an empty string if the dns name isn't populated yet potential_hostname = nil if potential_hostname == "" end potential_hostname end end |
#image ⇒ Aws::EC2::Image
The EC2 image this instance will be created from.
401 402 403 404 405 406 407 408 409 410 411 412 413 414 |
# File 'lib/kitchen/driver/ec2.rb', line 401 def image return @image if defined?(@image) if config[:image_id] @image = ec2.resource.image(config[:image_id]) show_chosen_image else raise "Neither image_id nor an image_search specified for instance #{instance.name}!" \ " Please specify one or the other." end @image end |
#image_info(image) ⇒ String
A one-line summary of the attributes that drive image selection.
984 985 986 987 988 989 990 991 992 993 |
# File 'lib/kitchen/driver/ec2.rb', line 984 def image_info(image) root_device = image.block_device_mappings .find { |b| b.device_name == image.root_device_name } volume_type = " #{root_device.ebs.volume_type}" if root_device&.ebs " Architecture: #{image.architecture}," \ " Virtualization: #{image.virtualization_type}," \ " Storage: #{image.root_device_type}#{volume_type}," \ " Created: #{image.creation_date}" end |
#instance_generator ⇒ Kitchen::Driver::Aws::InstanceGenerator
Deliberately reassigned rather than memoized with ||=: spot
requests retry against a rewritten #config, and a cached generator
would keep building the payload from the config of the first attempt.
A generator for the RunInstances payload.
517 518 519 |
# File 'lib/kitchen/driver/ec2.rb', line 517 def instance_generator @instance_generator = Aws::InstanceGenerator.new(config, ec2, instance.logger) end |
#show_chosen_image ⇒ void
This method returns an undefined value.
Log which image was chosen and what platform was detected on it.
968 969 970 971 972 973 974 975 976 977 978 |
# File 'lib/kitchen/driver/ec2.rb', line 968 def show_chosen_image # Print some debug stuff debug("Image for #{instance.name}: #{image.name}. #{image_info(image)}") if actual_platform info("Detected platform: #{actual_platform.name} version #{actual_platform.version}" \ " on #{actual_platform.architecture}. Instance Type: #{config[:instance_type]}." \ " Default username: #{actual_platform.username} (default).") else debug("No platform detected for #{image.name}.") end end |
#submit_server ⇒ Aws::EC2::Instance
Request a single on-demand instance.
524 525 526 527 528 529 530 531 532 |
# File 'lib/kitchen/driver/ec2.rb', line 524 def submit_server instance_data = instance_generator.ec2_instance_data debug("Creating EC2 instance in region #{config[:region]} with properties:") instance_data.each do |key, value| debug("- #{key} = #{value.inspect}") end ec2.create_instance(instance_data) end |
#submit_spot ⇒ Aws::EC2::Instance
Request a single spot instance for the current config.
A spot_price of "ondemand" or "on-demand" requests a spot instance
with no price cap, which EC2 expresses by omitting max_price.
create_instances is used rather than request_spot_instances because
only the former can tag an instance at creation time; the retry loop
compensates for its lack of built-in waiting.
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 |
# File 'lib/kitchen/driver/ec2.rb', line 648 def submit_spot debug("Creating EC2 Spot Instance..") instance_data = instance_generator.ec2_instance_data config_spot_price = config[:spot_price].to_s spot_price = if %w{ondemand on-demand}.include?(config_spot_price) "" else config_spot_price end = { # Must use one-time in order to use instance_interruption_behavior=terminate # spot_instance_type: "one-time", # default # Must use instance_interruption_behavior=terminate in order to use block_duration_minutes # instance_interruption_behavior: "terminate", # default } if config[:block_duration_minutes] [:block_duration_minutes] = config[:block_duration_minutes] end unless spot_price == "" # i.e. on-demand [:max_price] = spot_price end instance_data[:instance_market_options] = { market_type: "spot", spot_options:, } # The preferred way to create a spot instance is via request_spot_instances() # However, it does not allow for tagging to occur at creation time. # create_instances() allows creation of tagged spot instances, but does # not retry if the price could not be satisfied immediately. Retryable.retryable( tries: config[:spot_wait] / config[:retryable_sleep], sleep: ->(_n) { config[:retryable_sleep] }, on: ::Aws::EC2::Errors::SpotMaxPriceTooLow ) do |retries| c = retries * config[:retryable_sleep] t = config[:spot_wait] info "Waited #{c}/#{t}s for spot request to become fulfilled." ec2.create_instance(instance_data) end end |
#submit_spots ⇒ Aws::EC2::Instance
Request a spot instance, trying each viable configuration in turn.
Spot capacity is per instance type and per availability zone, so a request can fail for reasons that a different type or subnet would satisfy. Every combination of instance type and subnet is attempted before giving up, and all the failures are reported together.
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 |
# File 'lib/kitchen/driver/ec2.rb', line 583 def submit_spots configs = [config] = [] keys = i{instance_type} if config[:subnet_filter] # => Enable cascading through matching subnets client = ::Aws::EC2::Client.new(region: config[:region]) filters = [config[:subnet_filter]].flatten r = { filters: [] } filters.each do |subnet_filter| r[:filters] << { name: "tag:#{subnet_filter[:tag]}", values: [subnet_filter[:value]], } end subnets = client.describe_subnets(r).subnets raise "Subnets with tags '#{filters}' not found!" if subnets.empty? configs = subnets.map do |subnet| new_config = config.clone new_config[:subnet_id] = subnet.subnet_id new_config[:subnet_filter] = nil new_config end else # => Use explicitly specified subnets keys << :subnet_id end keys.each do |key| configs.each do |conf| .push (conf, key) end configs = .flatten = [] end errs = [] configs.each do |conf| @config = conf return submit_spot rescue => e errs.append(e) end raise ["Could not create a spot instance:", errs].flatten.join("\n") end |
#sudo_command ⇒ String
Returns the sudo command to use or empty string if sudo is not configured
The command used to elevate privileges, if any.
869 870 871 |
# File 'lib/kitchen/driver/ec2.rb', line 869 def sudo_command instance.provisioner[:sudo] ? instance.provisioner[:sudo_command].to_s : "" end |
#update_username(state) ⇒ void
This method returns an undefined value.
Record the platform's default SSH username in the instance state.
Only applied when the transport is still using its own default username, so that a username the user configured is never overwritten.
482 483 484 485 486 487 488 489 490 491 492 493 494 495 |
# File 'lib/kitchen/driver/ec2.rb', line 482 def update_username(state) # BUG: With the following equality condition on username, if the user specifies 'root' # as the transport's username then we will overwrite that value with one from the standard # platform definitions. This seems difficult to handle here as the default username is # provided by the underlying transport classes, and is often non-nil (eg; 'root'), leaving # us no way to distinguish a user-set value from the transport's default. # See https://github.com/test-kitchen/kitchen-ec2/pull/273 if actual_platform && instance.transport[:username] == instance.transport.class.defaults[:username] debug("No SSH username specified: using default username #{actual_platform.username} " \ "for image #{config[:image_id]}, which we detected as #{actual_platform}.") state[:username] = actual_platform.username end end |
#wait_until_ready(server, state) ⇒ void
This method returns an undefined value.
Wait until an instance is genuinely usable.
server.wait_until_running is not sufficient: an instance can report
running before it has an address, and a Windows instance is not usable
until its console output says so. The hostname is stored as soon as it
is known so that a later failure still leaves enough state to clean up.
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 |
# File 'lib/kitchen/driver/ec2.rb', line 702 def wait_until_ready(server, state) wait_with_destroy(server, state, "to become ready") do |aws_instance| hostname = hostname(aws_instance, config[:interface]) # We aggressively store the hostname so if the process fails here # we still have it, even if it will change later state[:hostname] = hostname # Euca instances often report ready before they have an IP ready = aws_instance.exists? && aws_instance.state.name == "running" && hostname != "0.0.0.0" if ready && (hostname.nil? || hostname == "") debug("Unable to detect hostname using interface_type #{config[:interface]}. Fallback to ordered mapping") state[:hostname] = hostname(aws_instance, nil) end if ready && windows_os? if instance.transport[:username] =~ /administrator/i && instance.transport[:password].nil? # If we're logging into the administrator user and a password isn't # supplied, try to fetch it from the AWS instance fetch_windows_admin_password(server, state) else output = server.console_output.output || "" unless output.nil? output = Base64.decode64(output) debug "Console output: --- \n#{output}" end ready = !!output.include?("Windows is Ready to use") end end ready end end |
#wait_with_destroy(server, state, status_msg) {|aws_instance| ... } ⇒ void
This method returns an undefined value.
Poll until a block returns true, destroying the instance if it never does.
An instance that never becomes ready would otherwise keep running and accruing charges after Test Kitchen gave up on it.
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 |
# File 'lib/kitchen/driver/ec2.rb', line 748 def wait_with_destroy(server, state, status_msg, &block) wait_log = proc do |attempts| c = attempts * config[:retryable_sleep] t = config[:retryable_tries] * config[:retryable_sleep] info "Waited #{c}/#{t}s for instance <#{state[:server_id]}> #{status_msg}." end begin with_request_limit_backoff(state) do server.wait_until( max_attempts: config[:retryable_tries], delay: config[:retryable_sleep], before_attempt: wait_log, &block ) end rescue ::Aws::Waiters::Errors::WaiterFailed error("Ran out of time waiting for the server with id [#{state[:server_id]}]" \ " #{status_msg}, attempting to destroy it") destroy(state) raise end end |
#with_request_limit_backoff(state) ⇒ Object
Retry a block with quadratic backoff when EC2 throttles the request.
Only throttling is retried; any other error is re-raised immediately so that a genuine failure is not delayed by five pointless retries.
802 803 804 805 806 807 808 809 810 811 812 813 814 815 |
# File 'lib/kitchen/driver/ec2.rb', line 802 def with_request_limit_backoff(state) retries = 0 begin yield rescue ::Aws::EC2::Errors::RequestLimitExceeded, ::Aws::Waiters::Errors::UnexpectedError => e raise unless retries < 5 && e..include?("Request limit exceeded") retries += 1 info("Request limit exceeded for instance <#{state[:server_id]}>." \ " Trying again in #{retries**2} seconds.") sleep(retries**2) retry end end |