Skip to content

Instantly share code, notes, and snippets.

@KrisAff84
Last active July 15, 2023 15:07
Show Gist options
  • Save KrisAff84/abc8de147e7430643389ed1640c05d49 to your computer and use it in GitHub Desktop.
Save KrisAff84/abc8de147e7430643389ed1640c05d49 to your computer and use it in GitHub Desktop.
Starts a 3 node docker swarm of EC2 instances and changes the HostName IP in your .ssh/config file. Replace the variables under 'def main()' with your own information
import boto3
def start_docker_fleet(node1, node2, node3):
ec2 = boto3.client('ec2')
waiter = ec2.get_waiter('instance_stopped')
waiter.wait(InstanceIds=[node1, node2, node3])
response = ec2.start_instances(
InstanceIds=[
node1,
node2,
node3
],
)
def get_public_ip(node1, config_file, line_number):
print()
print('Waiting for instances to start...')
ec2 = boto3.client('ec2')
waiter = ec2.get_waiter('instance_running')
waiter.wait(InstanceIds=[node1])
response = ec2.describe_instances(
InstanceIds=[
node1
],
)
print()
for instance in response['Reservations']:
print('Public IP of Node1:', instance['Instances'][0]['PublicIpAddress'])
new_ip = instance['Instances'][0]['PublicIpAddress']
with open(config_file, 'r') as file:
lines = file.readlines()
lines[line_number - 1] = f" HostName {new_ip} \n"
with open(config_file, 'w') as file:
file.writelines(lines)
print()
print('New IP of Node1 successfully written to config file')
print()
def main():
node1='i-05747a9d38a158d23' # Place the instance ID of node 1 here
node2='i-06545abf9d8303298' # Place the instance ID of node 2 here
node3='i-0259a1b93d8e0c690' # Place the instance ID of node 3 here
config_file='/Users/Kris/.ssh/config' # Replace with the absolute path to your .ssh/config file
line_number = 5 # The line number of your HostName to be changed in the config file
start_docker_fleet(node1, node2, node3)
get_public_ip(node1, config_file, line_number)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment