CreateLoadBalancer 搭配 a AWS SDK 或 CLI 使用 - AWS SDK 程式碼範例

文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的 GitHub 範例。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

CreateLoadBalancer 搭配 a AWS SDK 或 CLI 使用

下列程式碼範例示範如何使用 CreateLoadBalancer

動作範例是大型程式的程式碼摘錄,必須在內容中執行。您可以在下列程式碼範例的內容中看到此動作:

.NET
AWS SDK for .NET
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/// <summary> /// Create an Elastic Load Balancing load balancer that uses the specified subnets /// and forwards requests to the specified target group. /// </summary> /// <param name="name">The name for the new load balancer.</param> /// <param name="subnetIds">Subnets for the load balancer.</param> /// <param name="targetGroup">Target group for forwarded requests.</param> /// <returns>The new LoadBalancer object.</returns> public async Task<LoadBalancer> CreateLoadBalancerAndListener(string name, List<string> subnetIds, TargetGroup targetGroup) { var createLbResponse = await _amazonElasticLoadBalancingV2.CreateLoadBalancerAsync( new CreateLoadBalancerRequest() { Name = name, Subnets = subnetIds }); var loadBalancerArn = createLbResponse.LoadBalancers[0].LoadBalancerArn; // Wait for load balancer to be available. var loadBalancerReady = false; while (!loadBalancerReady) { try { var describeResponse = await _amazonElasticLoadBalancingV2.DescribeLoadBalancersAsync( new DescribeLoadBalancersRequest() { Names = new List<string>() { name } }); var loadBalancerState = describeResponse.LoadBalancers[0].State.Code; loadBalancerReady = loadBalancerState == LoadBalancerStateEnum.Active; } catch (LoadBalancerNotFoundException) { loadBalancerReady = false; } Thread.Sleep(10000); } // Create the listener. await _amazonElasticLoadBalancingV2.CreateListenerAsync( new CreateListenerRequest() { LoadBalancerArn = loadBalancerArn, Protocol = targetGroup.Protocol, Port = targetGroup.Port, DefaultActions = new List<Action>() { new Action() { Type = ActionTypeEnum.Forward, TargetGroupArn = targetGroup.TargetGroupArn } } }); return createLbResponse.LoadBalancers[0]; }
CLI
AWS CLI

範例 1:建立面向網際網路的負載平衡器

下列create-load-balancer範例會建立面向網際網路的 Application Load Balancer,並啟用指定子網路的可用區域。

aws elbv2 create-load-balancer \ --name my-load-balancer \ --subnets subnet-b7d581c0 subnet-8360a9e7

輸出:

{ "LoadBalancers": [ { "Type": "application", "Scheme": "internet-facing", "IpAddressType": "ipv4", "VpcId": "vpc-3ac0fb5f", "AvailabilityZones": [ { "ZoneName": "us-west-2a", "SubnetId": "subnet-8360a9e7" }, { "ZoneName": "us-west-2b", "SubnetId": "subnet-b7d581c0" } ], "CreatedTime": "2017-08-25T21:26:12.920Z", "CanonicalHostedZoneId": "Z2P70J7EXAMPLE", "DNSName": "my-load-balancer-424835706.us-west-2.elb.amazonaws.com", "SecurityGroups": [ "sg-5943793c" ], "LoadBalancerName": "my-load-balancer", "State": { "Code": "provisioning" }, "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188" } ] }

如需詳細資訊,請參閱 使用者指南中的教學課程:使用 AWS CLI 建立 Application Load Balancer Balancer

範例 2:建立內部負載平衡器

下列create-load-balancer範例會建立內部 Application Load Balancer,並啟用指定子網路的可用區域。

aws elbv2 create-load-balancer \ --name my-internal-load-balancer \ --scheme internal \ --subnets subnet-b7d581c0 subnet-8360a9e7

輸出:

{ "LoadBalancers": [ { "Type": "application", "Scheme": "internal", "IpAddressType": "ipv4", "VpcId": "vpc-3ac0fb5f", "AvailabilityZones": [ { "ZoneName": "us-west-2a", "SubnetId": "subnet-8360a9e7" }, { "ZoneName": "us-west-2b", "SubnetId": "subnet-b7d581c0" } ], "CreatedTime": "2016-03-25T21:29:48.850Z", "CanonicalHostedZoneId": "Z2P70J7EXAMPLE", "DNSName": "internal-my-internal-load-balancer-1529930873.us-west-2.elb.amazonaws.com", "SecurityGroups": [ "sg-5943793c" ], "LoadBalancerName": "my-internal-load-balancer", "State": { "Code": "provisioning" }, "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-internal-load-balancer/5b49b8d4303115c2" } ] }

如需詳細資訊,請參閱 Application Load Balancer 使用者指南中的教學課程:使用 AWS CLI 建立 Application Load Balancer。

範例 3:建立 Network Load Balancer

下列create-load-balancer範例會建立面向網際網路的網路Load Balancer,並啟用指定子網路的可用區域。它使用子網路映射將指定的彈性 IP 地址與可用區域的負載平衡器節點所使用的網路介面建立關聯。

aws elbv2 create-load-balancer \ --name my-network-load-balancer \ --type network \ --subnet-mappings SubnetId=subnet-b7d581c0,AllocationId=eipalloc-64d5890a

輸出:

{ "LoadBalancers": [ { "Type": "network", "Scheme": "internet-facing", "IpAddressType": "ipv4", "VpcId": "vpc-3ac0fb5f", "AvailabilityZones": [ { "LoadBalancerAddresses": [ { "IpAddress": "35.161.207.171", "AllocationId": "eipalloc-64d5890a" } ], "ZoneName": "us-west-2b", "SubnetId": "subnet-5264e837" } ], "CreatedTime": "2017-10-15T22:41:25.657Z", "CanonicalHostedZoneId": "Z2P70J7EXAMPLE", "DNSName": "my-network-load-balancer-5d1b75f4f1cee11e.elb.us-west-2.amazonaws.com", "LoadBalancerName": "my-network-load-balancer", "State": { "Code": "provisioning" }, "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/net/my-network-load-balancer/5d1b75f4f1cee11e" } ] }

如需詳細資訊,請參閱 Network Load Balancer 使用者指南中的教學課程:使用 AWS CLI 建立 Network Load Balancer。

範例 4:建立 Gateway Load Balancer

下列create-load-balancer範例會建立 Gateway Load Balancer,並啟用指定子網路的可用區域。

aws elbv2 create-load-balancer \ --name my-gateway-load-balancer \ --type gateway \ --subnets subnet-dc83f691 subnet-a62583f9

輸出:

{ "LoadBalancers": [ { "Type": "gateway", "VpcId": "vpc-838475fe", "AvailabilityZones": [ { "ZoneName": "us-east-1b", "SubnetId": "subnet-a62583f9" }, { "ZoneName": "us-east-1a", "SubnetId": "subnet-dc83f691" } ], "CreatedTime": "2021-07-14T19:33:43.324000+00:00", "LoadBalancerName": "my-gateway-load-balancer", "State": { "Code": "provisioning" }, "LoadBalancerArn": "arn:aws:elasticloadbalancing:us-east-1:850631746142:loadbalancer/gwy/my-gateway-load-balancer/dfbb5a7d32cdee79" } ] }

如需詳細資訊,請參閱 Gateway Load Balancer 使用者指南中的使用 AWS CLI 開始使用 Gateway Load Balancer。

Java
Java 2.x 的 SDK
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

/* * Creates an Elastic Load Balancing load balancer that uses the specified * subnets * and forwards requests to the specified target group. */ public String createLoadBalancer(List<Subnet> subnetIds, String targetGroupARN, String lbName, int port, String protocol) { try { List<String> subnetIdStrings = subnetIds.stream() .map(Subnet::subnetId) .collect(Collectors.toList()); CreateLoadBalancerRequest balancerRequest = CreateLoadBalancerRequest.builder() .subnets(subnetIdStrings) .name(lbName) .scheme("internet-facing") .build(); // Create and wait for the load balancer to become available. CreateLoadBalancerResponse lsResponse = getLoadBalancerClient().createLoadBalancer(balancerRequest); String lbARN = lsResponse.loadBalancers().get(0).loadBalancerArn(); ElasticLoadBalancingV2Waiter loadBalancerWaiter = getLoadBalancerClient().waiter(); DescribeLoadBalancersRequest request = DescribeLoadBalancersRequest.builder() .loadBalancerArns(lbARN) .build(); System.out.println("Waiting for Load Balancer " + lbName + " to become available."); WaiterResponse<DescribeLoadBalancersResponse> waiterResponse = loadBalancerWaiter .waitUntilLoadBalancerAvailable(request); waiterResponse.matched().response().ifPresent(System.out::println); System.out.println("Load Balancer " + lbName + " is available."); // Get the DNS name (endpoint) of the load balancer. String lbDNSName = lsResponse.loadBalancers().get(0).dnsName(); System.out.println("*** Load Balancer DNS Name: " + lbDNSName); // Create a listener for the load balance. Action action = Action.builder() .targetGroupArn(targetGroupARN) .type("forward") .build(); CreateListenerRequest listenerRequest = CreateListenerRequest.builder() .loadBalancerArn(lsResponse.loadBalancers().get(0).loadBalancerArn()) .defaultActions(action) .port(port) .protocol(protocol) .defaultActions(action) .build(); getLoadBalancerClient().createListener(listenerRequest); System.out.println("Created listener to forward traffic from load balancer " + lbName + " to target group " + targetGroupARN); // Return the load balancer DNS name. return lbDNSName; } catch (ElasticLoadBalancingV2Exception e) { e.printStackTrace(); } return ""; }
  • 如需 API 詳細資訊,請參閱 CreateLoadBalancer AWS SDK for Java 2.x 參考中的 API

JavaScript
SDK for JavaScript (v3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

const client = new ElasticLoadBalancingV2Client({}); const { LoadBalancers } = await client.send( new CreateLoadBalancerCommand({ Name: NAMES.loadBalancerName, Subnets: state.subnets, }), ); state.loadBalancerDns = LoadBalancers[0].DNSName; state.loadBalancerArn = LoadBalancers[0].LoadBalancerArn; await waitUntilLoadBalancerAvailable( { client }, { Names: [NAMES.loadBalancerName] }, );
  • 如需 API 詳細資訊,請參閱 CreateLoadBalancer AWS SDK for JavaScript 參考中的 API

PowerShell
for PowerShell 工具

範例 1:此範例會建立新的網際網路面向應用程式負載平衡器,具有兩個子網路。

New-ELB2LoadBalancer -Type application -Scheme internet-facing -IpAddressType ipv4 -Name 'New-Test-ALB' -SecurityGroup 'sg-07c3414abb8811cbd' -subnet 'subnet-c37a67a6','subnet-fc02eea0'

輸出:

AvailabilityZones : {us-east-1b, us-east-1a} CanonicalHostedZoneId : Z35SXDOTRQ7X7K CreatedTime : 12/28/19 2:58:03 PM DNSName : New-Test-ALB-1391502222.us-east-1.elb.amazonaws.com IpAddressType : ipv4 LoadBalancerArn : arn:aws:elasticloadbalancing:us-east-1:123456789012:loadbalancer/app/New-Test-ALB/dab2e4d90eb51493 LoadBalancerName : New-Test-ALB Scheme : internet-facing SecurityGroups : {sg-07c3414abb8811cbd} State : Amazon.ElasticLoadBalancingV2.Model.LoadBalancerState Type : application VpcId : vpc-2cfd7000
  • 如需 API 詳細資訊,請參閱 AWS Tools for PowerShell Cmdlet 參考中的 CreateLoadBalancer

Python
Python 的 SDK (Boto3)
注意

還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

class ElasticLoadBalancerWrapper: """Encapsulates Elastic Load Balancing (ELB) actions.""" def __init__(self, elb_client: boto3.client): """ Initializes the LoadBalancer class with the necessary parameters. """ self.elb_client = elb_client def create_load_balancer( self, load_balancer_name: str, subnet_ids: List[str], ) -> Dict[str, Any]: """ Creates an Elastic Load Balancing load balancer that uses the specified subnets and forwards requests to the specified target group. :param load_balancer_name: The name of the load balancer to create. :param subnet_ids: A list of subnets to associate with the load balancer. :return: Data about the newly created load balancer. """ try: response = self.elb_client.create_load_balancer( Name=load_balancer_name, Subnets=subnet_ids ) load_balancer = response["LoadBalancers"][0] log.info(f"Created load balancer '{load_balancer_name}'.") waiter = self.elb_client.get_waiter("load_balancer_available") log.info( f"Waiting for load balancer '{load_balancer_name}' to be available..." ) waiter.wait(Names=[load_balancer_name]) log.info(f"Load balancer '{load_balancer_name}' is now available!") except ClientError as err: error_code = err.response["Error"]["Code"] log.error( f"Failed to create load balancer '{load_balancer_name}'. Error code: {error_code}, Message: {err.response['Error']['Message']}" ) if error_code == "DuplicateLoadBalancerNameException": log.error( f"A load balancer with the name '{load_balancer_name}' already exists. " "Load balancer names must be unique within the AWS region. " "Please choose a different name and try again." ) if error_code == "TooManyLoadBalancersException": log.error( "The maximum number of load balancers has been reached in this account and region. " "You can delete unused load balancers or request an increase in the service quota from AWS Support." ) log.error(f"Full error:\n\t{err}") else: return load_balancer
  • 如需 API 詳細資訊,請參閱 CreateLoadBalancer AWS SDK for Python (Boto3) Word 參考中的 API