File Coverage

lib/VM/EC2/Instance/Located.pm
Criterion Covered Total %
statement 14 15 93.3
branch 2 4 50.0
condition n/a
subroutine 4 4 100.0
pod 1 1 100.0
total 21 24 87.5


line stmt bran cond sub pod time code
1             package VM::EC2::Instance::Located;
2             $VM::EC2::Instance::Located::VERSION = '0.13';
3             # ABSTRACT: A quick check to determine if the currently running code is running on a AWS EC2 instance.
4              
5 1     1   434 use strict;
  1         2  
  1         29  
6 1     1   4 use warnings;
  1         2  
  1         25  
7 1     1   488 use Net::DNS;
  1         63425  
  1         187  
8              
9             =head1 NAME
10              
11             VM::EC2::Instance::Located - determine if code is executing on an EC2 instance
12              
13             =head1 SYNOPSIS
14              
15             my $result = VM::EC2::Instance::Located::at_ec2();
16             if($result) {
17             print "Running at EC2\n";
18             } else {
19             print "Not running at EC2\n";
20             }
21              
22             =head1 DESCRIPTION
23              
24             Provides a function that determines if code is executing on an EC2
25             instance.
26              
27             Currently implemented by resolving instnace-data.ec2.internal. It
28             will succeed on an ec2 instance and fail otherwise.
29              
30             =cut
31              
32             =head1 METHODS
33              
34             =cut
35              
36             =head2 at_ec2
37              
38             Determines if the code is running at EC2.
39              
40             The answer is cached because typically the result does not change
41             unless you're able to move processes between an EC2 instance an a non
42             EC2 instance.
43              
44             Returns a boolean value answering the question.
45              
46             =cut
47              
48             my $target_hostname = 'instance-data.ec2.internal';
49              
50             my $known_answer;
51              
52             sub at_ec2 {
53 1 50   1 1 456 return $known_answer if defined($known_answer);
54              
55 1         12 my $res = Net::DNS::Resolver->new;
56 1         398 my $reply = $res->search($target_hostname);
57            
58 1 50       18638 if ($reply) {
59 0         0 return $known_answer = 1;
60             }
61            
62 1         15 return $known_answer = 0;
63             }
64              
65             1;
66              
67              
68