Skip to content

Commit

Permalink
feat: add option to use instance's private IP to connect to it
Browse files Browse the repository at this point in the history
  • Loading branch information
nikromen committed Oct 3, 2023
1 parent 4ea1093 commit 84ebbd0
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
3 changes: 3 additions & 0 deletions resalloc_ibm_cloud/argparsers.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ def vm_arg_parser():
parser_create.add_argument("--ssh-key-id", required=True)
parser_create.add_argument("--instance-type", help="e.g. cz2-2x4", required=True)
parser_create.add_argument("--floating-ip-name", default=None)
parser_create.add_argument(
"--no-floating-ip", action="store_true", help="Don't use floating IPs (for VPN)"
)
parser_create.add_argument(
"--zones",
help=(
Expand Down
30 changes: 29 additions & 1 deletion resalloc_ibm_cloud/ibm_cloud_vm.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@
import random
import subprocess
import sys
from time import sleep

import requests

from resalloc_ibm_cloud.helpers import get_service
Expand Down Expand Up @@ -106,6 +108,26 @@ def run_playbook(host, opts):
subprocess.check_call(cmd, stdout=sys.stderr)


def _get_zone_and_subnet_id(opts):
random_subnet = random.choice(opts.subnets_ids)
if ":" in random_subnet:
return tuple(random_subnet.split(":"))
return opts.zone, random_subnet


def _get_private_ip_of_instance(instance_id, service):
for _ in range(300):
private_ip = service.get_instance(
instance_id
)["primary_network_interface"]["primary_ip"]["address"]
if private_ip != "0.0.0.0":
return private_ip

sleep(5)

raise TimeoutError("Instance creation took too much time")


def create_instance(service, instance_name, opts):
"""
Start the VM, name it "instance_name"
Expand Down Expand Up @@ -167,7 +189,13 @@ def create_instance(service, instance_name, opts):
log.debug("Instance response[result]: %s", opts.instance_created)
instance_id = opts.instance_created["id"]
log.info("Instance ID: %s", instance_id)
ip_address = assign_floating_ip(service, instance_id, opts)

if opts.no_floating_ip:
# assuming you have access through to private IP address
ip_address = _get_private_ip_of_instance(instance_id, service)
else:
ip_address = assign_floating_ip(service, instance_id, opts)

_wait_for_ssh(ip_address)
run_playbook(ip_address, opts)
# Tell the Resalloc clients how to connect to this instance.
Expand Down

0 comments on commit 84ebbd0

Please sign in to comment.