Skip to content

Instantly share code, notes, and snippets.

@gilangvperdana
Last active March 9, 2023 11:34
Show Gist options
  • Save gilangvperdana/bb12995b93ad9a6127adb00d1a743cf2 to your computer and use it in GitHub Desktop.
Save gilangvperdana/bb12995b93ad9a6127adb00d1a743cf2 to your computer and use it in GitHub Desktop.
Search Instance Identity with Bashscript

Goals

  • Make bash script to search Instances on Openstack

Script.sh

#!/bin/bash

export OS_PROJECT_DOMAIN_NAME=Default
export OS_USER_DOMAIN_NAME=Default
export OS_PROJECT_NAME=admin
export OS_TENANT_NAME=admin
export OS_USERNAME=admin
export OS_PASSWORD=$PASSWORD
export OS_AUTH_URL=$AUTH_URL
export OS_INTERFACE=internal
export OS_ENDPOINT_TYPE=internalURL
export OS_IDENTITY_API_VERSION=3
export OS_REGION_NAME=RegionOne
export OS_AUTH_PLUGIN=password
export OS_CACERT=/etc/kolla/certificates/ca/root.crt

# Menanyakan nama instance yang ingin dicari
echo "Masukkan nama instance yang ingin dicari:"
read instance_name

# Mencari instance dengan nama yang mirip
instances=$(openstack server list --all --name "$instance_name" -f value -c ID -c Name)

# Memisahkan ID instance dan nama instance ke dalam array
instance_ids=()
instance_names=()
while read -r line; do
  instance_ids+=($(echo "$line" | awk '{print $1}'))
  instance_names+=($(echo "$line" | awk '{print $2}'))
done <<< "$instances"

# Menampilkan daftar instance yang ditemukan
if [ ${#instance_ids[@]} -eq 0 ]; then
  echo "Tidak ditemukan instance dengan nama '$instance_name'"
  exit 1
fi

echo "Berikut adalah daftar instance yang ditemukan:"
for i in "${!instance_ids[@]}"; do
  echo "  ${instance_names[$i]} [${instance_ids[$i]}]"
done

# Menanyakan pilihan instance yang diinginkan
PS3="Pilih instance yang Anda cari: "
select instance_name in "${instance_names[@]}"; do
  if [[ -n "$instance_name" ]]; then
    # Mendapatkan ID instance dari array instance_ids
    instance_id=${instance_ids[$((REPLY-1))]}
    break
  fi
done

# Mendapatkan informasi tentang instance yang dipilih
instance_info=$(openstack server show "$instance_id" -f json)

# Parsing informasi instance
name=$(echo "$instance_info" | jq -r '.name')
project_id=$(echo "$instance_info" | jq -r '.project_id')
project=$(openstack project show "$project_id" -f value -c name)
ip=$(echo "$instance_info" | jq -r '.addresses | split("\n") | map(select(. | contains("10.") or contains("172.") or contains("192."))) | join(", ")')
flavor_id=$(echo "$instance_info" | jq -r '.flavor')
flavor=$(echo "$flavor_id" | sed 's/ ([^)]*)//')
host=$(openstack server show "$instance_id" -f value -c OS-EXT-SRV-ATTR:host)

# Menampilkan informasi instance
echo "Instance '$name' berada pada project '$project' dengan IP '$ip' menggunakan flavor '$flavor' dan berjalan pada server '$host'."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment