DeleteSecurityGroup与 AWS SDK 或 CLI 配合使用 - Amazon Elastic Compute Cloud

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

DeleteSecurityGroup与 AWS SDK 或 CLI 配合使用

以下代码示例演示如何使用 DeleteSecurityGroup

操作示例是大型程序的代码摘录,必须在上下文中运行。在以下代码示例中,您可以查看此操作的上下文:

.NET
AWS SDK for .NET
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

/// <summary> /// Delete an Amazon EC2 security group. /// </summary> /// <param name="groupName">The name of the group to delete.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> DeleteSecurityGroup(string groupId) { var response = await _amazonEC2.DeleteSecurityGroupAsync(new DeleteSecurityGroupRequest { GroupId = groupId }); return response.HttpStatusCode == HttpStatusCode.OK; }
  • 有关 API 的详细信息,请参阅 AWS SDK for .NET API 参考DeleteSecurityGroup中的。

Bash
AWS CLI 使用 Bash 脚本
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

############################################################################### # function ec2_delete_security_group # # This function deletes an Amazon Elastic Compute Cloud (Amazon EC2) security group. # # Parameters: # -i security_group_id - The ID of the security group to delete. # # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_delete_security_group() { local security_group_id response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_delete_security_group" echo "Deletes an Amazon Elastic Compute Cloud (Amazon EC2) security group." echo " -i security_group_id - The ID of the security group to delete." echo "" } # Retrieve the calling parameters. while getopts "i:h" option; do case "${option}" in i) security_group_id="${OPTARG}" ;; h) usage return 0 ;; \?) echo "Invalid parameter" usage return 1 ;; esac done export OPTIND=1 if [[ -z "$security_group_id" ]]; then errecho "ERROR: You must provide a security group ID with the -i parameter." usage return 1 fi response=$(aws ec2 delete-security-group --group-id "$security_group_id" --output text) || { aws_cli_error_log ${?} errecho "ERROR: AWS reports delete-security-group operation failed.$response" return 1 } return 0 }

本示例中使用的实用程序函数。

############################################################################### # function errecho # # This function outputs everything sent to it to STDERR (standard error output). ############################################################################### function errecho() { printf "%s\n" "$*" 1>&2 } ############################################################################## # function aws_cli_error_log() # # This function is used to log the error messages from the AWS CLI. # # The function expects the following argument: # $1 - The error code returned by the AWS CLI. # # Returns: # 0: - Success. # ############################################################################## function aws_cli_error_log() { local err_code=$1 errecho "Error code : $err_code" if [ "$err_code" == 1 ]; then errecho " One or more S3 transfers failed." elif [ "$err_code" == 2 ]; then errecho " Command line failed to parse." elif [ "$err_code" == 130 ]; then errecho " Process received SIGINT." elif [ "$err_code" == 252 ]; then errecho " Command syntax invalid." elif [ "$err_code" == 253 ]; then errecho " The system environment or configuration was invalid." elif [ "$err_code" == 254 ]; then errecho " The service returned an error." elif [ "$err_code" == 255 ]; then errecho " 255 is a catch-all error." fi return 0 }
C++
SDK for C++
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::DeleteSecurityGroupRequest request; request.SetGroupId(securityGroupID); auto outcome = ec2Client.DeleteSecurityGroup(request); if (!outcome.IsSuccess()) { std::cerr << "Failed to delete security group " << securityGroupID << ":" << outcome.GetError().GetMessage() << std::endl; } else { std::cout << "Successfully deleted security group " << securityGroupID << std::endl; }
  • 有关 API 的详细信息,请参阅 AWS SDK for C++ API 参考DeleteSecurityGroup中的。

CLI
AWS CLI

[EC2-Classic] 删除安全组

本示例将删除名为 MySecurityGroup 的安全组。如果命令成功,则不返回任何输出。

命令:

aws ec2 delete-security-group --group-name MySecurityGroup

[EC2-VPC] 删除安全组

本示例将删除 ID 为 sg-903004f8 的安全组。请注意,您不能通过名称引用 EC2-VPC 的安全组。如果命令成功,则不返回任何输出。

命令:

aws ec2 delete-security-group --group-id sg-903004f8

有关更多信息,请参阅《AWS 命令行界面用户指南》中的“使用安全组”。

Java
适用于 Java 的 SDK 2.x
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

public static void deleteEC2SecGroup(Ec2Client ec2, String groupId) { try { DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder() .groupId(groupId) .build(); ec2.deleteSecurityGroup(request); System.out.println("Successfully deleted security group with Id " + groupId); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } }
  • 有关 API 的详细信息,请参阅 AWS SDK for Java 2.x API 参考DeleteSecurityGroup中的。

JavaScript
适用于 JavaScript (v3) 的软件开发工具包
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

import { DeleteSecurityGroupCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; export const main = async () => { const command = new DeleteSecurityGroupCommand({ GroupId: "GROUP_ID", }); try { await client.send(command); console.log("Security group deleted successfully."); } catch (err) { console.error(err); } };
  • 有关 API 的详细信息,请参阅 AWS SDK for JavaScript API 参考DeleteSecurityGroup中的。

Kotlin
适用于 Kotlin 的 SDK
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

suspend fun deleteEC2SecGroup(groupIdVal: String) { val request = DeleteSecurityGroupRequest { groupId = groupIdVal } Ec2Client { region = "us-west-2" }.use { ec2 -> ec2.deleteSecurityGroup(request) println("Successfully deleted Security Group with id $groupIdVal") } }
  • 有关 API 的详细信息,请参阅适用DeleteSecurityGroup于 K otlin 的AWS SDK API 参考

PowerShell
用于 PowerShell

示例 1:此示例删除了 EC2-VPC 的指定安全组。除非您还指定了 Force 参数,否则在操作继续之前,系统会提示您进行确认。

Remove-EC2SecurityGroup -GroupId sg-12345678

输出:

Confirm Are you sure you want to perform this action? Performing operation "Remove-EC2SecurityGroup (DeleteSecurityGroup)" on Target "sg-12345678". [Y] Yes [A] Yes to All [N] No [L] No to All [S] Suspend [?] Help (default is "Y"):

示例 2:此示例删除了 EC2-Classic 的指定安全组。

Remove-EC2SecurityGroup -GroupName my-security-group -Force
  • 有关 API 的详细信息,请参阅 AWS Tools for PowerShell Cmdlet 参考DeleteSecurityGroup中的。

Python
SDK for Python (Boto3)
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

class SecurityGroupWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions.""" def __init__(self, ec2_resource, security_group=None): """ :param ec2_resource: A Boto3 Amazon EC2 resource. This high-level resource is used to create additional high-level objects that wrap low-level Amazon EC2 service actions. :param security_group: A Boto3 SecurityGroup object. This is a high-level object that wraps security group actions. """ self.ec2_resource = ec2_resource self.security_group = security_group @classmethod def from_resource(cls): ec2_resource = boto3.resource("ec2") return cls(ec2_resource) def delete(self): """ Deletes the security group. """ if self.security_group is None: logger.info("No security group to delete.") return group_id = self.security_group.id try: self.security_group.delete() except ClientError as err: logger.error( "Couldn't delete security group %s. Here's why: %s: %s", group_id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise
  • 有关 API 的详细信息,请参阅适用DeleteSecurityGroupPython 的AWS SDK (Boto3) API 参考

SAP ABAP
SDK for SAP ABAP
注意

还有更多相关信息 GitHub。在 AWS 代码示例存储库中查找完整实例,了解如何进行设置和运行。

TRY. lo_ec2->deletesecuritygroup( iv_groupid = iv_security_group_id ). MESSAGE 'Security group deleted.' TYPE 'I'. CATCH /aws1/cx_rt_service_generic INTO DATA(lo_exception). DATA(lv_error) = |"{ lo_exception->av_err_code }" - { lo_exception->av_err_msg }|. MESSAGE lv_error TYPE 'E'. ENDTRY.
  • 有关 API 的详细信息,请参阅适用DeleteSecurityGroup于 S AP 的AWS SDK ABAP API 参考

有关 S AWS DK 开发者指南和代码示例的完整列表,请参阅使用 AWS 软件开发工具包创建 Amazon EC2 资源。本主题还包括有关入门的信息以及有关先前的 SDK 版本的详细信息。