bash - 重复安全组的 ba​​sh 脚本中 AWS CLI 的错误处理

标签 bash amazon-web-services amazon-ec2 aws-cli

我正在使用 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 - 重复安全组的 ba​​sh 脚本中 AWS CLI 的错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46960582/

相关文章:

bash - BASH 中的空函数

django - 是否可以在 zsh 中使用 Django bash 完成

bash - 使用 sudo bash -c 'echo $myVariable' 回显变量 - bash 脚本

linux - Bash 脚本打印错误的值

ios - Aws iOS sdk Pre-singed url 给出 "SignatureDoesNotMatch"错误

linux - 如何使用免费的 Windows 堆栈在 Amazon AWS 免费层上使用 XAMPP 部署 Windows 开发的应用程序?

amazon-web-services - AWS 对写入 s3 的 lambda 输出的大小限制

node.js - AWS认知: getCredentials not working

amazon-ec2 - 关于 Amazon EC2 的几个问题

mysql - 关于 EC2+MySQL 与 RDS for Wordpress