Use DeleteSecurityGroup com um AWS SDK ou CLI - Amazon Elastic Compute Cloud

As traduções são geradas por tradução automática. Em caso de conflito entre o conteúdo da tradução e da versão original em inglês, a versão em inglês prevalecerá.

Use DeleteSecurityGroup com um AWS SDK ou CLI

Os exemplos de código a seguir mostram como usar o DeleteSecurityGroup.

Exemplos de ações são trechos de código de programas maiores e devem ser executados em contexto. É possível ver essa ação no contexto no seguinte exemplo de código:

.NET
AWS SDK for .NET
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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) { try { var response = await _amazonEC2.DeleteSecurityGroupAsync( new DeleteSecurityGroupRequest { GroupId = groupId }); return response.HttpStatusCode == HttpStatusCode.OK; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidGroup.NotFound") { _logger.LogError( $"Security Group {groupId} does not exist and cannot be deleted. Please verify the ID and try again."); } return false; } catch (Exception ex) { Console.WriteLine($"Couldn't delete the security group because: {ex.Message}"); return false; } }
Bash
AWS CLI com script Bash
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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 }

As funções utilitárias usadas neste exemplo.

############################################################################### # 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++
SDKpara C++
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

//! Delete a security group. /*! \param securityGroupID: A security group ID. \param clientConfiguration: AWS client configuration. \return bool: Function succeeded. */ bool AwsDoc::EC2::deleteSecurityGroup(const Aws::String &securityGroupID, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::DeleteSecurityGroupRequest request; request.SetGroupId(securityGroupID); Aws::EC2::Model::DeleteSecurityGroupOutcome 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; } return outcome.IsSuccess(); }
CLI
AWS CLI

[EC2-Clássico] Para excluir um grupo de segurança

Este exemplo exclui o grupo de segurança chamado MySecurityGroup. Se o comando for bem-sucedido, nenhuma saída será retornada.

Comando:

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

[EC2-VPC] Para excluir um grupo de segurança

Este exemplo exclui o grupo de segurança com o ID sg-903004f8. Observe que você não pode referenciar um grupo de segurança para EC2 - VPC por nome. Se o comando for bem-sucedido, nenhuma saída será retornada.

Comando:

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

Para obter mais informações, consulte Using Security Groups no Guia do usuário da AWS Command Line Interface.

Java
SDKpara Java 2.x
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

/** * Deletes an EC2 security group asynchronously. * * @param groupId the ID of the security group to delete * @return a CompletableFuture that completes when the security group is deleted */ public CompletableFuture<Void> deleteEC2SecGroupAsync(String groupId) { DeleteSecurityGroupRequest request = DeleteSecurityGroupRequest.builder() .groupId(groupId) .build(); CompletableFuture<DeleteSecurityGroupResponse> response = getAsyncClient().deleteSecurityGroup(request); return response.whenComplete((resp, ex) -> { if (ex != null) { throw new RuntimeException("Failed to delete security group with Id " + groupId, ex); } else if (resp == null) { throw new RuntimeException("No response received for deleting security group with Id " + groupId); } }).thenApply(resp -> null); }
JavaScript
SDKpara JavaScript (v3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

import { DeleteSecurityGroupCommand, EC2Client } from "@aws-sdk/client-ec2"; /** * Deletes a security group. * @param {{ groupId: string }} options */ export const main = async ({ groupId }) => { const client = new EC2Client({}); const command = new DeleteSecurityGroupCommand({ GroupId: groupId, }); try { await client.send(command); console.log("Security group deleted successfully."); } catch (caught) { if (caught instanceof Error && caught.name === "InvalidGroupId.Malformed") { console.warn(`${caught.message}. Please provide a valid GroupId.`); } else { throw caught; } } };
  • Para API obter detalhes, consulte DeleteSecurityGroupem AWS SDK for JavaScript APIReferência.

Kotlin
SDKpara Kotlin
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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") } }
PowerShell
Ferramentas para PowerShell

Exemplo 1: Este exemplo exclui o grupo de segurança especificado para EC2 -VPC. Você será solicitado a confirmar antes que a operação continue, a menos que você também especifique o parâmetro Force.

Remove-EC2SecurityGroup -GroupId sg-12345678

Saída:

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"):

Exemplo 2: Este exemplo exclui o grupo de segurança especificado para EC2 -Classic.

Remove-EC2SecurityGroup -GroupName my-security-group -Force
  • Para API obter detalhes, consulte DeleteSecurityGroupem Referência de AWS Tools for PowerShell cmdlet.

Python
SDKpara Python (Boto3)
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

class SecurityGroupWrapper: """Encapsulates Amazon Elastic Compute Cloud (Amazon EC2) security group actions.""" def __init__(self, ec2_client: boto3.client, security_group: Optional[str] = None): """ Initializes the SecurityGroupWrapper with an EC2 client and an optional security group ID. :param ec2_client: A Boto3 Amazon EC2 client. This client provides low-level access to AWS EC2 services. :param security_group: The ID of a security group to manage. This is a high-level identifier that represents the security group. """ self.ec2_client = ec2_client self.security_group = security_group @classmethod def from_client(cls) -> "SecurityGroupWrapper": """ Creates a SecurityGroupWrapper instance with a default EC2 client. :return: An instance of SecurityGroupWrapper initialized with the default EC2 client. """ ec2_client = boto3.client("ec2") return cls(ec2_client) def delete(self, security_group_id: str) -> bool: """ Deletes the specified security group. :param security_group_id: The ID of the security group to delete. Required. :returns: True if the deletion is successful. :raises ClientError: If the security group cannot be deleted due to an AWS service error. """ try: self.ec2_client.delete_security_group(GroupId=security_group_id) logger.info(f"Successfully deleted security group '{security_group_id}'") return True except ClientError as err: logger.error(f"Deletion failed for security group '{security_group_id}'") error_code = err.response["Error"]["Code"] if error_code == "InvalidGroup.NotFound": logger.error( f"Security group '{security_group_id}' cannot be deleted because it does not exist." ) elif error_code == "DependencyViolation": logger.error( f"Security group '{security_group_id}' cannot be deleted because it is still in use." " Verify that it is:" "\n\t- Detached from resources" "\n\t- Removed from references in other groups" "\n\t- Removed from VPC's as a default group" ) raise
  • Para API obter detalhes, consulte a DeleteSecurityGroupReferência AWS SDK do Python (Boto3). API

Rust
SDKpara Rust
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da AWS.

pub async fn delete_security_group(&self, group_id: &str) -> Result<(), EC2Error> { tracing::info!("Deleting security group {group_id}"); self.client .delete_security_group() .group_id(group_id) .send() .await?; Ok(()) }
SAP ABAP
SDKpara SAP ABAP
nota

Tem mais sobre GitHub. Encontre o exemplo completo e saiba como configurar e executar no Repositório de exemplos de código da 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.

Para obter uma lista completa de guias do AWS SDK desenvolvedor e exemplos de código, consulteCrie EC2 recursos da Amazon usando um AWS SDK. Este tópico também inclui informações sobre como começar e detalhes sobre SDK versões anteriores.