bash 脚本中针对重复安全组的 AWS CLI 错误处理

问题描述 投票:0回答:1

我正在使用 Bash 脚本使用 AWS CLI 创建安全组。我想在脚本中实现错误处理,例如,如果我创建一个同名的安全组,我可以使用 if-else 或任何其他迭代来处理它。

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

但这对我不起作用。 这是重复创建 SG 时出现的错误代码。

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

请告诉我如何处理这个错误。

bash amazon-web-services amazon-ec2 aws-cli
1个回答
0
投票

我自己找到了答案, 我所做的是将用户给出的名称与 AWS 中已有的名称进行比较。 如果该名称已经存在,他们会要求使用不同的名称。

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
© www.soinside.com 2019 - 2024. All rights reserved.