Search code examples
amazon-web-servicesansibleamazon-elbaws-application-load-balancer

issue registering a EC2 instance with an Application Load Balancer (ALB)


According to the docs I should be able to register an EC2 instance with the elb_instance module, but the play fails with ELB Staging1 does not exist. For sanity check I've tried with the AWS CLI tool, but that fails with An error occurred (LoadBalancerNotFound) when calling the RegisterInstancesWithLoadBalancer operation: There is no ACTIVE Load Balancer named 'Staging1'. As a plot twist:

  • AWS console shows the ALB as "Active"
  • elb_application_lb_facts also lists it
  • ec2_elb_facts does not list it (it only list classic ELBs that I have)

It seems like application load balancers are only supported in newer api version and the module or cli were not meant to work with it. However I cannot find an explicit mention that they should not work. I'm also aware of elbv2 command, but it doesn't seem to offer a way to register instances to an ELB.

What am I missing here guys?

Ansible task that I wrote:

- name: Register instances in the ALB
  local_action:
        module: elb_instance
        aws_access_key: "{{ aws_credentials.access_key_id }}"
        aws_secret_key: "{{ aws_credentials.secret_access_key }}"
        region: "{{ aws_region }}"
        instance_id: "{{ item.instance_ids.0 }}"
        ec2_elbs: "Staging1"
        state: present
        wait: yes
  loop: "{{ new_instances.results }}"

alternative with aws cli tool (doesn't work either):

    - name: Register instance in ALB workaround
      command: "aws elb register-instances-with-load-balancer --load-balancer-name Staging1 --instances {{ instance_ids | join(' ') }}"
      environment:
        AWS_REGION: "{{ aws_region }}"
        AWS_ACCESS_KEY: "{{ aws_credentials.access_key_id }}"
        AWS_SECRET_KEY: "{{ aws_credentials.secret_access_key }}"

Solution

  • elbv2 does offer a way to register targets to an elb. You do so by:

    1. Create a target group
    2. Then use the Register target group API to register your EC2 instances
    3. Then use the Create Listener API to associate the ELB with the target group

    There are examples of doing this in the links I've provided.