Skip to content

Instantly share code, notes, and snippets.

@libert-xyz
Created March 15, 2021 16:38
Show Gist options
  • Save libert-xyz/e7e60c04f695ad9ca77de5ff61359bc2 to your computer and use it in GitHub Desktop.
Save libert-xyz/e7e60c04f695ad9ca77de5ff61359bc2 to your computer and use it in GitHub Desktop.
Workflow to test custom roles in different AWS amis
import boto3
import time
##AWS
REGION="us-east-1"
PROFILE="default"
##AMI
AMIS=[
{"os": "centos7", "ami": "ami-0affd4508a5d2481b", "distro":"centos"},
{"os": "centos8", "ami":"ami-0d6e9a57f6259ba3a", "distro":"centos"},
{"os": "amzn2", "ami":"ami-047a51fa27710816e", "distro":"amazon"},
{"os": "ubuntu18", "ami":"ami-02fe94dee086c0c37", "distro":"ubuntu"},
{"os": "ubuntu20", "ami":"ami-03d315ad33b9d49c4", "distro":"ubuntu"}
]
##KEY
KEY="myAws"
##VPC
SG="sg-ae41f0dc"
SUBNET="subnet-03666c74"
ec2 = boto3.resource('ec2')
list_ec2 = boto3.client('ec2')
print ("####")
print ("Launching...")
print ("####")
for i in range(len(AMIS)):
instances = ec2.create_instances(
ImageId = AMIS[i]["ami"],
MinCount = 1,
MaxCount = 1,
InstanceType = 't3.micro',
KeyName = KEY,
SecurityGroupIds=[SG],
SubnetId=SUBNET,
TagSpecifications=[
{
'ResourceType': 'instance',
'Tags': [
{
'Key': 'Name',
'Value': AMIS[i]["os"]
},
{
'Key' : 'env',
'Value': 'ansible'
},
{
'Key' : 'distro',
'Value': AMIS[i]["distro"]
}
]
}
]
)
print ("Launching %s") %(AMIS[i]["os"])
print instances
print ("\n")
print ("Wait until initiated....")
print ("\n")
# time.sleep(55 ) # Sleep for 55 seconds
# def describe():
# custom_filter = [{
# 'Name':'tag:env',
# 'Values': ['ansible-test']},
# {
# 'Name':'instance-state-name',
# 'Values': ['running']}]
# response = list_ec2.describe_instances(Filters=custom_filter)
# for r in response['Reservations']:
# for i in r['Instances']:
# print i['PublicIpAddress'], i['Tags']
# describe()
@libert-xyz
Copy link
Author

inventory_aws_ec2.yml

plugin: aws_ec2
boto_profile: default
regions:
  - us-east-1
filters:
  tag:env:
    - ansible
keyed_groups:
  - key: tags.distro
    separator: ''

hostnames:
  - network-interface.association.public-ip

@libert-xyz
Copy link
Author

ansible.cfg

[defaults]
inventory = inventory_aws_ec2.yml
private_key_file =  /home/myAws.pem

@libert-xyz
Copy link
Author

play.yml

---
- hosts: centos
  become: true
  roles:
    - ansible-role-update

@libert-xyz
Copy link
Author

ansible-playbook -u centos play.yml
ansible-playbook -u ec2-user play.yml
ansible-playbook -u ubuntu play.yml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment