Debian Codegraph @

ansible_collections/amazon/aws/plugins/modules/ec2_key.py

raw
1 #!/usr/bin/python
2 # -*- coding: utf-8 -*-
3
4 # Copyright: Ansible Project
5 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
6
7 DOCUMENTATION = r"""
8 ---
9 module: ec2_key
10 version_added: 1.0.0
11 short_description: Create or delete an EC2 key pair
12 description:
13 - Create or delete an EC2 key pair.
14 options:
15 name:
16 description:
17 - Name of the key pair.
18 required: true
19 type: str
20 key_material:
21 description:
22 - Public key material.
23 required: false
24 type: str
25 force:
26 description:
27 - Force overwrite of already existing key pair if key has changed.
28 required: false
29 default: true
30 type: bool
31 state:
32 description:
33 - Create or delete keypair.
34 required: false
35 choices: [ present, absent ]
36 default: 'present'
37 type: str
38 key_type:
39 description:
40 - The type of key pair to create.
41 - Note that ED25519 keys are not supported for Windows instances,
42 EC2 Instance Connect, and EC2 Serial Console.
43 - By default Amazon will create an RSA key.
44 - Mutually exclusive with parameter O(key_material).
45 type: str
46 choices:
47 - rsa
48 - ed25519
49 version_added: 3.1.0
50 file_name:
51 description:
52 - Name of the file where the generated private key will be saved.
53 - When provided, the RV(key.private_key) attribute will be removed from the return value.
54 - The file is written out on the 'host' side rather than the 'controller' side.
55 - Ignored when O(state=absent) or O(key_material) is provided.
56 type: path
57 version_added: 6.4.0
58 notes:
59 - Support for O(tags) and O(purge_tags) was added in release 2.1.0.
60 - For security reasons, this module should be used with B(no_log=true) and (register) functionalities
61 when creating new key pair without providing O(key_material).
62 extends_documentation_fragment:
63 - amazon.aws.common.modules
64 - amazon.aws.region.modules
65 - amazon.aws.tags
66 - amazon.aws.boto3
67
68 author:
69 - "Vincent Viallet (@zbal)"
70 - "Prasad Katti (@prasadkatti)"
71 """
72
73 EXAMPLES = r"""
74 # Note: These examples do not set authentication details, see the AWS Guide for details.
75
76 - name: create a new EC2 key pair, returns generated private key
77 # use no_log to avoid private key being displayed into output
78 amazon.aws.ec2_key:
79 name: my_keypair
80 no_log: true
81 register: aws_ec2_key_pair
82
83 - name: create key pair using provided key_material
84 amazon.aws.ec2_key:
85 name: my_keypair
86 key_material: 'ssh-rsa AAAAxyz...== [email protected]'
87
88 - name: create key pair using key_material obtained using 'file' lookup plugin
89 amazon.aws.ec2_key:
90 name: my_keypair
91 key_material: "{{ lookup('file', '/path/to/public_key/id_rsa.pub') }}"
92
93 - name: Create ED25519 key pair and save private key into a file
94 amazon.aws.ec2_key:
95 name: my_keypair
96 key_type: ed25519
97 file_name: /tmp/aws_ssh_rsa
98
99 # try creating a key pair with the name of an already existing keypair
100 # but don't overwrite it even if the key is different (force=false)
101 - name: try creating a key pair with name of an already existing keypair
102 amazon.aws.ec2_key:
103 name: my_existing_keypair
104 key_material: 'ssh-rsa AAAAxyz...== [email protected]'
105 force: false
106
107 - name: remove key pair from AWS by name
108 amazon.aws.ec2_key:
109 name: my_keypair
110 state: absent
111 """
112
113 RETURN = r"""
114 changed:
115 description: Whether a keypair was created/deleted.
116 returned: always
117 type: bool
118 sample: true
119 msg:
120 description: Short message describing the action taken.
121 returned: always
122 type: str
123 sample: key pair created
124 key:
125 description: Details of the keypair (this is set to null when state is absent).
126 returned: always
127 type: complex
128 contains:
129 fingerprint:
130 description: Fingerprint of the key.
131 returned: when O(state=present)
132 type: str
133 sample: 'b0:22:49:61:d9:44:9d:0c:7e:ac:8a:32:93:21:6c:e8:fb:59:62:43'
134 name:
135 description: Name of the keypair.
136 returned: when O(state=present)
137 type: str
138 sample: my_keypair
139 id:
140 description: Id of the keypair.
141 returned: when O(state=present)
142 type: str
143 sample: key-123456789abc
144 tags:
145 description: A dictionary representing the tags attached to the key pair.
146 returned: when O(state=present)
147 type: dict
148 sample: '{"my_key": "my value"}'
149 private_key:
150 description: Private key of a newly created keypair.
151 returned: when a new keypair is created by AWS (O(key_material) is not provided) and O(file_name) is not provided.
152 type: str
153 sample: '-----BEGIN RSA PRIVATE KEY-----
154 MIIEowIBAAKC...
155 -----END RSA PRIVATE KEY-----'
156 type:
157 description: Type of a newly created keypair.
158 returned: when a new keypair is created by AWS
159 type: str
160 sample: rsa
161 version_added: 3.1.0
162 """
163
164 import os
165 import uuid
166
167 from ansible.module_utils.common.text.converters import to_bytes
168
169 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import AnsibleEC2Error
170 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import create_key_pair
171 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import delete_key_pair as delete_ec2_key_pair
172 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import describe_key_pairs
173 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import ensure_ec2_tags
174 from ansible_collections.amazon.aws.plugins.module_utils.ec2 import import_key_pair
175 from ansible_collections.amazon.aws.plugins.module_utils.modules import AnsibleAWSModule
176 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_list_to_ansible_dict
177 from ansible_collections.amazon.aws.plugins.module_utils.tagging import boto3_tag_specifications
178 from ansible_collections.amazon.aws.plugins.module_utils.transformation import scrub_none_parameters
179
180
181 class Ec2KeyFailure(Exception):
182 def __init__(self, message=None, original_e=None):
183 super().__init__(message)
184 self.original_e = original_e
185 self.message = message
186
187
188 def _import_key_pair(ec2_client, name, key_material, tag_spec=None):
189 params = {"KeyName": name, "PublicKeyMaterial": to_bytes(key_material), "TagSpecifications": tag_spec}
190
191 params = scrub_none_parameters(params)
192
193 try:
194 key = import_key_pair(ec2_client, **params)
195 except AnsibleEC2Error as e:
196 raise Ec2KeyFailure(e, "error importing key")
197 return key
198
199
200 def extract_key_data(key, key_type=None, file_name=None):
201 data = {
202 "name": key["KeyName"],
203 "fingerprint": key["KeyFingerprint"],
204 "id": key["KeyPairId"],
205 "tags": boto3_tag_list_to_ansible_dict(key.get("Tags") or []),
206 # KeyMaterial is returned by create_key_pair, but not by describe_key_pairs
207 "private_key": key.get("KeyMaterial"),
208 # KeyType is only set by describe_key_pairs
209 "type": key.get("KeyType") or key_type,
210 }
211
212 # Write the private key to disk and remove it from the return value
213 if file_name and data["private_key"] is not None:
214 data = _write_private_key(data, file_name)
215 return scrub_none_parameters(data)
216
217
218 def get_key_fingerprint(check_mode, ec2_client, key_material):
219 """
220 EC2's fingerprints are non-trivial to generate, so push this key
221 to a temporary name and make ec2 calculate the fingerprint for us.
222 http://blog.jbrowne.com/?p=23
223 https://forums.aws.amazon.com/thread.jspa?messageID=352828
224 """
225 # find an unused name
226 name_in_use = True
227 while name_in_use:
228 random_name = "ansible-" + str(uuid.uuid4())
229 name_in_use = find_key_pair(ec2_client, random_name)
230 temp_key = _import_key_pair(ec2_client, random_name, key_material)
231 delete_key_pair(check_mode, ec2_client, random_name, finish_task=False)
232 return temp_key["KeyFingerprint"]
233
234
235 def find_key_pair(ec2_client, name):
236 try:
237 key = describe_key_pairs(ec2_client, KeyNames=[name])
238 if not key:
239 return None
240 except AnsibleEC2Error as e:
241 raise Ec2KeyFailure(e, "error finding keypair")
242 except IndexError:
243 key = None
244
245 return key[0]
246
247
248 def _create_key_pair(ec2_client, name, tag_spec, key_type):
249 params = {
250 "KeyName": name,
251 "TagSpecifications": tag_spec,
252 "KeyType": key_type,
253 }
254
255 params = scrub_none_parameters(params)
256
257 try:
258 key = create_key_pair(ec2_client, **params)
259 except AnsibleEC2Error as e:
260 raise Ec2KeyFailure(e, "error creating key")
261 return key
262
263
264 def _write_private_key(key_data, file_name):
265 """
266 Write the private key data to the specified file, and remove 'private_key'
267 from the ouput. This ensures we don't expose the key data in logs or task output.
268 """
269 try:
270 file = os.open(file_name, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)
271 os.write(file, key_data["private_key"].encode("utf-8"))
272 os.close(file)
273 except (IOError, OSError) as e:
274 raise Ec2KeyFailure(e, "Could not save private key to specified path. Private key is irretrievable.")
275
276 del key_data["private_key"]
277 return key_data
278
279
280 def create_new_key_pair(ec2_client, name, key_material, key_type, tags, file_name, check_mode):
281 """
282 key does not exist, we create new key
283 """
284 if check_mode:
285 return {"changed": True, "key": None, "msg": "key pair created"}
286
287 tag_spec = boto3_tag_specifications(tags, ["key-pair"])
288 if key_material:
289 key = _import_key_pair(ec2_client, name, key_material, tag_spec)
290 else:
291 key = _create_key_pair(ec2_client, name, tag_spec, key_type)
292 key_data = extract_key_data(key, key_type, file_name)
293
294 result = {"changed": True, "key": key_data, "msg": "key pair created"}
295 return result
296
297
298 def update_key_pair_by_key_material(check_mode, ec2_client, name, key, key_material, tag_spec):
299 if check_mode:
300 return {"changed": True, "key": None, "msg": "key pair updated"}
301 new_fingerprint = get_key_fingerprint(check_mode, ec2_client, key_material)
302 changed = False
303 msg = "key pair already exists"
304 if key["KeyFingerprint"] != new_fingerprint:
305 delete_key_pair(check_mode, ec2_client, name, finish_task=False)
306 key = _import_key_pair(ec2_client, name, key_material, tag_spec)
307 msg = "key pair updated"
308 changed = True
309 key_data = extract_key_data(key)
310 return {"changed": changed, "key": key_data, "msg": msg}
311
312
313 def update_key_pair_by_key_type(check_mode, ec2_client, name, key_type, tag_spec, file_name):
314 if check_mode:
315 return {"changed": True, "key": None, "msg": "key pair updated"}
316 else:
317 delete_key_pair(check_mode, ec2_client, name, finish_task=False)
318 key = _create_key_pair(ec2_client, name, tag_spec, key_type)
319 key_data = extract_key_data(key, key_type, file_name)
320 return {"changed": True, "key": key_data, "msg": "key pair updated"}
321
322
323 def delete_key_pair(check_mode, ec2_client, name, finish_task=True):
324 key = find_key_pair(ec2_client, name)
325
326 if key and check_mode:
327 result = {"changed": True, "key": None, "msg": "key deleted"}
328 elif not key:
329 result = {"key": None, "msg": "key did not exist"}
330 return result
331 else:
332 try:
333 delete_ec2_key_pair(ec2_client, name)
334 except AnsibleEC2Error as e:
335 raise Ec2KeyFailure(e, "error deleting keypair")
336 if not finish_task:
337 return
338 result = {"changed": True, "key": None, "msg": "key deleted"}
339
340 return result
341
342
343 def handle_existing_key_pair_update(module, ec2_client, name, key):
344 key_material = module.params.get("key_material")
345 force = module.params.get("force")
346 key_type = module.params.get("key_type")
347 tags = module.params.get("tags")
348 purge_tags = module.params.get("purge_tags")
349 tag_spec = boto3_tag_specifications(tags, ["key-pair"])
350 check_mode = module.check_mode
351 file_name = module.params.get("file_name")
352 if key_material and force:
353 result = update_key_pair_by_key_material(check_mode, ec2_client, name, key, key_material, tag_spec)
354 elif key_type and key_type != key["KeyType"]:
355 result = update_key_pair_by_key_type(check_mode, ec2_client, name, key_type, tag_spec, file_name)
356 else:
357 changed = False
358 changed |= ensure_ec2_tags(ec2_client, module, key["KeyPairId"], tags=tags, purge_tags=purge_tags)
359 key = find_key_pair(ec2_client, name)
360 key_data = extract_key_data(key, file_name=file_name)
361 result = {"changed": changed, "key": key_data, "msg": "key pair already exists"}
362 return result
363
364
365 def main():
366 argument_spec = dict(
367 name=dict(required=True),
368 key_material=dict(no_log=False),
369 force=dict(type="bool", default=True),
370 state=dict(default="present", choices=["present", "absent"]),
371 tags=dict(type="dict", aliases=["resource_tags"]),
372 purge_tags=dict(type="bool", default=True),
373 key_type=dict(type="str", choices=["rsa", "ed25519"]),
374 file_name=dict(type="path", required=False),
375 )
376
377 module = AnsibleAWSModule(
378 argument_spec=argument_spec,
379 mutually_exclusive=[["key_material", "key_type"]],
380 supports_check_mode=True,
381 )
382
383 ec2_client = module.client("ec2")
384
385 name = module.params["name"]
386 state = module.params.get("state")
387 key_material = module.params.get("key_material")
388 key_type = module.params.get("key_type")
389 tags = module.params.get("tags")
390 file_name = module.params.get("file_name")
391
392 result = {}
393
394 try:
395 if state == "absent":
396 result = delete_key_pair(module.check_mode, ec2_client, name)
397
398 elif state == "present":
399 # check if key already exists
400 key = find_key_pair(ec2_client, name)
401 if key:
402 result = handle_existing_key_pair_update(module, ec2_client, name, key)
403 else:
404 result = create_new_key_pair(
405 ec2_client, name, key_material, key_type, tags, file_name, module.check_mode
406 )
407
408 except Ec2KeyFailure as e:
409 if e.original_e:
410 module.fail_json_aws(e.original_e, e.message)
411 else:
412 module.fail_json(e.message)
413
414 module.exit_json(**result)
415
416
417 if __name__ == "__main__":
418 main()