From b66006280186ab4295dc7a7fdee467076993c322 Mon Sep 17 00:00:00 2001 From: James Tanner Date: Thu, 3 Apr 2014 13:53:43 -0400 Subject: [PATCH] Fixes #6454 verify ec2 key fingerprints --- library/cloud/ec2_key | 47 +++++++++++++++++++++++++++++++++++++++---- 1 file changed, 43 insertions(+), 4 deletions(-) diff --git a/library/cloud/ec2_key b/library/cloud/ec2_key index 9e94d22a0b3..99ea5bcc3e0 100644 --- a/library/cloud/ec2_key +++ b/library/cloud/ec2_key @@ -132,6 +132,10 @@ except ImportError: print "failed=True msg='boto required for this module'" sys.exit(1) +import random +import string + + def main(): argument_spec = ec2_argument_spec() argument_spec.update(dict( @@ -187,10 +191,45 @@ def main(): # Ensure requested key is present elif state == 'present': if key: - '''existing key found''' - # Should check if the fingerprint is the same - but lack of info - # and different fingerprint provided (pub or private) depending if - # the key has been created of imported. + # existing key found + if key_material: + # EC2's fingerprints are non-trivial to generate, so push this key + # to a temporary name and make ec2 calculate the fingerprint for us. + # + # http://blog.jbrowne.com/?p=23 + # https://forums.aws.amazon.com/thread.jspa?messageID=352828 + + # find an unused name + test = 'empty' + while test: + randomchars = [random.choice(string.ascii_letters + string.digits) for x in range(0,10)] + tmpkeyname = "ansible-" + ''.join(randomchars) + test = ec2.get_key_pair(tmpkeyname) + + # create tmp key + tmpkey = ec2.import_key_pair(tmpkeyname, key_material) + # get tmp key fingerprint + tmpfingerprint = tmpkey.fingerprint + # delete tmp key + tmpkey.delete() + + if key.fingerprint != tmpfingerprint: + if not module.check_mode: + key.delete() + key = ec2.import_key_pair(name, key_material) + + if wait: + start = time.time() + action_complete = False + while (time.time() - start) < wait_timeout: + if ec2.get_key_pair(name): + action_complete = True + break + time.sleep(1) + if not action_complete: + module.fail_json(msg="timed out while waiting for the key to be re-created") + + changed = True pass # if the key doesn't exist, create it now