Creating an SSH key-pair

When an OpenStack virtual machine is launched, you need an SSH key-pair to log in to the virtual machine.

In the following code, we first determine if there's already an existing keypair with the same name. If there isn't, we invoke the create_keypair() function of the compute class and pass the name of the keypair that we want to create. This function returns a keypair object, which can be used to extract the private key. We then write this private key to a local file. You may choose to write this file in your .ssh folder in your home directory:

def create_keypair(conn): 
keypair_name = "packtpub-keypair" # The name of the keypair to be created
private_key_file = "private.key" # The name of the file that stores the private key
keypair = conn.compute.find_keypair(keypair_name)

if not keypair:
keypair = conn.compute.create_keypair(name=keypair_name) # Create a keypair

with open(private_key_file, 'w') as filehandle:
filehandle.write("%s" % keypair.private_key) # Write the private key to a file
os.chmod(private_key_file, 0o400) # Change the permission of the key file

return keypair
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.217.7.117