Gunakan AuthorizeSecurityGroupIngress dengan AWS SDK atau CLI - Amazon Elastic Compute Cloud

Terjemahan disediakan oleh mesin penerjemah. Jika konten terjemahan yang diberikan bertentangan dengan versi bahasa Inggris aslinya, utamakan versi bahasa Inggris.

Gunakan AuthorizeSecurityGroupIngress dengan AWS SDK atau CLI

Contoh kode berikut menunjukkan cara menggunakanAuthorizeSecurityGroupIngress.

Contoh tindakan adalah kutipan kode dari program yang lebih besar dan harus dijalankan dalam konteks. Anda dapat melihat tindakan ini dalam konteks dalam contoh kode berikut:

.NET
AWS SDK for .NET
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

/// <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) { // 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; } /// <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(); }
Bash
AWS CLI dengan skrip Bash
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

############################################################################### # 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 }

Fungsi utilitas yang digunakan dalam contoh ini.

############################################################################### # 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 untuk C++
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

Aws::EC2::EC2Client ec2Client(clientConfiguration); Aws::EC2::Model::IpRange ip_range; ip_range.SetCidrIp("0.0.0.0/0"); 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); const Aws::EC2::Model::AuthorizeSecurityGroupIngressOutcome authorizeOutcome = ec2Client.AuthorizeSecurityGroupIngress(authorizeRequest); if (!authorizeOutcome.IsSuccess()) { std::cerr << "Failed to set ingress policy for security group " << groupName << ":" << authorizeOutcome.GetError().GetMessage() << std::endl; return false; } std::cout << "Successfully added ingress policy to security group " << groupName << std::endl;
CLI
AWS CLI

Contoh 1: Untuk menambahkan aturan yang mengizinkan lalu lintas SSH masuk

Contoh authorize-security-group-ingress berikut menambahkan aturan yang mengizinkan lalu lintas masuk pada TCP port 22 (SSH).

aws ec2 authorize-security-group-ingress \ --group-id sg-1234567890abcdef0 \ --protocol tcp \ --port 22 \ --cidr 203.0.113.0/24

Output:

{ "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" } ] }

Contoh 2: Untuk menambahkan aturan yang mengizinkan lalu lintas HTTP masuk dari grup keamanan lain

Contoh authorize-security-group-ingress berikut menambahkan aturan yang mengizinkan akses masuk pada TCP port 80 dari grup keamanan sumber sg-1a2b3c4d. Grup sumber harus berada di VPC atau VPC peer yang sama (memerlukan koneksi peering VPC). Lalu lintas masuk diizinkan berdasarkan alamat IP privat dari instans yang dikaitkan dengan grup keamanan sumber (bukan alamat IP publik atau alamat IP Elastis).

aws ec2 authorize-security-group-ingress \ --group-id sg-1234567890abcdef0 \ --protocol tcp \ --port 80 \ --source-group sg-1a2b3c4d

Output:

{ "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" } } ] }

Contoh 3: Untuk menambahkan banyak aturan dalam panggilan yang sama

Contoh authorize-security-group-ingress berikut menggunakan parameter ip-permissions untuk menambahkan dua aturan masuk, satu yang mengizinkan akses masuk pada TCP port 3389 (RDP) dan satu yang mengizinkan ping/ICMP.

aws 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

Output:

{ "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" } ] }

Contoh 4: Guna menambahkan aturan untuk lalu lintas ICMP

Contoh authorize-security-group-ingress berikut menggunakan parameter ip-permissions untuk menambahkan aturan masuk yang mengizinkan pesan ICMP Destination Unreachable: Fragmentation Needed and Don't Fragment was Set (Tipe 3, Kode 4) dari mana saja.

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

Output:

{ "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" } ] }

Contoh 5: Guna menambahkan aturan untuk lalu lintas IPv6

Contoh authorize-security-group-ingress berikut menggunakan parameter ip-permissions untuk menambahkan aturan masuk yang mengizinkan akses SSH (port 22) dari rentang IPv6 2001: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: IpProtocol :/64}]” FromPort ToPort CidrIpv

Output:

{ "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" } ] }

Contoh 6: Guna menambahkan aturan untuk lalu lintas ICMPv6

Contoh authorize-security-group-ingress berikut menggunakan parameter ip-permissions untuk menambahkan aturan masuk yang mengizinkan lalu lintas ICMPv6 dari mana saja.

aws ec2 authorize-security-group-ingress --group-id sg-1234567890abcdef0 --ip-permissions =icmpv6, Ipv6Ranges= "[{6=: :/0}]” IpProtocol CidrIpv

Output:

{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-04b612d9363ab6327", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "icmpv6", "FromPort": -1, "ToPort": -1, "CidrIpv6": "::/0" } ] }

Contoh 7: Tambahkan aturan dengan deskripsi

Contoh authorize-security-group-ingress berikut menggunakan parameter ip-permissions untuk menambahkan aturan masuk yang mengizinkan lalu lintas RDP dari rentang alamat IPv4 tertentu. Aturan mencakup deskripsi untuk membantu Anda mengidentifikasinya nanti.

aws ec2 authorize-security-group-ingress --group-id sg-1234567890abcdef0 --ip-permissions IpProtocol =tcp, =3389, =3389, = "[{=203.0.113.0/24, description='akses RDP dari kantor NY'}]” FromPort ToPort IpRanges CidrIp

Output:

{ "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" } ] }

Contoh 8: Untuk menambahkan aturan masuk yang menggunakan daftar prefiks

Contoh authorize-security-group-ingress berikut menggunakan parameter ip-permissions untuk menambahkan aturan masuk yang mengizinkan semua lalu lintas untuk rentang CIDR dalam daftar prefiks tertentu.

aws ec2 authorize-security-group-ingress --group-id sg-04a351bfe432d4e71 --ip-permissions =all, = "[{=pl-002dc3ec097de1514}]” IpProtocol PrefixListIds PrefixListId

Output:

{ "Return": true, "SecurityGroupRules": [ { "SecurityGroupRuleId": "sgr-09c74b32f677c6c7c", "GroupId": "sg-1234567890abcdef0", "GroupOwnerId": "123456789012", "IsEgress": false, "IpProtocol": "-1", "FromPort": -1, "ToPort": -1, "PrefixListId": "pl-0721453c7ac4ec009" } ] }

Untuk informasi selengkapnya, lihat Grup keamanan di Panduan Pengguna Amazon VPC.

Java
SDK untuk Java 2.x
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

public static String createSecurityGroup(Ec2Client ec2, String groupName, String groupDesc, String vpcId, String myIpAddress) { try { CreateSecurityGroupRequest createRequest = CreateSecurityGroupRequest.builder() .groupName(groupName) .description(groupDesc) .vpcId(vpcId) .build(); CreateSecurityGroupResponse resp = ec2.createSecurityGroup(createRequest); IpRange ipRange = IpRange.builder() .cidrIp(myIpAddress + "/0") .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(); ec2.authorizeSecurityGroupIngress(authRequest); System.out.println("Successfully added ingress policy to security group " + groupName); return resp.groupId(); } catch (Ec2Exception e) { System.err.println(e.awsErrorDetails().errorMessage()); System.exit(1); } return ""; }
JavaScript
SDK untuk JavaScript (v3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

import { AuthorizeSecurityGroupIngressCommand } from "@aws-sdk/client-ec2"; import { client } from "../libs/client.js"; // Grant permissions for a single IP address to ssh into instances // within the provided security group. export const main = async () => { const command = new AuthorizeSecurityGroupIngressCommand({ // Replace with a security group ID from the AWS console or // the DescribeSecurityGroupsCommand. GroupId: "SECURITY_GROUP_ID", IpPermissions: [ { IpProtocol: "tcp", FromPort: 22, ToPort: 22, // Replace 0.0.0.0 with 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: "0.0.0.0/32" }], }, ], }); try { const { SecurityGroupRules } = await client.send(command); console.log(JSON.stringify(SecurityGroupRules, null, 2)); } catch (err) { console.error(err); } };
Kotlin
SDK untuk Kotlin
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

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 } }
PowerShell
Alat untuk PowerShell

Contoh 1: Contoh ini mendefinisikan aturan masuk untuk grup keamanan untuk EC2-VPC. Aturan ini memberikan akses ke alamat IP tertentu untuk SSH (port 22) dan RDC (port 3389). Perhatikan bahwa Anda harus mengidentifikasi grup keamanan untuk EC2-VPC menggunakan ID grup keamanan bukan nama grup keamanan. Sintaks yang digunakan oleh contoh ini membutuhkan PowerShell versi 3 atau lebih tinggi.

$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 )

Contoh 2: Dengan PowerShell versi 2, Anda harus menggunakan New-Object untuk membuat objek. IpPermission

$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 )

Contoh 3: Contoh ini mendefinisikan aturan ingress untuk grup keamanan untuk EC2-Classic. Aturan ini memberikan akses ke alamat IP tertentu untuk SSH (port 22) dan RDC (port 3389). Sintaks yang digunakan oleh contoh ini membutuhkan PowerShell versi 3 atau lebih tinggi.

$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 )

Contoh 4: Dengan PowerShell versi 2, Anda harus menggunakan New-Object untuk membuat objek. IpPermission

$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 )

Contoh 5: Contoh ini memberikan akses port TCP 8081 dari grup keamanan sumber tertentu (sg-1a2b3c4d) ke grup keamanan yang ditentukan (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 } )

Contoh 6: Contoh ini menambahkan CIDR 5.5.5.5/32 ke aturan Ingress dari Grup keamanan sg-1234abcd untuk lalu lintas port TCP 22 dengan deskripsi.

$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
Python
SDK untuk Python (Boto3)
catatan

Ada lebih banyak tentang GitHub. Temukan contoh lengkapnya dan pelajari cara mengatur dan menjalankannya di AWS Repositori Contoh Kode.

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 authorize_ingress(self, ssh_ingress_ip): """ 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. """ if self.security_group is None: logger.info("No security group to update.") return 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.security_group.authorize_ingress( IpPermissions=ip_permissions ) except ClientError as err: logger.error( "Couldn't authorize inbound rules for %s. Here's why: %s: %s", self.security_group.id, err.response["Error"]["Code"], err.response["Error"]["Message"], ) raise else: return response

Untuk daftar lengkap panduan pengembang AWS SDK dan contoh kode, lihatMembuat sumber daya Amazon EC2 menggunakan SDK AWS. Topik ini juga mencakup informasi tentang memulai dan detail tentang versi SDK sebelumnya.