Module: Capistrano::Aws::Hosts

Defined in:
lib/capistrano/aws/hosts.rb,
lib/capistrano/aws/hosts/version.rb

Constant Summary collapse

VERSION =
"0.1.0"

Instance Method Summary collapse

Instance Method Details

#fetch_aws_hostsArray<Struct(private_ip, instance_id, name>] array of instance records

Fetches the hosts from AWS, filtering based on the tag ‘Role’ values (wildcarded)

Returns:

  • (Array<Struct(private_ip, instance_id, name>] array of instance records)

    Array<Struct(private_ip, instance_id, name>] array of instance records



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/capistrano/aws/hosts.rb', line 9

def fetch_aws_hosts
  role_name = fetch(:aws_hosts_filter)
  profile = fetch(:aws_hosts_profile) || ENV['AWS_PROFILE']
  region = fetch(:aws_region) || ENV['AWS_DEFAULT_REGION']
  
  raise 'Region is not specified - please set :aws_region or export AWS_DEFAULT_REGION as an environment variable' unless region.to_s != ''
  # raise "Profile is not specified - please set :aws_region or export AWS_DEFAULT_REGION as an environment variable" unless region.present?
  
  client = ::Aws::EC2::Client.new(region: region, profile: profile)

  instances = client.describe_instances(filters: [
    {name: 'instance-state-name', values: ['running']},
    {name: 'tag-key', values: ['Role']},
    {name: 'tag-value', values: ["*#{role_name}*"]}
  ])

  instances = instances.first.reservations.first.instances
  result = instances.each_with_object([]) do |item, arr|
    arr << OpenStruct.new(
      private_ip: item.private_ip_address,
      instance_id: item.instance_id,
      name: item.tags.select {|t| t.key == 'Name'}.first.value
    )
  end

  print "Target hosts: #{result.map(&:name).join(', ')}\n"
  result
end