terminate.yml 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. ---
  2. - name: Terminate instance(s)
  3. hosts: localhost
  4. gather_facts: no
  5. vars_files:
  6. - vars.yml
  7. tasks:
  8. - set_fact: scratch_group=tag_env_{{ cluster_id }}
  9. - add_host:
  10. name: "{{ item }}"
  11. groups: oo_hosts_to_terminate
  12. ansible_ssh_user: "{{ deployment_vars[deployment_type].ssh_user }}"
  13. ansible_sudo: "{{ deployment_vars[deployment_type].sudo }}"
  14. with_items: groups[scratch_group] | default([]) | difference(['localhost'])
  15. - name: Terminate instances
  16. hosts: localhost
  17. connection: local
  18. gather_facts: no
  19. vars:
  20. host_vars: "{{ hostvars
  21. | oo_select_keys(groups['oo_hosts_to_terminate']) }}"
  22. tasks:
  23. - name: Remove tags from instances
  24. ec2_tag: resource={{ item.ec2_id }} region={{ item.ec2_region }} state=absent
  25. args:
  26. tags:
  27. env: "{{ item['ec2_tag_env'] }}"
  28. host-type: "{{ item['ec2_tag_host-type'] }}"
  29. env-host-type: "{{ item['ec2_tag_env-host-type'] }}"
  30. with_items: host_vars
  31. when: "'oo_hosts_to_terminate' in groups"
  32. - name: Terminate instances
  33. ec2:
  34. state: absent
  35. instance_ids: ["{{ item.ec2_id }}"]
  36. region: "{{ item.ec2_region }}"
  37. ignore_errors: yes
  38. register: ec2_term
  39. with_items: host_vars
  40. when: "'oo_hosts_to_terminate' in groups"
  41. # Fail if any of the instances failed to terminate with an error other
  42. # than 403 Forbidden
  43. - fail: msg=Terminating instance {{ item.ec2_id }} failed with message {{ item.msg }}
  44. when: "'oo_hosts_to_terminate' in groups and item.failed and not item.msg | search(\"error: EC2ResponseError: 403 Forbidden\")"
  45. with_items: ec2_term.results
  46. - name: Stop instance if termination failed
  47. ec2:
  48. state: stopped
  49. instance_ids: ["{{ item.item.ec2_id }}"]
  50. region: "{{ item.item.ec2_region }}"
  51. register: ec2_stop
  52. when: "'oo_hosts_to_terminate' in groups and item.failed"
  53. with_items: ec2_term.results
  54. - name: Rename stopped instances
  55. ec2_tag: resource={{ item.item.item.ec2_id }} region={{ item.item.item.ec2_region }} state=present
  56. args:
  57. tags:
  58. Name: "{{ item.item.item.ec2_tag_Name }}-terminate"
  59. with_items: ec2_stop.results
  60. when: "'oo_hosts_to_terminate' in groups"