philroche
11/29/2019 - 4:44 PM

cloneawsinstance function to clone an aws instance in the same region as the source instance

cloneawsinstance function to clone an aws instance in the same region as the source instance

function cloneinstance {
  awsinstanceid=$1
  region=${2:-us-east-1}
  awsprofile=${3:-seg}
  export AWS_DEFAULT_REGION=$region
  dt=$(date '+%Y%m%d%H%M%S')
  ami=$(aws --profile=${awsprofile} ec2 describe-instances --instance-ids $awsinstanceid --query 'Reservations[].Instances[].ImageId' --output=text)
  privatekey=$(aws --profile=${awsprofile} ec2 describe-instances --instance-ids $awsinstanceid --query 'Reservations[].Instances[].KeyName' --output=text)
  securitygroup=$(aws --profile=${awsprofile} ec2 describe-instances --instance-ids $awsinstanceid --query 'Reservations[].Instances[].NetworkInterfaces[].Groups[].GroupId' --output=text)
  instancetype=$(aws --profile=${awsprofile} ec2 describe-instances --instance-ids $awsinstanceid --query 'Reservations[].Instances[].InstanceType' --output=text)
  subnet=$(aws --profile=${awsprofile} ec2 describe-instances --instance-ids $awsinstanceid --query 'Reservations[].Instances[].SubnetId' --output=text)
  tag=$(aws --profile=${awsprofile} ec2 describe-instances --instance-ids $awsinstanceid --query "Reservations[].Instances[].Tags[?Key=='Name'].Value" --output=text)
  newtag="${tag}-${dt}"
   
  echo "ami: ${ami}"
  echo "privatekey: ${privatekey}"
  echo "securitygroup: ${securitygroup}"
  echo "instancetype: ${instancetype}"
  echo "subnet: ${subnet}"
  echo "tag: ${tag}"
  echo "newtag: ${newtag}"
  clonedawsinstanceid=$(aws --profile=${awsprofile} ec2 run-instances --image-id $ami --key-name $privatekey --security-group-ids $securitygroup --instance-type $instancetype --subnet-id $subnet --tag-specifications "ResourceType=instance,Tags=[{Key=Name,Value=${newtag}}]" "ResourceType=volume,Tags=[{Key=Name,Value=${newtag}}]" --query 'Instances[].InstanceId' --output=text)
  # AWS CLI doesn't return error codes so have to look for a valid id
  if [[ "${clonedawsinstanceid}" == i-* ]]; 
  then 
    echo -e "\t\tSuccessfully created. Instance ID: ${clonedawsinstanceid}"; 
  else 
    echo -e "\t\tSomething went wrong. Check your configuration."; 
  fi 
  echo -e "\t\tWaiting for it to come up..."
  aws --profile=${awsprofile} ec2 wait instance-running --instance-ids ${clonedawsinstanceid}
  echo -e "\t\tServer is up and ready"
  clonedawsinstance_ipaddress=$(aws --profile=${awsprofile} ec2 describe-instances --instance-ids ${clonedawsinstanceid} --query 'Reservations[].Instances[].PublicIpAddress' --output=text)
  echo "Cloned instance id: ${clonedawsinstanceid}"
  echo "Cloned instance public ip address: ${clonedawsinstance_ipaddress}"
}