|
| 1 | +# -*- encoding: utf-8 -*- |
| 2 | +# |
| 3 | +# Author:: Tyler Ball (<[email protected]>) |
| 4 | +# |
| 5 | +# Copyright (C) 2015, Fletcher Nichol |
| 6 | +# |
| 7 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | +# you may not use this file except in compliance with the License. |
| 9 | +# You may obtain a copy of the License at |
| 10 | +# |
| 11 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | +# |
| 13 | +# Unless required by applicable law or agreed to in writing, software |
| 14 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | +# See the License for the specific language governing permissions and |
| 17 | +# limitations under the License. |
| 18 | + |
| 19 | +require "aws-sdk" |
| 20 | + |
| 21 | +module Kitchen |
| 22 | + |
| 23 | + module Driver |
| 24 | + |
| 25 | + module Client |
| 26 | + |
| 27 | + # A class for creating and managing the EC2 client connection |
| 28 | + # |
| 29 | + # @author Tyler Ball <[email protected]> |
| 30 | + class Ec2Client |
| 31 | + |
| 32 | + def initialize(region, profile_name = nil, access_key_id = nil, secret_access_key = nil) |
| 33 | + Aws.config = { |
| 34 | + :region => region, |
| 35 | + :credentials => get_credentials(profile_name, access_key_id, secret_access_key) |
| 36 | + } |
| 37 | + end |
| 38 | + |
| 39 | + # Try and get the credentials from an ordered list of locations |
| 40 | + def get_credentials(profile_name, access_key_id, secret_access_key) |
| 41 | + shared_creds = Aws::SharedCredentials.new(:profile_name => profile_name) |
| 42 | + if access_key_id && secret_access_key |
| 43 | + Aws::Credentials.new(access_key_id, secret_access_key) |
| 44 | + elsif ENV['AWS_ACCESS_KEY_ID'] && ENV['AWS_SECRET_ACCESS_KEY'] |
| 45 | + Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY'], ENV['AWS_SESSION_TOKEN']) |
| 46 | + elsif shared_creds.loadable? |
| 47 | + shared_creds |
| 48 | + else |
| 49 | + Aws::InstanceProfileCredentials.new(:retries => 1) |
| 50 | + end |
| 51 | + end |
| 52 | + |
| 53 | + def create_instance(options) |
| 54 | + resource.create_instances(options)[0] |
| 55 | + end |
| 56 | + |
| 57 | + def get_instance(id) |
| 58 | + resource.instance(id) |
| 59 | + end |
| 60 | + |
| 61 | + def get_instance_from_spot_request(request_id) |
| 62 | + resource.instances( |
| 63 | + :filters => [{ |
| 64 | + :name => "spot-instance-request-id", |
| 65 | + :values => [request_id] |
| 66 | + }] |
| 67 | + ).to_a[0] |
| 68 | + end |
| 69 | + |
| 70 | + def client |
| 71 | + @client ||= Aws::EC2::Client.new |
| 72 | + end |
| 73 | + |
| 74 | + def resource |
| 75 | + @resource ||= Aws::EC2::Resource.new |
| 76 | + end |
| 77 | + |
| 78 | + end |
| 79 | + |
| 80 | + end |
| 81 | + |
| 82 | + end |
| 83 | + |
| 84 | +end |
0 commit comments