Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Automate checking running instances #114

Open
wants to merge 2 commits into
base: humble
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 28 additions & 0 deletions fogros2/utils/check_running_instances.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import jmespath
import boto3
import configparser
import os


def get_all_instances():
config = configparser.ConfigParser()
config.read(os.path.join(os.path.expanduser('~'), '.aws/credentials'))
ec2_client = boto3.client('ec2')
regions = [region['RegionName']
for region in ec2_client.describe_regions()['Regions']]

result = []
for profile in config.sections():
for region in regions:
current_session = boto3.Session(profile_name = profile, region_name = region)
client = current_session.client('ec2')
response = client.describe_instances()
output = jmespath.search("Reservations[].Instances[].[NetworkInterfaces[0].OwnerId, InstanceId, InstanceType, \
State.Name, Placement.AvailabilityZone, PrivateIpAddress, PublicIpAddress, KeyName, [Tags[?Key=='Name'].Value] [0][0]]", response)
if output and any("FogROS" in instance[7] for instance in output):
result.append(output)

return result

def get_running_instances():
return [[instance for instance in region if "running" in instance] for region in get_all_instances()]
8 changes: 7 additions & 1 deletion fogros2_examples/launch/talker.auto_aws.launch.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@

from launch_ros.actions import Node
import fogros2
from utils import region_ami_selection, ec2_instance_type_selection
from utils import region_ami_selection, ec2_instance_type_selection, check_running_instances


def generic_ubuntu_ami():
Expand All @@ -57,6 +57,12 @@ def generate_launch_description():
ec2_instance_type = ec2_instance_type_selection.find_cheapest_ec2_instance_type(region)

print(region, ami, ec2_instance_type)

all_instances = check_running_instances.get_all_instances()
running_instances = check_running_instances.get_running_instances()
print("All instances: ", all_instances)
print("Running instances: ", running_instances)

machine1 = fogros2.AWSCloudInstance(
region=region, ec2_instance_type=ec2_instance_type, ami_image=ami
)
Expand Down