Skip to content

Instantly share code, notes, and snippets.

@namnv609
Last active January 19, 2022 07:41
Show Gist options
  • Save namnv609/fcef35f313d1c02dcf2de27cbfaeacb5 to your computer and use it in GitHub Desktop.
Save namnv609/fcef35f313d1c02dcf2de27cbfaeacb5 to your computer and use it in GitHub Desktop.
Simple script to update SSH config file from AutoScaling groups
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""Update SSH config file from AutoScaling groups
Author: NamNV609
Copyright: 2022, NamNV609
Homepage: https://github.com/namnv609
"""
import subprocess
import json
import os
def exec_aws_cmd(cmd):
aws_response = subprocess.run(cmd, stdout=subprocess.PIPE)
return json.loads(aws_response.stdout.decode("utf-8"))
ssh_config_file = "/home/{username}/.ssh/config".format(username=os.environ.get("USER"))
bak_ssh_config_file = ssh_config_file + "_old"
print("-> Backup {current} to {bak} ...".format(current=ssh_config_file, bak=bak_ssh_config_file))
if os.path.isfile(ssh_config_file):
subprocess.run(["cp", "-f", ssh_config_file, bak_ssh_config_file], stdout=subprocess.PIPE)
print("-> Backup done!")
asg_names = []
ssh_config_content = []
for asg_name in asg_names:
print("-> Get instances for autoscaling group {asg_name} ...".format(asg_name=asg_name))
auto_scaling_groups = exec_aws_cmd(["aws", "autoscaling", "describe-auto-scaling-groups", "--auto-scaling-group-name", asg_name])
print("-> Get instances done!")
for instance in auto_scaling_groups["AutoScalingGroups"][0]["Instances"]:
instance_id = instance["InstanceId"]
print("-> Get private ip for {instance_id}".format(instance_id=instance_id))
instance_data = exec_aws_cmd(["aws", "ec2", "describe-instances", "--instance-ids", instance_id])
private_ip = instance_data["Reservations"][0]["Instances"][0]["PrivateIpAddress"]
print("-> Get private ip done!")
ssh_config_content.append("Host {asg_name}-{private_ip}".format(asg_name=asg_name, private_ip=private_ip))
ssh_config_content.append(" HostName {private_ip}".format(private_ip=private_ip))
ssh_config_content.append("")
print("Update ssh config file ...")
ssh_config = open(ssh_config_file, "w")
ssh_config.write("\n".join(ssh_config_content))
ssh_config.close()
print("Update done. Here is config content:")
print("========================================")
print("\n".join(ssh_config_content))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment