EC2 태깅 MKII

7541 단어 devopsawsbashlinux
몇 주 전에 에 조잡한 bash 스크립트에 대해 게시했습니다. 이후 각 인스턴스 ID와 연결된 volumessnapshots를 찾기 위해 인스턴스 ID를 사용하도록 스크립트를 조정했습니다.

또한 AWS 구성 파일에서 사용할 계정을 동적으로 가져옵니다.

즐거운 시간 보내세요

#!/bin/bash

## Functions

tag_rescources () {
aws --profile=$profile --region=$region ec2 create-tags --resources $1 \
    --tags Key="COST CENTRE",Value="$cost" \
      Key="APP",Value="$app" \
      Key="ENVIRONMENT",Value="$environment" \
      Key="OWNER",Value="$owner" 
}

get_volumes (){
aws --profile=$profile --region=$region ec2 describe-volumes \
  --filters Name=attachment.instance-id,Values=$1 \
  --query "Volumes[].VolumeId" --output=text
}

get_snapshots(){
aws --profile=$profile --region=$region ec2 describe-snapshots \
  --filters Name=volume-id,Values=$1 \
  --query "Snapshots[].SnapshotId" --output=text
}


## Script
echo "Use this script to tag EC2 instance in the desired account"
echo "Multiple can be enter at once seperated by a singe space."
echo "Below resources are supported using the ID"
echo "            Instance ID"
echo "            Security Group ID"
echo "            Elastic IPs Allocation ID"
echo " "
echo "----------------------------------------------------------- "
echo "Please choose AWS Account Profile"
select profile in `grep '^\[' ~/.aws/config|sed -r 's/\[|\]//g'|awk '{print $2}'`
do
   echo "Please choose AWS Region"
   select region in eu-west-1 eu-central-1 us-east-1
   do

   echo "Please list EC2 Instance ID"
   echo "Multiple can be entered at once, seperated by a singe space."
   read instance
   echo "Please Enter COST CENTRE"
   read cost
   echo "Please Enter APP"
   read app
   echo "Please Enter ENVIRONMENT"
   read environment
   echo "Please Enter OWNER"
   read owner

   ## Tagging EC2 Instances
   for i in $instance
   do
      tag_rescources $i
      echo "Tagging EC2 Instances $i"
   done

   ## Tagging Volunmes
   #! a nested loop is used as the get volume function can only filter one volume at a time
   for i in $instance
   do
         for j in `get_volumes $i`
         do
            echo "Tagging Volume $j beloning to Instance $i"
            tag_rescources $j
         done
   done

   ## Tagging Snapshots
   #! a nested loop is used as the get snapshot function can only filter one volume at a time
   volumes=`get_volumes $instance`
   for i in $volumes
   do
         for j in `get_snapshots $i`
         do
            echo "Tagging SnapShot $j belonging to Volume $i"
            tag_rescources $j
         done
   done

   echo "If no error's above tagging complete"
   break
   done
   break
done

좋은 웹페이지 즐겨찾기