Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Create a EC2 instance with ansible-playbook
---
- hosts: localhost
connection: local
vars:
gather_facts: False
vars:
keypair: "my-keypair-name"
instance_type: m4.large
security_group:
- "vpc-group-1"
- "vpc-group-2"
image: "ami-XXXXXXXXXXXXXXXX"
region: us-east-1
user_access_key: "{{ lookup('env', 'AWS_ACCESS_KEY') }}"
user_secret_key: "{{ lookup('env', 'AWS_SECRET_ACCESS_KEY') }}"
tasks:
- name: startup new instance
ec2:
key_name: "{{ keypair }}"
groups: "{{ security_group }}"
instance_type: "{{ instance_type }}"
image: "{{ image }}"
wait: true
region: "{{ region }}"
assign_public_ip: yes
vpc_subnet_id: "subnet-XXXXXXXXXXXXXXXX"
aws_access_key: "{{ user_access_key }}"
aws_secret_key: "{{ user_secret_key }}"
user_data: |
#!/bin/bash -xe
/bin/sed -ri '/Defaults[ ]{1,}requiretty/d' -i /etc/sudoers
termination_protection: yes
instance_tags:
Name: "new-server-name"
volumes:
- device_name: /dev/sda1
volume_type: gp2
volume_size: 8
- device_name: /dev/xvdb
volume_type: gp2
volume_size: 1000
register: ec2
- name: Add new instance to host group
add_host:
hostname: "{{ item.public_ip }}"
groupname: launched
ansible_ssh_host: "{{ item.public_ip }}"
ansible_ssh_port: 22
ansible_ssh_user: 'centos'
ansible_ssh_private_key_file: '/path/to/the/file.pem'
with_items: '{{ec2.instances}}'
- 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}}'
- hosts: launched
# strategy: debug
become: yes
gather_facts: Yes
tasks:
### DO YOUR MAGIC HERE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.