How to create and attach a ELB properly in Boto3

2020-06-30 02:49发布

I'm new to Amazon's Boto3 API. I created a basic diagram of my sample architecture shown below, with an ELB, 4 instances, 2 subnets and and 2 target groups in 2 different Availability Zones (2 instances in each target group).

enter image description here

I know how to create an EC2 instance, a target group, subnets, and an ELB. But what ELB functions to use, is not clear to me.

How I can attach the ELB to other components? Basically, how to add instances to the ELB? I'm not sure what next steps and functions are needed now.

Here is my simple code so far:

def create_load_balancer(load_balancer_name, vpcid, subnets, security_group):
    command = "aws elbv2 create-load-balancer --name " + load_balancer_name + " --subnets " + subnets + " --security-groups " + security_group+" --scheme internet-facing --type application"
    response = os.popen(command).read()

// ....created 4 instances, subnets, and security groups ...

//now ELB:
#Load Balancer
elb = boto3.client('elbv2')
elb.create_target_group( Name='boto3-target-a', Protocol='HTTP',  Port=80, VpcId=vpc.id)
elb.create_target_group( Name='boto3-target-b', Protocol='HTTP',  Port=80, VpcId=vpc.id)
response = elb.create_load_balancer(Name="elb_boto3", Listeners=[ { 'Protocol': 'tcp', 'LoadBalancerPort': 80, 'InstanceProtocol': 'tcp', 'InstancePort': 80, 'SSLCertificateId': 'string'}, ], Subnets=[subnet1,subnet2], SecurityGroups=[sec_group], Scheme='internet-facing', Type='application')

1条回答
萌系小妹纸
2楼-- · 2020-06-30 03:40

Use register_targets() to attach instances to a Target Group:

response = client.register_targets(
    TargetGroupArn='arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067',
    Targets=[
        {
            'Id': 'i-80c8dd94',
        },
        {
            'Id': 'i-ceddcd4d',
        },
    ],
)

Use create_listener() to associate a Target Group with a Load Balancer:

response = client.create_listener(
    DefaultActions=[
        {
            'TargetGroupArn': 'arn:aws:elasticloadbalancing:us-west-2:123456789012:targetgroup/my-targets/73e2d6bc24d8a067',
            'Type': 'forward',
        },
    ],
    LoadBalancerArn='arn:aws:elasticloadbalancing:us-west-2:123456789012:loadbalancer/app/my-load-balancer/50dc6c495c0c9188',
    Port=80,
    Protocol='HTTP',
)

From the create_target_group() documentation:

To register targets with the target group, use RegisterTargets . To update the health check settings for the target group, use ModifyTargetGroup . To monitor the health of targets in the target group, use DescribeTargetHealth .

To route traffic to the targets in a target group, specify the target group in an action using CreateListener or CreateRule .

So, the best order of creation is:

  • Create Load Balancer
  • Create Target Groups
  • Create Listeners to link Target Groups to the ELB
  • Register instances to Target Groups
查看更多
登录 后发表回答