Skip to content

Instantly share code, notes, and snippets.

@swithrow
Last active August 18, 2023 15:16
Show Gist options
  • Save swithrow/05add0d405f7cce18265 to your computer and use it in GitHub Desktop.
Save swithrow/05add0d405f7cce18265 to your computer and use it in GitHub Desktop.
EC2 Instance Name Tag in the bash prompt.
#!/bin/bash
#
# copy this into /etc/profile.d/instance-name-tag.sh
#
# you will need:
# - curl, jq, and aws cli installed
# - an IAM role that gives the EC2 instance access to describe tags
#
## get instance info
INSTANCE=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document|jq .instanceId|tr -d '"')
## use region the instance is in as default region
export AWS_DEFAULT_REGION=$(curl -s http://169.254.169.254/latest/dynamic/instance-identity/document|jq .region|tr -d '"')
## make sure aws stuff is in the path
PATH="/opt/aws/bin:$PATH"
## grab the Name tag for this instance
NAMETAG=$(aws ec2 describe-tags --filters Name=resource-id,Values=$INSTANCE Name=key,Values=Name|jq ".Tags[0].Value"|tr -d '"')
export PS1="\\t [\\u@${NAMETAG} \\W]\\\$ "
@btisdall
Copy link

btisdall commented May 8, 2019

The tr invocations can be avoided by using jq's raw mode, ie jq -r ...

@piotr-ce
Copy link

piotr-ce commented Jun 6, 2019

it's great but jq is not always installed, I use below if it helps someone
INSTANCE_ID=$(wget -qO- http://instance-data/latest/meta-data/instance-id)
REGION=$(wget -qO- http://instance-data/latest/meta-data/placement/availability-zone | sed 's/.$//')
export PS1="$(aws ec2 describe-tags --region $REGION --filter "Name=resource-id,Values=$INSTANCE_ID" --output=text | cut -f5)$ "

@miglen
Copy link

miglen commented Sep 29, 2020

Howdy, I have created a sample script as well: https://gist.github.com/miglen/e2e577b95acf1171a1853871737323ce

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment