3
votes

I am trying to execute some bash script on EC2 instance using boto. Boto provides a way SSH to EC2 instance on public IP but in my case the instances have only private IP. The way SSH is done on these instance is using a host which can SSH on all the instance using private IP (Bastion host). Following is the script to connect to instance on public IP:

s3_client = boto3.client('s3')
s3_client.download_file('mybucket','key/mykey.pem', '/tmp/mykey.pem')
k = paramiko.RSAKey.from_private_key_file("/tmp/mykey.pem")
c = paramiko.SSHClient()
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
host=event
print "Connecting to " + host
c.connect( hostname = host, username = "ec2-user", pkey = k )

How to connect to instances if host have private IP instead of public key if we want to connect through bastion host with public IP P.P.P.P

1
Where are you running the script? On your own computer on the Internet, or on an Amazon EC2 instance? If EC2, is it in the same VPC? If it is outside of EC2 and you are trying to connect to instances in private subnets, then you need to SSH into the public instance, then somehow initiate another SSH connection from there into the private instances. - John Rotenstein
Yes, there is an instance to which I need to ssh first then from this instance I will ssh to instance in private subnet. How this could be achieved in the above script using paramiko. - drishti ahuja
You can't do this. You would need to SSH into a public-facing instance, then initiate another SSH session from the Public instance to the Private instance. - John Rotenstein
Did you setup any "redirect" or ssh tunneling service in your bastion host? - mootmoot

1 Answers

0
votes

If your requirement is to trigger execution of some code on an Amazon EC2 instance, then it would be better to use the Amazon EC2 Run Command rather than try to automate an SSH connection.

Amazon EC2 Run Command provides a simple way of automating common administrative tasks like executing Shell scripts and commands on Linux, running PowerShell commands on Windows, installing software or patches, and more. Amazon EC2 Run Command allows you to execute these commands across multiple instances and provides visibility into the results, making it easy to manage configuration change across fleets of instances.

Your instances would need the Amazon EC2 Systems Manager (SSM) agent installed. See: Installing SSM Agent

You would then run commands on Amazon EC2 instances from the management console, AWS Command-Line Interface (CLI) or via an API call.

The send command does not accept tags as input. However, you could first perform a list-instances command to search for instances by tag, then pass the instance-ids to the send command. See: AWS CLI send-command