# [EN] How I Stopped Copy-Pasting AWS EC2 IPs and Started SSHing Smarter

![](https://cdn.hashnode.com/res/hashnode/image/upload/v1747819707681/9b61369a-d022-4719-8d38-6a5dfbe7e365.png align="center")

Remembering IP in a massive, dynamic environment is not easy. You may have an instance with IP 10.0.0.1 today, but there is no guarantee that the same server will be there tomorrow. If you are still SSH-ing to your server using a traditional method like `ssh user@ip_address`you’ll have a hard time remembering the IP address of that server. Wouldn't it be easier to just run `server_a` or `server_b` to get into that particular server? You just have to know the name of the server, which is easier to remember. Also, the command is dynamically updated when a new server is created or deleted.

# tl;dr

* Allow the bastion host to read EC2 metadata
    
* Create a Python script to get all the instance names and private IPv4 addresses
    
* Add the command alias to your `.bashrc` or `.zshrc` file.
    
* Add cron to run the script automatically and update your alias.
    

# Allow Bastion host to get EC2 instances

<div data-node-type="callout">
<div data-node-type="callout-emoji">💡</div>
<div data-node-type="callout-text">Please review the IAM policy to comply with your security standards. Don’t blindly copy and paste.</div>
</div>

1. The script will get all the EC2 data using the `describe-instances` command. Create an AWS IAM policy to allow read access to the instances:
    
    ```json
    {
      "Version": "2012-10-17",
      "Statement": [
        {
          "Effect": "Allow",
          "Action": "ec2:DescribeInstances",
          "Resource": "*"
        }
      ]
    }
    ```
    
2. Create or modify your existing Bastion IAM role to attach this IAM policy.
    
3. Verify the access by running `aws ec2 describe-instances` inside the Bastion host.
    

# Create a script to generate the command alias

The idea is to generate this output that can be fed to the `.bashrc`:

```bash
alias server_a="ssh ubuntu@private_ipv4_address"
...
```

Here’s the Python code to do that:

%[https://gist.github.com/roboticpuppies/c0078aea83866fda9488ed55d464fb1d] 

Generate the alias and write it to `~/.awsvmaliases`:

```bash
python3 aliasgen.py > ~/.awsvmaliases
```

# Automatically load the aliases

To automatically load those aliases when you open the terminal, open your `.bashrc` or `.zshrc` file and append this line:

```bash
...
source ~/.awsvmaliases
```

# Automatically update the list

In my case, it is sufficient to update the script once an hour. So I just use cron to update the aliases:

```bash
# Inside the crontab
@hourly /usr/bin/python3 path/to/aliasgen.py > ~/.awsvmaliases
```

If you need to manually update the list without waiting for cron to run, you can run this command:

```bash
python3 path/to/aliasgen.py > ~/.awsvmaliases
# If you use bash shell, tell bash to reload the .bashrc file and read the changes
source ~/.bashrc
```
