---

- hosts: localhost
  connection: local
  gather_facts: no
  vars_files:
    - ../vars/ec2_security_groups.yaml

  vars:
    provision: false

  tasks:
    - name: set up logging and monitoring security group
      ec2_group:
        name: LoggingMonitoring
        description: Security group for ELK and related logging & monitoring services
        vpc_id: "{{ vpc.vpc_default }}"
        region: us-west-1
        rules:
          - proto: tcp
            from_port: "{{ ports.http }}"
            to_port: "{{ ports.http }}"
            cidr_ip: "{{ cidr.corp.all }}"
          - proto: tcp
            from_port: "{{ ports.http }}"
            to_port: "{{ ports.http }}"
            cidr_ip: "{{ cidr.eng.all }}"
          - proto: tcp
            from_port: "{{ ports.logstash }}"
            to_port: "{{ ports.logstash }}"
            cidr_ip: "{{ cidr.corp.all }}"
          - proto: tcp
            from_port: "{{ ports.logstash }}"
            to_port: "{{ ports.logstash }}"
            cidr_ip: "{{ cidr.eng.all }}"
          - proto: tcp
            from_port: "{{ ports.elasticsearch }}"
            to_port: "{{ ports.elasticsearch }}"
            cidr_ip: "{{ cidr.corp.all }}"
          - proto: tcp
            from_port: "{{ ports.elasticsearch }}"
            to_port: "{{ ports.elasticsearch }}"
            cidr_ip: "{{ cidr.eng.all }}"
          - proto: tcp
            from_port: "{{ ports.kibana }}"
            to_port: "{{ ports.kibana }}"
            cidr_ip: "{{ cidr.eng.all }}"
          - proto: tcp
            from_port: "{{ ports.kibana }}"
            to_port: "{{ ports.kibana }}"
            cidr_ip: "{{ cidr.corp.all }}"
          - proto: tcp
            from_port: "{{ ports.ssh }}"
            to_port: "{{ ports.ssh }}"
            cidr_ip: "{{ cidr.corp.all }}"

    - name: provision elk host
      ec2:
        exact_count: 1
        count_tag:
          Role: elk_server

        image: ami-06116566
        instance_type: t2.medium
        region: us-west-1
        instance_tags:
          Role: elk
          Name: ELK

        key_name: elkserver
        vpc_subnet_id: subnet-ca192a93 # LoggingMonitoring us-west-1
        group:
          - LoggingMonitoring
        assign_public_ip: no
        private_ip: 10.1.14.10
      register: elk
      when: provision

    - name: wait for provisioned servers to start ssh
      wait_for:
        host: "{{ item.private_ip }}"
        port: 22
      with_items: "{{ elk.instances }}"
      when: provision
    - name: accept new ssh fingerprints
      shell: ssh-keyscan -H {{ item.private_ip }} >> ~/.ssh/known_hosts
      with_items: "{{ elk.instances }}"
      when: provision


- hosts: tag_Role_elk
  roles:
    - java
    - elasticsearch
    - logstash
    - kibana
