---
- name: Create EC2 instances (CNS)
  ec2:
    assign_public_ip: no
    count_tag:
      Name: "{{ item.name }}"
    exact_count: 1
    group: [
      "cns",
      "node"
    ]
    instance_type: "{{ item.type }}"
    image: "{{ ec2ami }}"
    instance_tags:
      Name: "{{ item.name }}"
    key_name: "{{ clusterid }}.{{ dns_domain }}"
    monitoring: no
    region: "{{ aws_region }}"
    termination_protection: no
    user_data: "{{ lookup('template', ( playbook_dir + '/roles/aws/templates/ec2_userdata.sh.j2') ) }}"
    volumes:
      - device_name: /dev/sda1
        volume_type: gp2
        volume_size: 100
      - device_name: /dev/xvdb
        volume_type: gp2
        volume_size: 100
      - device_name: /dev/xvdc
        volume_type: gp2
        volume_size: 100
      - device_name: /dev/xvdd
        volume_type: gp2
        volume_size: 100
        delete_on_termination: true
    vpc_subnet_id: "{{ item.subnet }}"
    wait: yes
  with_items:
    - name: "cns1"
      subnet: "{{ subnet_private.results.0.subnet.id }}"
      type: "{{ ec2_type_cns }}"
    - name: "cns2"
      subnet: "{{ subnet_private.results.1.subnet.id }}"
      type: "{{ ec2_type_cns }}"
    - name: "cns3"
      subnet: "{{ subnet_private.results.2.subnet.id }}"
      type: "{{ ec2_type_cns }}"
  retries: 3
  delay: 3
  register: ec2cns

- include_tasks: tag.yaml
  vars:
    - resource: "{{ item.tagged_instances[0].id }}"
    - tagss: "clusterid={{ clusterid }}, ami={{ ec2ami }}, kubernetes.io/cluster/{{ clusterid }}={{ clusterid }}, host-type=node, sub-host-type=cns"
  with_items: "{{ ec2cns.results }}"

- include_tasks: tag.yaml
  vars:
    - resource: "{{ item.tagged_instances[0].block_device_mapping['/dev/sda1'].volume_id }}"
    - tagss: "Name={{ item.tagged_instances[0].id }}-rootvol, clusterid={{ clusterid }}, "
  with_items: "{{ ec2cns.results }}"

- include_tasks: tag.yaml
  vars:
    - resource: "{{ item.tagged_instances[0].block_device_mapping['/dev/xvdb'].volume_id }}"
    - tagss: "Name={{ item.tagged_instances[0].id }}-xvdb, clusterid={{ clusterid }}, "
  with_items: "{{ ec2cns.results }}"
