aaron dodd dot com

Calling AWS for current nodes in a group instead of hardcoding public IPs

17 Mar 2017 - Aaron Dodd

When integrating CI/CD with cloud instances, the old-school method of specifying a server IP is problematic since a well-architected cloud solution allows for instance to be replaced as needed. Instead, Jenkins or other processes should verify the current running nodes before issuing a connection attempt.

Below is a sample query that return the public DNS names of servers tagged with a certain value (Group=fancyapp1).

aws ec2 describe-instances  --region us-east-1 --filters "Name=tag:Group,Values=fancyapp1" --output json --query 'Reservations[*].Instances[*].{Name:Tags[?Key==`Name`].Value,PublicIP:PublicIpAddress}'

The response would look like:

[
    [
        {
            "Name": [
                "myfancyappserver-1516203598"
            ],
            "PublicIP": "52.187.211.151"
        }
    ],
    [
        {
            "Name": [
                "myfancyappserver2-1516200980"
            ],
            "PublicIP": "52.211.223.141"
        }
    ]
]

Or, if you just want the first node, change Reservations[*] to Reservations[0]. And if you only want the public IP, remove the Name: part of the query and change output to –text:

aws ec2 describe-instances  --region us-east-1 --filters "Name=tag:Group,Values=myfancyapp1" --output text --query 'Reservations[0].Instances[*].{PublicIP:PublicIpAddress}'

In this case the output would be:

52.187.211.151

From the source script, you could just set the result of the above to a variable for the server to connect to.