Created
June 15, 2020 04:05
-
-
Save scresante/31810a947ca8987c31cdc1e39fabf2b2 to your computer and use it in GitHub Desktop.
This file contains 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
import boto3 | |
import secrets | |
import sys | |
def create(): | |
user_data = """#!/bin/sh | |
yum update -y | |
yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm | |
yum install -y zsh wireguard-tools""" | |
local_id = secrets.token_hex(8) | |
local_id = 'okwow0' | |
ec2 = boto3.resource("ec2") | |
ec2.create_instances( | |
ImageId="ami-09d95fab7fff3776c", | |
MinCount=1, | |
MaxCount=1, | |
InstanceType="t2.micro", | |
KeyName="boto_keypair", | |
BlockDeviceMappings=[ | |
{ | |
"DeviceName": "/dev/xvda", | |
"Ebs": { | |
"DeleteOnTermination": True, | |
"VolumeSize": 15, | |
"VolumeType": "gp2", | |
"Encrypted": False, | |
}, | |
} | |
], | |
Monitoring={"Enabled": False}, | |
# SecurityGroupIds=[ | |
# 'sg-0a021879a11d440c3', | |
# 'sg-0410e596e9b1e9513', | |
# ], | |
UserData=user_data, | |
InstanceInitiatedShutdownBehavior="terminate", | |
NetworkInterfaces=[ | |
{ | |
"AssociatePublicIpAddress": True, | |
"DeleteOnTermination": True, | |
"DeviceIndex": 0, | |
}, | |
], | |
# TagsSpecifications=[ | |
# {"ResourceType": "instance", "Tags": [{"Key": "lid", "Value": 'okwow0'},]}, | |
# ], | |
) | |
print(f'created new instance with tag lid:{local_id}') | |
return local_id | |
def wait_and_add_sg(lid): | |
new_sgs = ["sg-82c377af", "sg-0410e596e9b1e9513"] | |
client = boto3.client("ec2") | |
ec2 = boto3.resource("ec2") | |
# there needs to be a better way to get a single instance by tag | |
this_tag = client.describe_instances( | |
Filters=[{'Name':'tag:lid','Values':[lid]}]) | |
this_instance = this_tag['Reservations'][0]['Instances'][0] | |
this_id = this_instance['InstanceId'] | |
alivewaiter = client.get_waiter('instance_status_ok') | |
alivewaiter.wait(InstanceIds=[this_id]) | |
print(f'lid {lid} must be running') | |
del this_instance | |
this_instance = [_ for _ in ec2.instances.filter(InstanceIds=[this_id])][0] | |
this_instance.modify_attribute(Groups=new_sgs) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment