diff --git a/config.cfg b/config.cfg index d48872d..a8c86e8 100644 --- a/config.cfg +++ b/config.cfg @@ -58,3 +58,10 @@ SSH_keys: comment: algo@ssh private: configs/algo.pem public: configs/algo.pem.pub + +dynamic_inventory_groups: + - azure + - digitalocean + - ec2 + - gce + - local diff --git a/playbooks/local.yml b/playbooks/local.yml index a7bc353..7627401 100644 --- a/playbooks/local.yml +++ b/playbooks/local.yml @@ -12,3 +12,14 @@ - name: Change mode for the SSH private key local_action: file path=configs/algo.pem mode=0600 + +- name: Ensure the dynamic inventory exists + blockinfile: + dest: configs/inventory.dynamic + marker: "# {mark} ALGO MANAGED BLOCK" + create: yes + block: | + [algo:children] + {% for group in dynamic_inventory_groups %} + {{ group }} + {% endfor %} diff --git a/roles/cloud-ec2/tasks/main.yml b/roles/cloud-ec2/tasks/main.yml index edbfc02..00a87dd 100644 --- a/roles/cloud-ec2/tasks/main.yml +++ b/roles/cloud-ec2/tasks/main.yml @@ -96,6 +96,7 @@ region: "{{ region }}" instance_tags: name: "{{ aws_server_name }}" + Environment: Algo exact_count: 1 count_tag: name: "{{ aws_server_name }}" @@ -115,3 +116,29 @@ - set_fact: cloud_instance_ip: "{{ ec2.tagged_instances[0].public_ip }}" + +- name: Get EC2 instances + ec2_remote_facts: + aws_access_key: "{{ aws_access_key | default(lookup('env','AWS_ACCESS_KEY_ID'))}}" + aws_secret_key: "{{ aws_secret_key | default(lookup('env','AWS_SECRET_ACCESS_KEY'))}}" + region: "{{ region }}" + filters: + instance-state-name: running + "tag:Environment": Algo + register: algo_instances + +- name: Ensure the group ec2 exists in the dynamic inventory file + lineinfile: + state: present + dest: configs/inventory.dynamic + line: '[ec2]' + +- name: Populate the dynamic inventory + lineinfile: + state: present + dest: configs/inventory.dynamic + insertafter: '\[ec2\]' + regexp: "^{{ item.public_ip_address }}.*" + line: "{{ item.public_ip_address }}" + with_items: + - "{{ algo_instances.instances }}"