Created
March 11, 2015 16:12
-
-
Save likwid/bd1c62c6adbbe6853114 to your computer and use it in GitHub Desktop.
"Idempotent" ec2 creation with ansible
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
- name: Find trusty ami for base image | |
ec2_ami_search: | |
distro: ubuntu | |
release: trusty | |
region: "{{ aws_region }}" | |
store: ebs-ssd | |
virt: hvm | |
register: ubuntu | |
when: not aws_ami_id is defined | |
- name: Use a custom ami | |
set_fact: | |
current_ami: "{{ aws_ami_id }}" | |
when: aws_ami_id is defined | |
- name: Use the base ubuntu ami | |
set_fact: | |
current_ami: "{{ ubuntu.ami }}" | |
when: not aws_ami_id is defined | |
- name: Determine random private subnet | |
set_fact: | |
current_subnet: "{{ item }}" | |
with_random_choice: aws_private_subnets | |
- name: Query for existing instance | |
command: aws ec2 describe-instances --region {{ aws_region }} --filter Name=tag:Name,Values={{ hostname }} --query "Reservations[].Instances[].PrivateIpAddress" --output text | |
register: query_private_ip | |
- name: Create an ec2 instance if none exists | |
ec2: | |
count: "{{ aws_instance_count }}" | |
group_id: "{{ aws_default_sg }}" | |
key_name: wm-infrastructure | |
image: "{{ current_ami }}" | |
instance_type: "{{ aws_instance_type }}" | |
instance_tags: | |
Name: "{{ hostname }}" | |
Purpose: "{{ purpose }}" | |
Requestor: "{{ requestor | default('') }}" | |
region: "{{ aws_region }}" | |
vpc_subnet_id: "{{ current_subnet }}" | |
wait: yes | |
when: query_private_ip.stdout == '' | |
- name: Get ip address of existing or created instance | |
command: aws ec2 describe-instances --region {{ aws_region }} --filter Name=tag:Name,Values={{ hostname }} --query "Reservations[].Instances[].PrivateIpAddress" --output text | |
register: query_private_ip | |
- name: Set fact for ip address | |
set_fact: | |
ec2_instance_private_address: "{{ query_private_ip.stdout }}" | |
- name: Add instance to group for later plays | |
add_host: | |
name: "{{ ec2_instance_private_address }}" | |
groups: to_be_provisioned | |
- name: Wait for ssh to respond | |
wait_for: | |
host: "{{ ec2_instance_private_address }}" | |
port: 22 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- | |
- hosts: localhost | |
gather_facts: yes | |
sudo: no | |
roles: | |
- ec2-instance | |
- hosts: to_be_provisioned | |
gather_facts: yes | |
sudo: no | |
tasks: | |
- name: Debug | |
debug: | |
msg: "{{ ec2_id }}" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment