in scripts/testing/cli.py [0:0]
def create_vm(name, vm_type, vm_zone):
"""
Creates a new VM and waits until the startup script finishes its work
"""
with click.progressbar(label="Creating a new VM...", length=100) as steps:
cmd = [
"gcloud",
"compute",
"instances",
"create",
name,
"--async",
"--source-machine-image",
SOURCE_MACHINE_IMAGE,
"--image-family",
IMAGE_FAMILY,
"--machine-type",
vm_type,
"--zone",
vm_zone,
f"--metadata-from-file={VM_STARTUP_SCRIPT_PATH}",
]
result = run_gcloud_cmd(cmd)
steps.update(25)
attempts = 0
while True:
if attempts >= VM_INIT_ATTEMPTS:
click.echo("Timeout!")
raise click.Abort()
attempts = attempts + 1
# Tries to ssh to the VM and check if the startup script finished its work
cmd = [
"gcloud",
"compute",
"ssh",
name,
"--zone",
vm_zone,
"--ssh-flag=",
"-q",
"--command",
"sudo ls /var/log/startup-is-finished ",
]
result = subprocess.run( # noqa: S603
cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
)
stdout = result.stdout.decode("utf-8")
# indicates that the VM is booting
if re.search("Connection refused", stdout) or re.search(
"SSH connectivity issues", stdout
):
steps.update(25)
# indicates that the VM is ready but the startup script
elif result.returncode == 1 or result.returncode == 2:
pass
elif result.returncode == 0:
steps.update(25)
break
else:
click.echo(stdout)
raise click.Abort()
time.sleep(SLEEP_TIMEOUT)
# update the VM metadata
cmd = [
"gcloud",
"compute",
"instances",
"add-metadata",
name,
"--zone",
vm_zone,
"--metadata",
f"division={DIVISION},org={ORG},team={TEAM},project={PROJECT}",
]
run_gcloud_cmd(cmd)
steps.update(25)