EC2

  1#!/usr/bin/env python3
  2# This file is part of pycloudlib. See LICENSE file for license information.
  3"""Basic examples of various lifecycle with an EC2 instance."""
  4
  5import logging
  6import os
  7
  8import pycloudlib
  9from pycloudlib.cloud import ImageType
 10
 11
 12def hot_add(ec2, daily):
 13    """Hot add to an instance.
 14
 15    Give an example of hot adding a pair of network interfaces and a
 16    couple storage volumes of various sizes.
 17    """
 18    with ec2.launch(daily, instance_type="m4.xlarge") as instance:
 19        instance.wait()
 20        # Add NIC with 2 private ips
 21        instance.add_network_interface(ipv4_address_count=2)
 22        instance.add_network_interface()
 23
 24        instance.add_volume(size=9)
 25        instance.add_volume(size=10, drive_type="gp2")
 26
 27
 28def launch_multiple(ec2, daily):
 29    """Launch multiple instances.
 30
 31    How to quickly launch multiple instances with EC2. This prevents
 32    waiting for the instance to start each time.
 33    """
 34    instances = []
 35    for _ in range(3):
 36        instances.append(ec2.launch(daily))
 37
 38    for instance in instances:
 39        instance.wait()
 40
 41    for instance in instances:
 42        instance.delete(wait=False)
 43
 44    for instance in instances:
 45        instance.wait_for_delete()
 46
 47
 48def snapshot(ec2, daily):
 49    """Create a snapshot from a customized image and launch it."""
 50    with ec2.launch(daily) as instance:
 51        instance.wait()
 52        instance.execute("touch custom_config_file")
 53
 54        image = ec2.snapshot(instance)
 55        new_instance = ec2.launch(image)
 56        new_instance.wait()
 57        new_instance.execute("ls")
 58
 59        new_instance.delete()
 60        ec2.delete_image(image)
 61
 62
 63def custom_vpc(ec2, daily):
 64    """Launch instances using a custom VPC."""
 65    vpc = ec2.get_or_create_vpc(name="test-vpc")
 66    with ec2.launch(daily, vpc=vpc) as instance:
 67        instance.wait()
 68        instance.execute("whoami")
 69
 70    # vpc.delete will also delete any associated instances in that VPC
 71    vpc.delete()
 72
 73
 74def launch_basic(ec2, daily):
 75    """Show basic functionality on instances.
 76
 77    Simple launching of an instance, run a command, and delete.
 78    """
 79    with ec2.launch(daily) as instance:
 80        instance.wait()
 81        instance.console_log()
 82        print(instance.execute("lsb_release -a"))
 83
 84        instance.shutdown()
 85        instance.start()
 86        instance.restart()
 87
 88        # Various Attributes
 89        print(instance.ip)
 90        print(instance.id)
 91        print(instance.image_id)
 92        print(instance.availability_zone)
 93
 94
 95def launch_pro(ec2, name, image):
 96    """Show basic functionality on Pro instances."""
 97    print("Launching {} instance...".format(name))
 98    with ec2.launch(image) as instance:
 99        instance.wait()
100        print(instance.execute("sudo pro status --wait"))
101        print("Deleting {} instance...".format(name))
102
103
104def handle_ssh_key(ec2, key_name):
105    """Manage ssh keys to be used in the instances."""
106    if key_name in ec2.list_keys():
107        ec2.delete_key(key_name)
108
109    key_pair = ec2.client.create_key_pair(KeyName=key_name)
110    private_key_path = "ec2-test.pem"
111    with open(private_key_path, "w", encoding="utf-8") as stream:
112        stream.write(key_pair["KeyMaterial"])
113    os.chmod(private_key_path, 0o600)
114
115    # Since we are using a pem file, we don't have distinct public and
116    # private key paths
117    ec2.use_key(
118        public_key_path=private_key_path,
119        private_key_path=private_key_path,
120        name=key_name,
121    )
122
123
124def demo():
125    """Show example of using the EC2 library.
126
127    Connects to EC2 and finds the latest daily image. Then runs
128    through a number of examples.
129    """
130    with pycloudlib.EC2(tag="examples") as ec2:
131        key_name = "test-ec2"
132        handle_ssh_key(ec2, key_name)
133
134        daily = ec2.daily_image(release="focal")
135        daily_pro = ec2.daily_image(release="focal", image_type=ImageType.PRO)
136        daily_pro_fips = ec2.daily_image(release="focal", image_type=ImageType.PRO_FIPS)
137        daily_pro_fips_updates = ec2.daily_image(
138            release="focal", image_type=ImageType.PRO_FIPS_UPDATES
139        )
140
141        launch_basic(ec2, daily)
142        launch_pro(ec2, "PRO", daily_pro)
143        launch_pro(ec2, "PRO FIPS", daily_pro_fips)
144        launch_pro(ec2, "PRO FIPS UPDATES", daily_pro_fips_updates)
145        custom_vpc(ec2, daily)
146        snapshot(ec2, daily)
147        launch_multiple(ec2, daily)
148        hot_add(ec2, daily)
149
150
151if __name__ == "__main__":
152    logging.basicConfig(level=logging.DEBUG)
153    demo()