terminate.yml 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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: Unsubscribe VMs
  16. hosts: oo_hosts_to_terminate
  17. roles:
  18. - role: rhel_unsubscribe
  19. when: deployment_type == "enterprise" and
  20. ansible_distribution == "RedHat" and
  21. lookup('oo_option', 'rhel_skip_subscription') | default(rhsub_skip, True) |
  22. default('no', True) | lower in ['no', 'false']
  23. - name: Terminate instances
  24. hosts: localhost
  25. connection: local
  26. gather_facts: no
  27. vars:
  28. host_vars: "{{ hostvars
  29. | oo_select_keys(groups['oo_hosts_to_terminate']) }}"
  30. tasks:
  31. - name: Remove tags from instances
  32. ec2_tag: resource={{ item.ec2_id }} region={{ item.ec2_region }} state=absent
  33. args:
  34. tags:
  35. env: "{{ item['ec2_tag_env'] }}"
  36. host-type: "{{ item['ec2_tag_host-type'] }}"
  37. env-host-type: "{{ item['ec2_tag_env-host-type'] }}"
  38. sub_host_type: "{{ item['ec2_tag_sub-host-type'] }}"
  39. with_items: host_vars
  40. when: "'oo_hosts_to_terminate' in groups"
  41. - name: Terminate instances
  42. ec2:
  43. state: absent
  44. instance_ids: ["{{ item.ec2_id }}"]
  45. region: "{{ item.ec2_region }}"
  46. ignore_errors: yes
  47. register: ec2_term
  48. with_items: host_vars
  49. when: "'oo_hosts_to_terminate' in groups"
  50. # Fail if any of the instances failed to terminate with an error other
  51. # than 403 Forbidden
  52. - fail: msg=Terminating instance {{ item.ec2_id }} failed with message {{ item.msg }}
  53. when: "'oo_hosts_to_terminate' in groups and item.failed and not item.msg | search(\"error: EC2ResponseError: 403 Forbidden\")"
  54. with_items: ec2_term.results
  55. - name: Stop instance if termination failed
  56. ec2:
  57. state: stopped
  58. instance_ids: ["{{ item.item.ec2_id }}"]
  59. region: "{{ item.item.ec2_region }}"
  60. register: ec2_stop
  61. when: "'oo_hosts_to_terminate' in groups and item.failed"
  62. with_items: ec2_term.results
  63. - name: Rename stopped instances
  64. ec2_tag: resource={{ item.item.item.ec2_id }} region={{ item.item.item.ec2_region }} state=present
  65. args:
  66. tags:
  67. Name: "{{ item.item.item.ec2_tag_Name }}-terminate"
  68. with_items: ec2_stop.results
  69. when: "'oo_hosts_to_terminate' in groups"