Nirbhay Singh
Nirbhay Singh

Reputation: 409

Error handling for AWS CLI in bash script for duplicate security group

I am creating a security group using AWS CLI using Bash script. I want to implement an error handling in the script for example if I create a security group with the same name I can handle it with if-else or any other iteration.

read -p "Enter the Security group name :" group_name
read -p "Enter the Security group description :" description
sgGroup_id=$(aws ec2 create-security-group --group-name $group_name --description "$description" --vpc-id vpc-547eae32 --output json | sed 's/}//g;s/"//g;s/ //g;s/{//g;s/GroupId://g')

while [ "$?" -eq "255" ]; do
echo "Dublicate name, enter detials again"
    read -p "Enter the Security group name :" group_name
    read -p "Enter the Security group description :" description
    sgGroup_id=$(aws ec2 create-security-group --group-name $group_name --description "$description" --vpc-id vpc-547eae32 --output json | sed 's/}//g;s/"//g;s/ //g;s/{//g;s/GroupId://g')
done

But this is not working for me. this is the error code that comes for duplicate sg creation.

An error occurred (InvalidGroup.Duplicate) when calling the CreateSecurityGroup operation: The security group 'testsg1w' already exists for VPC 'vpc-547eae32'

Please tell me how can I handle this error.

Upvotes: 3

Views: 10686

Answers (1)

Nirbhay Singh
Nirbhay Singh

Reputation: 409

I found an answer for this by myself, What I did is compared the name given by the user with the already existing name in AWS. If the name already existed them asked for a different name.

read -p "Enter the Security group name :" group_name
    STR=`aws ec2 describe-security-groups --filters Name=vpc-id,Values=$vpcId --query 'SecurityGroups[*].GroupName' --output text`
    echo $STR | grep $group_name &> /dev/nul
    while [ $? == 0 ]; 
    do
    echo ""
    echo "A security-group already exists by this name, please try a different name"
    echo ""
    read -p "Enter the Security group name :" group_name
    STR=`aws ec2 describe-security-groups --filters Name=vpc-id,Values=$vpcId --query 'SecurityGroups[*].GroupName' --output text`
    echo $STR | grep $group_name &> /dev/nul
    if [ $? == 0 ]; then
        echo ""
        echo "A security-group already exists by this name, please try a different name"
        continue
    else    
        break
    fi
    done
    read -p "Enter the Security group description :" description
    aws ec2 create-security-group --group-name $group_name --description "$description" --vpc-id $vpcId

Upvotes: 0

Related Questions