16
16
17
17
from __future__ import absolute_import
18
18
from __future__ import print_function
19
- import six
19
+ import sys
20
+ import boto3
21
+ from ansible .module_utils .basic import AnsibleModule
22
+
20
23
DOCUMENTATION = '''
21
24
---
22
25
module: ec2_lookup
@@ -28,8 +31,8 @@ options:
28
31
region:
29
32
description:
30
33
- The AWS region to use. Must be specified if ec2_url
31
- is not used. If not specified then the value of the
32
- EC2_REGION environment variable, if any, is used.
34
+ is not used. If not specified then the value of
35
+ the EC2_REGION environment variable, if any, is used.
33
36
required: false
34
37
default: null
35
38
aliases: [ 'aws_region', 'ec2_region' ]
@@ -42,20 +45,20 @@ options:
42
45
aliases: [ 'ec2_secret_key', 'secret_key' ]
43
46
aws_access_key:
44
47
description:
45
- - AWS access key. If not set then the value of the
46
- AWS_ACCESS_KEY environment variable is used.
48
+ - AWS access key. If not set then the value of
49
+ the AWS_ACCESS_KEY environment variable is used.
47
50
required: false
48
51
default: null
49
52
aliases: [ 'ec2_access_key', 'access_key' ]
50
53
tags:
51
- desription :
54
+ description :
52
55
- tags to lookup
53
56
required: false
54
57
default: null
55
58
type: dict
56
59
aliases: []
57
60
58
- requirements: [ "boto " ]
61
+ requirements: [ "boto3 " ]
59
62
author: John Jarvis
60
63
'''
61
64
@@ -70,8 +73,6 @@ EXAMPLES = '''
70
73
Name: foo
71
74
'''
72
75
73
- import sys
74
-
75
76
AWS_REGIONS = ['ap-northeast-1' ,
76
77
'ap-southeast-1' ,
77
78
'ap-southeast-2' ,
@@ -81,17 +82,8 @@ AWS_REGIONS = ['ap-northeast-1',
81
82
'us-west-1' ,
82
83
'us-west-2' ]
83
84
84
- try :
85
- import boto .ec2
86
- from boto .ec2 import connect_to_region
87
- except ImportError :
88
- print ("failed=True msg='boto required for this module'" )
89
- sys .exit (1 )
90
-
91
-
92
85
def main ():
93
-
94
- module = AnsibleModule (
86
+ module = AnsibleModule (
95
87
argument_spec = dict (
96
88
ec2_url = dict (),
97
89
region = dict (aliases = ['aws_region' , 'ec2_region' ],
@@ -108,35 +100,34 @@ def main():
108
100
region = module .params .get ('region' )
109
101
ec2_url = module .params .get ('ec2_url' )
110
102
111
- # If we have a region specified, connect to its endpoint.
103
+ # If region is specified, create a session with boto3 and connect to the EC2 service
112
104
if region :
113
105
try :
114
- ec2 = connect_to_region (region , aws_access_key_id = aws_access_key ,
115
- aws_secret_access_key = aws_secret_key )
116
- except boto .exception .NoAuthHandlerFound as e :
117
- module .fail_json (msg = str (e ))
118
- # If we specified an ec2_url then try connecting to it
119
- elif ec2_url :
120
- try :
121
- ec2 = boto .connect_ec2_endpoint (ec2_url , aws_access_key ,
122
- aws_secret_key )
123
- except boto .exception .NoAuthHandlerFound as e :
124
- module .fail_json (msg = str (e ))
106
+ ec2 = boto3 .resource ('ec2' , region_name = region , aws_access_key_id = aws_access_key , aws_secret_access_key = aws_secret_key )
107
+ except Exception as e :
108
+ module .fail_json (msg = f"Error connecting to AWS EC2: { str (e )} " )
125
109
else :
126
- module .fail_json (msg = "Either region or ec2_url must be specified" )
110
+ module .fail_json (msg = "Region must be specified" )
111
+
112
+ # If EC2 URL is provided, it can be used for connection
113
+ if ec2_url :
114
+ module .fail_json (msg = "ec2_url is not supported in boto3 connection. Please use region instead." )
127
115
128
116
instances = []
129
117
instance_ids = []
130
- for res in ec2 .get_all_instances (filters = {'tag:' + tag : value
131
- for tag , value in six .iteritems (module .params .get ('tags' ))}):
132
- for inst in res .instances :
133
- if inst .state == "running" :
134
- instances .append ({k : v for k , v in six .iteritems (inst .__dict__ )
135
- if isinstance (v , (six .string_types ))})
136
- instance_ids .append (inst .id )
137
- module .exit_json (changed = False , instances = instances ,
138
- instance_ids = instance_ids )
139
118
119
+ # Get all instances with the specified tags
120
+ filters = {'tag:' + tag : value for tag , value in module .params .get ('tags' , {}).items ()}
121
+ try :
122
+ instances_query = ec2 .instances .filter (Filters = [{'Name' : f'tag:{ tag } ' , 'Values' : [value ]} for tag , value in filters .items ()])
123
+ for instance in instances_query :
124
+ if instance .state ['Name' ] == 'running' :
125
+ instances .append ({k : v for k , v in instance .__dict__ .items () if isinstance (v , str )})
126
+ instance_ids .append (instance .id )
127
+ except Exception as e :
128
+ module .fail_json (msg = f"Error querying EC2 instances: { str (e )} " )
129
+
130
+ module .exit_json (changed = False , instances = instances , instance_ids = instance_ids )
140
131
141
132
# this is magic, see lib/ansible/module_common.py
142
133
#<<INCLUDE_ANSIBLE_MODULE_COMMON>>
0 commit comments