How to structure an accessible script to instantiate or not instantiate
I have scripts to build infrastructure on existing server instances. My inventory files define all hosts, and players work with instances in my inventory file.
My question is, what is the best practice for creating new instances? should it be included in scripts that set up the environment or share? I'm a little confused how the script can instantiate (like EC2 instances) and take inventory files.
source to share
Maybe this example will help you in reproduction, it will create the instance (s) for you and then run tasks / roles on those created instances all in one, it will also add the ip of the newly created instances in (suppose it is in the same directory from where you run this book):
---
- name: Provision an EC2 Instance
hosts: local
connection: local
gather_facts: False
tags: provisioning
# Necessary Variables for creating/provisioning the EC2 Instance
vars:
instance_type: t1.micro
security_group: test-sg
image: ami-98aa1cf0
region: us-east-1
keypair: ansible
count: 1
# Task that will be used to Launch/Create an EC2 Instance
tasks:
- name: Create a security group
local_action:
module: ec2_group
name: "{{ security_group }}"
description: Security Group for Servers
region: "{{ region }}"
rules:
- proto: tcp
type: ssh
from_port: 22
to_port: 22
cidr_ip: 0.0.0.0/0
- proto: tcp
from_port: 6800
to_port: 6800
cidr_ip: 0.0.0.0/0
rules_egress:
- proto: all
type: all
cidr_ip: 0.0.0.0/0
- name: Launch the new EC2 Instance
local_action: ec2
group={{ security_group }}
instance_type={{ instance_type}}
image={{ image }}
wait=true
region={{ region }}
keypair={{ keypair }}
count={{count}}
register: ec2
- name: Add the newly created EC2 instance(s) to the local host group
local_action: lineinfile
dest="./hosts"
regexp={{ item.public_ip }}
insertafter="[ec2server]" line={{ item.public_ip }}
with_items: ec2.instances
- name: Wait for SSH to come up
local_action: wait_for
host={{ item.public_ip }}
port=22
state=started
with_items: ec2.instances
- name: Add tag to Instance(s)
local_action: ec2_tag resource={{ item.id }} region={{ region }} state=present
with_items: ec2.instances
args:
tags:
Name: test
- name: SSH to the EC2 Instance(s)
add_host: hostname={{ item.public_ip }} groupname=ec2server
with_items: ec2.instances
- name: Install these things on Newly created EC2 Instance(s)
hosts: ec2server
sudo: True
remote_user: ubuntu
gather_facts: True
# Run these tasks
tasks:
- include: tasks/upgrade.yml
And your hosts file will look like this:
[local]
localhost
[ec2server]
Hope this helps you. Thanks to
source to share