Skip to content

Instantly share code, notes, and snippets.

@tboeghk
Created February 24, 2023 09:12
Show Gist options
  • Save tboeghk/873a184237769b3867f3c9dca9b57285 to your computer and use it in GitHub Desktop.
Save tboeghk/873a184237769b3867f3c9dca9b57285 to your computer and use it in GitHub Desktop.
Collecting AWS instance cost & spot metrics using Prometheus
# writes additional node_aws_info metrics to node exporter
* * * * * node-exporter /usr/local/bin/node-exporter-instance-info.sh
#!/usr/bin/env bash
#
# Collect AWS EC2 metadata for this instance
AWS_REGION=$(curl -s http://169.254.169.254/latest/meta-data/placement/region)
INSTANCE_LIFE_CYCLE=$(curl -s http://169.254.169.254/latest/meta-data/instance-life-cycle)
INSTANCE_TYPE=$(curl -s http://169.254.169.254/latest/meta-data/instance-type)
# Collect pricing from ec2.shop
INSTANCE_INFO=$(curl -sL "https://ec2.shop?region=${AWS_REGION}&filter=${INSTANCE_TYPE}" -H 'accept: json' | jq '.Prices[]')
instance_storage=$(echo ${INSTANCE_INFO} | jq -r .Storage)
instance_network=$(echo ${INSTANCE_INFO} | jq -r .Network)
instance_cost_hourly=$(echo ${INSTANCE_INFO} | jq -r .Cost)
instance_cost_monthly=$(echo ${INSTANCE_INFO} | jq -r .MonthlyPrice)
instance_spot_price=$(echo ${INSTANCE_INFO} | jq -r .SpotPrice)
if [ "${INSTANCE_LIFE_CYCLE}" = "spot" ] ; then
instance_cost_hourly_billed=${instance_spot_price}
else
instance_cost_hourly_billed=${instance_cost_hourly}
fi
# spot information
SPOT_INSTANCE_ACTION=$(curl -sf http://169.254.169.254/latest/meta-data/spot/instance-action | jq -r .action)
cat << EOF > /etc/node-exporter/node_aws.prom
# HELP node_aws_info AWS specific information to this node
node_aws_info{life_cycle="${INSTANCE_LIFE_CYCLE}",storage="${instance_storage}",network="${instance_network}",cost_hourly="${instance_cost_hourly}",cost_monthly="${instance_cost_monthly}",spot_price="${instance_spot_price}",cost_hourly_billed="${instance_cost_hourly_billed}",spot_action="${SPOT_INSTANCE_ACTION}"} 1
node_aws_costs{life_cycle="${INSTANCE_LIFE_CYCLE}"} ${instance_cost_hourly_billed}
EOF
[Unit]
Description=Node Exporter
[Service]
User=node-exporter
Restart=always
RestartSec=5
ExecStart=/usr/local/bin/node_exporter \
--collector.textfile.directory=/etc/node-exporter
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment