terminate.yml 2.2 KB

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