Skip to content

Instantly share code, notes, and snippets.

@Nitecon
Created January 31, 2025 19:58
Show Gist options
  • Save Nitecon/e838f98f82fae4be0bdaa4ee2a08cd2f to your computer and use it in GitHub Desktop.
Save Nitecon/e838f98f82fae4be0bdaa4ee2a08cd2f to your computer and use it in GitHub Desktop.
Quick example using bruce.tools 1.5 to standup a new ec2 instance, run a command and then terminate the instance.
---
variables:
INSTANCE_TYPE: t2.micro
steps:
# Create a new aws ec2 instance, but only if none already exist (notIf)
- cmd: aws ec2 run-instances --image-id ami-0c614dee691cbbf37 --count 1 --instance-type {{.INSTANCE_TYPE}} --key-name YourKey --subnet-id subnet-07317935cd9123d --tag-specifications 'ResourceType=instance,Tags=[{Key=BoxType,Value=TestMe}]'
notIf: INSTANCE_IP=$(aws ec2 describe-instances --filters Name=tag:BoxType,Values=TestMe --query "Reservations[*].Instances[0].PublicIpAddress" --output text); if [ ! -z "$INSTANCE_IP" ] && [ "$INSTANCE_IP" != "None" ]; then echo "instance up"; fi
setEnv: NEW_INSTANCE
# Get the ip address of the instance so we can connect
- cmd: 'for i in {1..12}; do INSTANCE_IP=$(aws ec2 describe-instances --filters Name=tag:BoxType,Values=TestMe --query "Reservations[*].Instances[0].PublicIpAddress" --output text); if [ -n "$INSTANCE_IP" ] && [ "$INSTANCE_IP" != "None" ]; then echo "$INSTANCE_IP"; break; fi; sleep 5; done'
setEnv: INSTANCE_IP
- sleep: 90 # to make sure instance comes up properly, but only if the instance doesn't exist yet.
notIf: if [ "{{.NEW_INSTANCE}}" != "" ]; then echo "new instance"; fi
# Use echo to state what we are connecting to, but exit the run if the instance ip is not set
- cmd: 'echo "Connecting to: {{.INSTANCE_IP}}"'
exitIf: if [ -z "{{.INSTANCE_IP}}" ]; then echo "No IP Address"; fi
# run a remote command on the ec2 box and capture the output into remhost environment variable
- remoteCmd: hostname -f
host: ec2-user@{{.INSTANCE_IP}}
allowInsecure: true
setEnv: remhost
# use cmd to echo out the envar that was set
- cmd: echo "Ran echo on {{.remhost}}"
# now we just terminate the instance as we no longer need it.
- cmd: aws ec2 terminate-instances --instance-ids $(aws ec2 describe-instances --filters "Name=tag:BoxType,Values=TestMe" --query "Reservations[*].Instances[0].InstanceId" --output text) && echo "Instance terminated."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment