Há mais AWS SDK exemplos disponíveis no GitHub repositório AWS Doc SDK Examples
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 AuthorizeSecurityGroupIngress
com um AWS SDK ou CLI
Os exemplos de código a seguir mostram como usar o AuthorizeSecurityGroupIngress
.
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> /// Authorize the local computer ingress to EC2 instances associated /// with the virtual private cloud (VPC) security group. /// </summary> /// <param name="groupName">The name of the security group.</param> /// <returns>A Boolean value indicating the success of the action.</returns> public async Task<bool> AuthorizeSecurityGroupIngress(string groupName) { try { // Get the IP address for the local computer. var ipAddress = await GetIpAddress(); Console.WriteLine($"Your IP address is: {ipAddress}"); var ipRanges = new List<IpRange> { new IpRange { CidrIp = $"{ipAddress}/32" } }; var permission = new IpPermission { Ipv4Ranges = ipRanges, IpProtocol = "tcp", FromPort = 22, ToPort = 22 }; var permissions = new List<IpPermission> { permission }; var response = await _amazonEC2.AuthorizeSecurityGroupIngressAsync( new AuthorizeSecurityGroupIngressRequest(groupName, permissions)); return response.HttpStatusCode == HttpStatusCode.OK; } catch (AmazonEC2Exception ec2Exception) { if (ec2Exception.ErrorCode == "InvalidPermission.Duplicate") { _logger.LogError( $"The ingress rule already exists. {ec2Exception.Message}"); } throw; } catch (Exception ex) { _logger.LogError( $"An error occurred while authorizing ingress.: {ex.Message}"); throw; } } /// <summary> /// Authorize the local computer for ingress to /// the Amazon EC2 SecurityGroup. /// </summary> /// <returns>The IPv4 address of the computer running the scenario.</returns> private static async Task<string> GetIpAddress() { var httpClient = new HttpClient(); var ipString = await httpClient.GetStringAsync("https://checkip.amazonaws.com"); // The IP address is returned with a new line // character on the end. Trim off the whitespace and // return the value to the caller. return ipString.Trim(); }
-
Para API obter detalhes, consulte AuthorizeSecurityGroupIngressem AWS SDK for .NET APIReferência.
-
- 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_authorize_security_group_ingress # # This function authorizes an ingress rule for an Amazon Elastic Compute Cloud (Amazon EC2) security group. # # Parameters: # -g security_group_id - The ID of the security group. # -i ip_address - The IP address or CIDR block to authorize. # -p protocol - The protocol to authorize (e.g., tcp, udp, icmp). # -f from_port - The start of the port range to authorize. # -t to_port - The end of the port range to authorize. # # And: # 0 - If successful. # 1 - If it fails. ############################################################################### function ec2_authorize_security_group_ingress() { local security_group_id ip_address protocol from_port to_port response local option OPTARG # Required to use getopts command in a function. # bashsupport disable=BP5008 function usage() { echo "function ec2_authorize_security_group_ingress" echo "Authorizes an ingress rule for an Amazon Elastic Compute Cloud (Amazon EC2) security group." echo " -g security_group_id - The ID of the security group." echo " -i ip_address - The IP address or CIDR block to authorize." echo " -p protocol - The protocol to authorize (e.g., tcp, udp, icmp)." echo " -f from_port - The start of the port range to authorize." echo " -t to_port - The end of the port range to authorize." echo "" } # Retrieve the calling parameters. while getopts "g:i:p:f:t:h" option; do case "${option}" in g) security_group_id="${OPTARG}" ;; i) ip_address="${OPTARG}" ;; p) protocol="${OPTARG}" ;; f) from_port="${OPTARG}" ;; t) to_port="${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 -g parameter." usage return 1 fi if [[ -z "$ip_address" ]]; then errecho "ERROR: You must provide an IP address or CIDR block with the -i parameter." usage return 1 fi if [[ -z "$protocol" ]]; then errecho "ERROR: You must provide a protocol with the -p parameter." usage return 1 fi if [[ -z "$from_port" ]]; then errecho "ERROR: You must provide a start port with the -f parameter." usage return 1 fi if [[ -z "$to_port" ]]; then errecho "ERROR: You must provide an end port with the -t parameter." usage return 1 fi response=$(aws ec2 authorize-security-group-ingress \ --group-id "$security_group_id" \ --cidr "${ip_address}/32" \ --protocol "$protocol" \ --port "$from_port-$to_port" \ --output text) || { aws_cli_error_log ${?} errecho "ERROR: AWS reports authorize-security-group-ingress 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 }
-
Para API obter detalhes, consulte AuthorizeSecurityGroupIngressna Referência de AWS CLI Comandos.
-
- 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
. //! Authorize ingress to an Amazon Elastic Compute Cloud (Amazon EC2) group. /*! \param groupID: The EC2 group ID. \param clientConfiguration: The ClientConfiguration object. \return bool: True if the operation was successful, false otherwise. */ bool AwsDoc::EC2::authorizeSecurityGroupIngress(const Aws::String &groupID, const Aws::Client::ClientConfiguration &clientConfiguration) { Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::AuthorizeSecurityGroupIngressRequest authorizeSecurityGroupIngressRequest; authorizeSecurityGroupIngressRequest.SetGroupId(groupID); buildSampleIngressRule(authorizeSecurityGroupIngressRequest); Aws::EC2::Model::AuthorizeSecurityGroupIngressOutcome authorizeSecurityGroupIngressOutcome = ec2Client.AuthorizeSecurityGroupIngress(authorizeSecurityGroupIngressRequest); if (authorizeSecurityGroupIngressOutcome.IsSuccess()) { std::cout << "Successfully authorized security group ingress." << std::endl; } else { std::cerr << "Error authorizing security group ingress: " << authorizeSecurityGroupIngressOutcome.GetError().GetMessage() << std::endl; } return authorizeSecurityGroupIngressOutcome.IsSuccess(); }
Função utilitária para criar uma regra de entrada.
//! Build a sample ingress rule. /*! \param authorize_request: An 'AuthorizeSecurityGroupIngressRequest' instance. \return void: */ void buildSampleIngressRule( Aws::EC2::Model::AuthorizeSecurityGroupIngressRequest &authorize_request) { Aws::String ingressIPRange = "203.0.113.0/24"; // Configure this for your allowed IP range. Aws::EC2::Model::IpRange ip_range; ip_range.SetCidrIp(ingressIPRange); Aws::EC2::Model::IpPermission permission1; permission1.SetIpProtocol("tcp"); permission1.SetToPort(80); permission1.SetFromPort(80); permission1.AddIpRanges(ip_range); authorize_request.AddIpPermissions(permission1); Aws::EC2::Model::IpPermission permission2; permission2.SetIpProtocol("tcp"); permission2.SetToPort(22); permission2.SetFromPort(22); permission2.AddIpRanges(ip_range); authorize_request.AddIpPermissions(permission2); }
-
Para API obter detalhes, consulte AuthorizeSecurityGroupIngressem AWS SDK for C++ APIReferência.
-
- CLI
-
- AWS CLI
-
Exemplo 1: Para adicionar uma regra que permita tráfego de entrada SSH
O
authorize-security-group-ingress
exemplo a seguir adiciona uma regra que permite tráfego de entrada na TCP porta 22 (SSH).aws ec2 authorize-security-group-ingress \ --group-id
sg-1234567890abcdef0
\ --protocoltcp
\ --port22
\ --cidr203.0.113.0/24
Saída:
{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-01afa97ef3e1bedfc", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "CidrIpv4": "203.0.113.0/24" } ] }
Exemplo 2: Para adicionar uma regra que permita HTTP tráfego de entrada de outro grupo de segurança
O
authorize-security-group-ingress
exemplo a seguir adiciona uma regra que permite acesso de entrada na TCP porta 80 do gruposg-1a2b3c4d
de segurança de origem. O grupo de origem deve estar no mesmo grupo VPC ou em um peer VPC (requer uma conexão de VPC peering). O tráfego de entrada é permitido com base nos endereços IP privados das instâncias associadas ao grupo de segurança de origem (e não ao endereço IP público ou ao endereço IP elástico).aws ec2 authorize-security-group-ingress \ --group-id
sg-1234567890abcdef0
\ --protocoltcp
\ --port80
\ --source-groupsg-1a2b3c4d
Saída:
{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-01f4be99110f638a7", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "tcp", "FromPort": 80, "ToPort": 80, "ReferencedGroupInfo": { "GroupId": "sg-1a2b3c4d", "UserId": "123456789012" } } ] }
Exemplo 3: adicionar várias regras na mesma chamada
O
authorize-security-group-ingress
exemplo a seguir usa oip-permissions
parâmetro para adicionar duas regras de entrada, uma que habilita o acesso de entrada na TCP porta 3389 (RDP) e a outra que habilita ping/. ICMPaws ec2 authorize-security-group-ingress --group-id sg-1234567890abcdef0 --ip-permissions IpProtocol =tcp, =3389, FromPort =3389, = "[{=172.31.0.0/16}]” =icmp, =-1, =-1, = "[{=172.31.0.0/16}ToPort]” IpRanges CidrIp IpProtocol FromPort ToPort IpRanges CidrIp
Saída:
{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-00e06e5d3690f29f3", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "tcp", "FromPort": 3389, "ToPort": 3389, "CidrIpv4": "172.31.0.0/16" }, { "SecurityGroupRuleId": "sgr-0a133dd4493944b87", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "tcp", "FromPort": -1, "ToPort": -1, "CidrIpv4": "172.31.0.0/16" } ] }
Exemplo 4: Para adicionar uma regra para ICMP tráfego
O
authorize-security-group-ingress
exemplo a seguir usa oip-permissions
parâmetro para adicionar uma regra de entrada que permite a ICMP mensagemDestination Unreachable: Fragmentation Needed and Don't Fragment was Set
(Tipo 3, Código 4) de qualquer lugar.aws ec2 authorize-security-group-ingress --group-id sg-1234567890abcdef0 --ip-permissions =icmp, =3, =4, = "[{=0.0.0.0/0}]” IpProtocol FromPort ToPort IpRanges CidrIp
Saída:
{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-0de3811019069b787", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "icmp", "FromPort": 3, "ToPort": 4, "CidrIpv4": "0.0.0.0/0" } ] }
Exemplo 5: Para adicionar uma regra para IPv6 tráfego
O
authorize-security-group-ingress
exemplo a seguir usa oip-permissions
parâmetro para adicionar uma regra de entrada que permite SSH acesso (porta 22) a partir do IPv6 intervalo2001:db8:1234:1a00::/64
.aws ec2 authorize-security-group-ingress --group-id sg-1234567890abcdef0 --ip-permissions =tcp, =22, =22, Ipv6Ranges= "[{6=2001:db 8:1234:1 a00: :/64 IpProtocol}]” FromPort ToPort CidrIpv
Saída:
{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-0455bc68b60805563", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "CidrIpv6": "2001:db8:1234:1a00::/64" } ] }
Exemplo 6: Para adicionar uma regra para ICMPv6 tráfego
O
authorize-security-group-ingress
exemplo a seguir usa oip-permissions
parâmetro para adicionar uma regra de entrada que permite ICMPv6 tráfego de qualquer lugar.aws ec2 authorize-security-group-ingress --group-id sg-1234567890abcdef0 --ip-permissions =icmpv6, Ipv6Ranges= "[{6=: :/0}]” IpProtocol CidrIpv
Saída:
{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-04b612d9363ab6327", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "icmpv6", "FromPort": -1, "ToPort": -1, "CidrIpv6": "::/0" } ] }
Exemplo 7: adicionar uma regra com uma descrição
O
authorize-security-group-ingress
exemplo a seguir usa oip-permissions
parâmetro para adicionar uma regra de entrada que permite o RDP tráfego do intervalo de IPv4 endereços especificado. A regra inclui uma descrição para ajudar a identificá-lo posteriormente.aws ec2 authorize-security-group-ingress --group-id sg-1234567890abcdef0 --ip-permissions IpProtocol =tcp, =3389, =3389, = "[{=203.0.113.0/24, Descrição=' acesso do escritório de Nova York '}]” FromPort ToPort IpRanges CidrIp RDP
Saída:
{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-0397bbcc01e974db3", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "tcp", "FromPort": 3389, "ToPort": 3389, "CidrIpv4": "203.0.113.0/24", "Description": "RDP access from NY office" } ] }
Exemplo 8: adicionar uma regra de entrada que use uma lista de prefixos
O
authorize-security-group-ingress
exemplo a seguir usa oip-permissions
parâmetro para adicionar uma regra de entrada que permite todo o tráfego para os CIDR intervalos na lista de prefixos especificada.aws ec2 authorize-security-group-ingress --group-id sg-04a351bfe432d4e71 --ip-permissions =all, = "[{=pl-002dc3ec097de1514}]” IpProtocol PrefixListIds PrefixListId
Saída:
{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-09c74b32f677c6c7c", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "-1", "FromPort": -1, "ToPort": -1, "PrefixListId": "pl-0721453c7ac4ec009" } ] }
Para obter mais informações, consulte Grupos de segurança no Guia VPC do usuário da Amazon.
-
Para API obter detalhes, consulte AuthorizeSecurityGroupIngress
na Referência de AWS CLI Comandos.
-
- 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
. /** * Creates a new security group asynchronously with the specified group name, description, and VPC ID. It also * authorizes inbound traffic on ports 80 and 22 from the specified IP address. * * @param groupName the name of the security group to create * @param groupDesc the description of the security group * @param vpcId the ID of the VPC in which to create the security group * @param myIpAddress the IP address from which to allow inbound traffic (e.g., "192.168.1.1/0" to allow traffic from * any IP address in the 192.168.1.0/24 subnet) * @return a CompletableFuture that, when completed, returns the ID of the created security group * @throws RuntimeException if there was a failure creating the security group or authorizing the inbound traffic */ public CompletableFuture<String> createSecurityGroupAsync(String groupName, String groupDesc, String vpcId, String myIpAddress) { CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder() .groupName(groupName) .description(groupDesc) .vpcId(vpcId) .build(); return getAsyncClient().createSecurityGroup(createRequest) .thenCompose(createResponse -> { String groupId = createResponse.groupId(); IpRange ipRange = IpRange.builder() .cidrIp(myIpAddress + "/32") .build(); IpPermission ipPerm = IpPermission.builder() .ipProtocol("tcp") .toPort(80) .fromPort(80) .ipRanges(ipRange) .build(); IpPermission ipPerm2 = IpPermission.builder() .ipProtocol("tcp") .toPort(22) .fromPort(22) .ipRanges(ipRange) .build(); AuthorizeSecurityGroupIngressRequest authRequest = AuthorizeSecurityGroupIngressRequest.builder() .groupName(groupName) .ipPermissions(ipPerm, ipPerm2) .build(); return getAsyncClient().authorizeSecurityGroupIngress(authRequest) .thenApply(authResponse -> groupId); }) .whenComplete((result, exception) -> { if (exception != null) { if (exception instanceof CompletionException && exception.getCause() instanceof Ec2Exception) { throw (Ec2Exception) exception.getCause(); } else { throw new RuntimeException("Failed to create security group: " + exception.getMessage(), exception); } } }); }
-
Para API obter detalhes, consulte AuthorizeSecurityGroupIngressem AWS SDK for Java 2.x APIReferência.
-
- 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 { AuthorizeSecurityGroupIngressCommand, EC2Client, } from "@aws-sdk/client-ec2"; /** * Adds the specified inbound (ingress) rules to a security group. * @param {{ groupId: string, ipAddress: string }} options */ export const main = async ({ groupId, ipAddress }) => { const client = new EC2Client({}); const command = new AuthorizeSecurityGroupIngressCommand({ // Use a group ID from the AWS console or // the DescribeSecurityGroupsCommand. GroupId: groupId, IpPermissions: [ { IpProtocol: "tcp", FromPort: 22, ToPort: 22, // The IP address to authorize. // For more information on this notation, see // https://en.wikipedia.org/wiki/Classless_Inter-Domain_Routing#CIDR_notation IpRanges: [{ CidrIp: `${ipAddress}/32` }], }, ], }); try { const { SecurityGroupRules } = await client.send(command); console.log(JSON.stringify(SecurityGroupRules, null, 2)); } 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 AuthorizeSecurityGroupIngressem 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 createEC2SecurityGroupSc( groupNameVal: String?, groupDescVal: String?, vpcIdVal: String?, myIpAddress: String?, ): String? { val request = CreateSecurityGroupRequest { groupName = groupNameVal description = groupDescVal vpcId = vpcIdVal } Ec2Client { region = "us-west-2" }.use { ec2 -> val resp = ec2.createSecurityGroup(request) val ipRange = IpRange { cidrIp = "$myIpAddress/0" } val ipPerm = IpPermission { ipProtocol = "tcp" toPort = 80 fromPort = 80 ipRanges = listOf(ipRange) } val ipPerm2 = IpPermission { ipProtocol = "tcp" toPort = 22 fromPort = 22 ipRanges = listOf(ipRange) } val authRequest = AuthorizeSecurityGroupIngressRequest { groupName = groupNameVal ipPermissions = listOf(ipPerm, ipPerm2) } ec2.authorizeSecurityGroupIngress(authRequest) println("Successfully added ingress policy to Security Group $groupNameVal") return resp.groupId } }
-
Para API obter detalhes, consulte a AuthorizeSecurityGroupIngress
referência AWS SDKdo Kotlin API.
-
- PowerShell
-
- Ferramentas para PowerShell
-
Exemplo 1: Este exemplo define regras de entrada para um grupo de segurança para EC2 -VPC. Essas regras concedem acesso a um endereço IP específico para SSH (porta 22) e RDC (porta 3389). Observe que você deve identificar grupos de segurança para EC2 VPC usar o ID do grupo de segurança e não o nome do grupo de segurança. A sintaxe usada neste exemplo requer a PowerShell versão 3 ou superior.
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" } $ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" } Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
Exemplo 2: Com a PowerShell versão 2, você deve usar New-Object para criar os IpPermission objetos.
$ip1 = New-Object Amazon.EC2.Model.IpPermission $ip1.IpProtocol = "tcp" $ip1.FromPort = 22 $ip1.ToPort = 22 $ip1.IpRanges.Add("203.0.113.25/32") $ip2 = new-object Amazon.EC2.Model.IpPermission $ip2.IpProtocol = "tcp" $ip2.FromPort = 3389 $ip2.ToPort = 3389 $ip2.IpRanges.Add("203.0.113.25/32") Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( $ip1, $ip2 )
Exemplo 3: Este exemplo define regras de entrada para um grupo de segurança para EC2 -Classic. Essas regras concedem acesso a um endereço IP específico para SSH (porta 22) e RDC (porta 3389). A sintaxe usada neste exemplo requer a PowerShell versão 3 ou superior.
$ip1 = @{ IpProtocol="tcp"; FromPort="22"; ToPort="22"; IpRanges="203.0.113.25/32" } $ip2 = @{ IpProtocol="tcp"; FromPort="3389"; ToPort="3389"; IpRanges="203.0.113.25/32" } Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
Exemplo 4: Com a PowerShell versão 2, você deve usar New-Object para criar os IpPermission objetos.
$ip1 = New-Object Amazon.EC2.Model.IpPermission $ip1.IpProtocol = "tcp" $ip1.FromPort = 22 $ip1.ToPort = 22 $ip1.IpRanges.Add("203.0.113.25/32") $ip2 = new-object Amazon.EC2.Model.IpPermission $ip2.IpProtocol = "tcp" $ip2.FromPort = 3389 $ip2.ToPort = 3389 $ip2.IpRanges.Add("203.0.113.25/32") Grant-EC2SecurityGroupIngress -GroupName "my-security-group" -IpPermission @( $ip1, $ip2 )
Exemplo 5: Este exemplo concede acesso à TCP porta 8081 do grupo de segurança de origem especificado (sg-1a2b3c4d) ao grupo de segurança especificado (sg-12345678).
$ug = New-Object Amazon.EC2.Model.UserIdGroupPair $ug.GroupId = "sg-1a2b3c4d" $ug.UserId = "123456789012" Grant-EC2SecurityGroupIngress -GroupId sg-12345678 -IpPermission @( @{ IpProtocol="tcp"; FromPort="8081"; ToPort="8081"; UserIdGroupPairs=$ug } )
Exemplo 6: Este exemplo adiciona o CIDR 5.5.5.5/32 às regras de entrada do grupo de segurança sg-1234abcd para o tráfego da porta 22 com uma descrição. TCP
$IpRange = New-Object -TypeName Amazon.EC2.Model.IpRange $IpRange.CidrIp = "5.5.5.5/32" $IpRange.Description = "SSH from Office" $IpPermission = New-Object Amazon.EC2.Model.IpPermission $IpPermission.IpProtocol = "tcp" $IpPermission.ToPort = 22 $IpPermission.FromPort = 22 $IpPermission.Ipv4Ranges = $IpRange Grant-EC2SecurityGroupIngress -GroupId sg-1234abcd -IpPermission $IpPermission
-
Para API obter detalhes, consulte AuthorizeSecurityGroupIngressem 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 authorize_ingress(self, ssh_ingress_ip: str) -> Optional[Dict[str, Any]]: """ Adds a rule to the security group to allow access to SSH. :param ssh_ingress_ip: The IP address that is granted inbound access to connect to port 22 over TCP, used for SSH. :return: The response to the authorization request. The 'Return' field of the response indicates whether the request succeeded or failed, or None if no security group is set. :raise Handles AWS SDK service-level ClientError, with special handling for ResourceAlreadyExists """ if self.security_group is None: logger.info("No security group to update.") return None try: ip_permissions = [ { # SSH ingress open to only the specified IP address. "IpProtocol": "tcp", "FromPort": 22, "ToPort": 22, "IpRanges": [{"CidrIp": f"{ssh_ingress_ip}/32"}], } ] response = self.ec2_client.authorize_security_group_ingress( GroupId=self.security_group, IpPermissions=ip_permissions ) except ClientError as err: if err.response["Error"]["Code"] == "InvalidPermission.Duplicate": logger.error( f"The SSH ingress rule for IP {ssh_ingress_ip} already exists" f"in security group '{self.security_group}'." ) raise else: return response
-
Para API obter detalhes, consulte a AuthorizeSecurityGroupIngressReferê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
. /// Add an ingress rule to a security group explicitly allowing IPv4 address /// as {ip}/32 over TCP port 22. pub async fn authorize_security_group_ssh_ingress( &self, group_id: &str, ingress_ips: Vec<Ipv4Addr>, ) -> Result<(), EC2Error> { tracing::info!("Authorizing ingress for security group {group_id}"); self.client .authorize_security_group_ingress() .group_id(group_id) .set_ip_permissions(Some( ingress_ips .into_iter() .map(|ip| { IpPermission::builder() .ip_protocol("tcp") .from_port(22) .to_port(22) .ip_ranges(IpRange::builder().cidr_ip(format!("{ip}/32")).build()) .build() }) .collect(), )) .send() .await?; Ok(()) }
-
Para API obter detalhes, consulte AuthorizeSecurityGroupIngress
a AWS SDKAPIreferência do Rust.
-