GCE

 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 GCE instance."""
 4
 5import logging
 6import os
 7
 8import pycloudlib
 9from pycloudlib.cloud import ImageType
10
11
12def manage_ssh_key(gce):
13    """Manage ssh keys for gce instances."""
14    pub_key_path = "gce-pubkey"
15    priv_key_path = "gce-privkey"
16    pub_key, priv_key = gce.create_key_pair()
17
18    with open(pub_key_path, "w", encoding="utf-8") as f:
19        f.write(pub_key)
20
21    with open(priv_key_path, "w", encoding="utf-8") as f:
22        f.write(priv_key)
23
24    os.chmod(pub_key_path, 0o600)
25    os.chmod(priv_key_path, 0o600)
26
27    gce.use_key(public_key_path=pub_key_path, private_key_path=priv_key_path)
28
29
30def generic(gce):
31    """Show example of using the GCE library.
32
33    Connects to GCE and finds the latest daily image. Then runs
34    through a number of examples.
35    """
36    daily = gce.daily_image("bionic", arch="x86_64")
37    with gce.launch(daily) as inst:
38        inst.wait()
39        print(inst.execute("lsb_release -a"))
40
41
42def pro(gce, series, image_type):
43    """Show example of running a GCE PRO machine."""
44    daily = gce.daily_image(series, image_type)
45    with gce.launch(daily) as inst:
46        inst.wait()
47        print(inst.execute("sudo pro status --wait"))
48
49
50def demo():
51    """Show examples of launching GCP instances."""
52    logging.basicConfig(level=logging.DEBUG)
53    with pycloudlib.GCE(tag="examples") as gce:
54        manage_ssh_key(gce)
55
56        generic(gce)
57        pro(gce, "focal", ImageType.PRO)
58        pro(gce, "focal", ImageType.PRO_FIPS)
59        pro(gce, "jammy", ImageType.PRO_FIPS_UPDATES)
60
61
62if __name__ == "__main__":
63    demo()