Upload IP Address to S3
This guide explains how to create a bash script that runs after your Linux server boots up. The script will get the IP address, create a JSON file, and upload it to an AWS S3 bucket.
Files
/usr/bin/system_info.sh
/usr/bin/system_info.sh |
---|
| #!/bin/bash
print_header() {
local title="$1"
echo "------------------------------------------------------------------------"
echo " $title "
echo "------------------------------------------------------------------------"
}
# Get the IP address and datetime in ISO format
echo "Datetime: $(date -u +'%Y-%m-%dT%H:%M:%SZ')"
echo "Hostname: $(hostname)"
echo "IP: $(hostname -I | awk '{print $1}')"
echo ""
# Check if virsh is installed
if command -v virsh &> /dev/null
then
print_header "LIST OF VIRTUAL MACHINES"
virsh list --all
fi
print_header "FILE SYSTEM"
df -h
print_header "OPERATING SYSTEM INFORMATION"
cat /etc/os-release
print_header "CPU INFORMATION"
lscpu
print_header "MEMORY INFORMATION"
free -h
print_header "NETWORK INFORMATION"
ip a
print_header "IP ROUTES"
ip route
|
/usr/bin/upload_ip.sh
This bash script gets the System Informations, creates a TXT file, and uploads it to an AWS S3 bucket.
Bash |
---|
| #!/bin/bash
export S3_BUCKET="your-s3-bucket-name"
export AWS_ACCESS_KEY_ID="access-key"
export AWS_SECRET_ACCESS_KEY="secret"
# Get the IP address and datetime in ISO format
# Create a JSON file with the IP address
INFO_FILE="host-$HOSTNAME.txt"
bash /usr/bin/system_info.sh > $INFO_FILE
# Upload the JSON file to an AWS S3 bucket
aws s3 cp $INFO_FILE s3://$S3_BUCKET/
# Clean up
rm $INFO_FILE
|
/etc/systemd/system/upload_ip.service
This systemd service file runs the script at boot.
INI |
---|
| # filepath: /etc/systemd/system/upload_ip.service
[Unit]
Description=Upload IP address to S3
After=network.target
[Service]
ExecStart=/bin/bash /usr/bin/upload_ip.sh
[Install]
WantedBy=default.target
|
Enable and Start the Service
Run the following commands to enable and start the service:
Bash |
---|
| chmod +x /usr/bin/system_info.sh
chmod +x /usr/bin/upload_ip.sh
sudo systemctl enable upload_ip.service
sudo systemctl start upload_ip.service
|
If you want an update every hour
Bash |
---|
| echo "0 * * * * root /bin/bash /usr/bin/upload_ip.sh" | sudo tee /etc/cron.d/upload_ip
|