How to launch multiple EC2 hosts using ansible

Dear Experts,

How to launch multiple EC2 instances using ansible?

I want to create an environment in AWS using below playbook but I see only one instance is being created when I execute below playbook.

Could you please help with missing code/syntax here?

Note: I’m using free account with AWS.

I think this is because you’ve defined the desired count in your vars but not actually in the invocation of the ec2 module.

Something like this should work as you expect:

  • name: create webserver instances
    hosts: localhost
    connection: local
    gather_facts: false

vars:
ec2_instance_count: 2
ec2_instance_tag:
name: webserver

tasks:

  • name: provision ec2 webserver instances
    ec2:
    aws_access_key: “{{ aws_access_key }}”
    aws_secret_key: “{{ aws_secret_key }}”
    count_tag: “{{ ec2_instance_tag }}”
    ec2_url: “{{ ec2_url }}”
    exact_count: “{{ ec2_instance_count }}”
    groups: “{{ ec2_security_group }}”
    key_name: “{{ ec2_key_name }}”
    image: “{{ ec2_image }}”
    instance_tags: “{{ ec2_instance_tag }}”
    instance_type: “{{ ec2_instance_type }}”
    region: “{{ ec2_region }}”
    wait: true
    register: ec2

Cheers,

Will.

Hi Will,

Updated changes but see an error, could you please let me know what is missing? Inserted code for your reference.

fatal: [localhost]: FAILED! => {“changed”: false, “msg”: “argument instance_tags is of type <type ‘str’> and we were unable to convert to dict: dictionary requested, could not parse JSON or key=value”}

Your ec2_instance_tag ‘name:webserver’ is being evaluated as a string because there’s no space, it needs to be a YAML dictionary.

If you read the docs on the module (ansible-doc ec2), they state:

  • instance_tags
    a hash/dictionary of tags to add to the new instance or for starting/stopping instance by tag; ‘{“key”:“value”}’ and
    ‘{“key”:“value”,“key”:“value”}’
    [Default: None]
    version_added: 1.0

And if you pay attention to: http://docs.ansible.com/ansible/latest/reference_appendices/YAMLSyntax.html

A dictionary is represented in a simple key: value form (the colon must be followed by a space):

You have:

ec2_instance_tag:
name:webserver

This should be:

ec2_instance_tag:
name: webserver
^

That worked, thank you Will.