我正在使用 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 时出现的错误代码。
调用 CreateSecurityGroup 操作时发生错误(InvalidGroup.Duplicate):VPC“vpc-547eae32
”的安全组“testsg1w”已存在
请告诉我如何处理这个错误。
最佳答案
我自己找到了答案, 我所做的是将用户给出的名称与 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
关于bash - 重复安全组的 bash 脚本中 AWS CLI 的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46960582/