Leveraging Ansible to automate AWS instance management
Instance Creation
# Launch an ubuntu instance and wait for ssh
- name: Create an instance request
hosts: localhost
gather_facts: False
tasks:
- name: query api
ec2_ami_info:
filters:
name: "ubuntu/images/hvm-ssd/ubuntu-bionic-18.04-amd64-server-*"
owner-id: "099720109477" # Canonical Group Limited
register: amis
- name: sort by creation date
set_fact:
sorted_amis: "{{ amis.images | sort(attribute='creation_date') }}"
- name: get latest
set_fact:
latest_ami: "{{ sorted_amis | last }}"
- name: Launch instance
ec2:
key_name: "{{ key }}"
instance_type: "{{ instance_type | default('m5.xlarge') }}"
group:
- <your-security-groups>
image: "{{ latest_ami.image_id }}"
count: "{{ count | default('1') }}"
wait: yes
wait_timeout: 500
region: "{{ region }}"
spot_wait_timeout: 600
instance_initiated_shutdown_behavior: terminate
ebs_optimized: yes
volumes:
- device_name: /dev/sda1
volume_type: gp2
volume_size: "{{ volume_size | default('20') }}"
delete_on_termination: yes
instance_tags:
Name: "{{ Name }}"
CNAME: "{{ Name }}.<your-domain>"
register: ec2
- name: Wait for SSH to come up
wait_for:
host: "{{ item.public_dns_name }}"
port: 22
delay: 60
timeout: 320
state: started
with_items: "{{ ec2.instances }}"Instance Termination
Instance Resizing
Last updated
Was this helpful?