Skip to content

Instantly share code, notes, and snippets.

@gilfreund
Last active April 5, 2024 23:12
Show Gist options
  • Save gilfreund/aef50aeea964f0642ed136bdbfccc80c to your computer and use it in GitHub Desktop.
Save gilfreund/aef50aeea964f0642ed136bdbfccc80c to your computer and use it in GitHub Desktop.
Launch an EC@ instance the get the intance ID and IP

A script to start a spot instance based on a template.

Provide instance type, AMI ID and an owner id, and the script will launch and instance naming it on the owner id and AMI id, and will return the instance ID and external IP

The tamplate used is a spot template (hence the name), but any template will do. The usage of the template is mainly to provide easier inclusion of keys, role and user data.

#!/bin/bash
LAUNCHTEMPLATEID=lt-04f7a88addea07001
INTANCETYPE=p3.2xlarge
REGION=$(curl http://169.254.169.254/latest/meta-data/placement/availability-zone | cut -c1-9)
AWSCMD="aws --region $REGION --output text
IMAGEID=$($AWSCMD ssm get-parameters --names /aws/service/ami-amazon-linux-latest/amzn2-ami-hvm-x86_64-gp2 | cut -f 6)
TAGVALUEOWNER=$($AWSCMD iam get-user| awk '{printf $7}')
SNAPSHITID=$($AWSCMD ec2 describe-images --image-id $IMAGEID | grep snap- | awk -F" " '{print $4}')
BOOTDEVICESIZE=$($AWSCMD ec2 describe-images --image-id $IMAGEID | grep snap- | awk -F" " '{print $5}')
EXTERNALIP=
INSTANCEID=$($AWSCMD ec2 run-instances --launch-template LaunchTemplateId=$LAUNCHTEMPLATEID --instance-type $INTANCETYPE --image-id $IMAGEID --tag-specifications "ResourceType=instance,Tags=[{Key=Owner,Value=$TAGVALUEOWNER},{Key=name,Value=$TAGVALUEOWNER-$INTANCETYPE}]" --block-device-mappings "[{\"DeviceName\":\"/dev/xvda\",\"Ebs\":{\"VolumeSize\":$BOOTDEVICESIZE,\"SnapshotId\":\"$SNAPSHITID\"}}]" --region $REGION | grep INSTANCES | awk -F" " '{print $7}')
echo Instance ID is $INSTANCEID
waiting for IP
EXTERNALIP=$($AWSCMD ec2 describe-instances --instance-ids $INSTANCEID --query 'Reservations[*].Instances[*].PublicIpAddress')
echo IP is "$EXTERNALIP"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment