user3329087
user3329087

Reputation: 31

How do I create an AWS EC2 instance and assign it to an ELB using Ansible?

I am trying to use Ansible to create an EC2 instance, configure a web server and then register it to a load balancer. I have no problem creating the EC2 instance, nor configuring the web server but all attempts to register it against an existing load balancer fail with varying errors depending on the code I use.

Has anyone had success in doing this?

Here are the links to the Ansible documentation for the ec2 and ec2_elb modules:

http://docs.ansible.com/ec2_module.html

http://docs.ansible.com/ec2_elb_module.html

Alternatively, if it is not possible to register the EC2 instance against the ELB post creation, I would settle for another 'play' that collects all EC2 instances with a certain name and loops through them, adding them to the ELB.

Upvotes: 3

Views: 3982

Answers (2)

Rahul Mehrotra
Rahul Mehrotra

Reputation: 639

The below playbook should work for ec2 server creation and registering it to the elb. Make sure you have the variables set properly or you can also hard-code the variable values in playbook.

- name: Creating webserver
  local_action:
    module: ec2
    region: "{{ region }}"
    key_name: "{{ key }}"
    instance_type: t1.micro
    image: "{{ ami_id }}"
    wait: yes
    assign_public_ip: yes
    group_id: ["{{ sg_webserver }}"]
    vpc_subnet_id: "{{ PublicSubnet }}"
    instance_tags: '{"Name": "webserver", "Environment": "Dev"}
  register: webserver
- name: Adding Webserver to ELB
  local_action: 
    module: ec2_elb
    ec2_elbs: "{{ elb_name }}"
    instance_id: "{{ item.id }}"
    state: 'present'
    region: "{{ region }}"
  with_items: nat.instances

Upvotes: 0

hkariti
hkariti

Reputation: 1719

Here's what I do that works:

- name: Add machine to elb
  local_action:
      module: ec2_elb
      aws_access_key: "{{lookup('env', 'AWS_ACCESS_KEY')}}"
      aws_secret_key: "{{lookup('env', 'AWS_SECRET_KEY')}}"
      region: "{{ansible_ec2_placement_region}}"
      instance_id: "{{ ansible_ec2_instance_id }}"
      ec2_elbs: "{{elb_name}}"
      state: present

The biggest issue was the access and secret keys. The ec2_elb module doesn't seem to use the environment variables or read ~/.boto, so I had to pass them manually.

The ansible_ec2_* variables are available if you use the ec2_facts module. You can fill these parameters by yourself of course.

Upvotes: 3

Related Questions