UserData = user_data, SecurityGroupIds=[sg.group_id] )
for bucket_name in sys.argv[1:]: try: response = s3.create_bucket(Bucket=ec2-assignbuke2, CreateBucketConfiguration={'LocationConstraint': 'eu-west-1'}) print (response) except Exception as error: print (error)
print(sg.group_id)
Here is an example of a boto3 script that creates a security group in a specific VPC, authorizes ingress from the internet on ports 22 and 80, and launches an EC2 instance into a public subnet of the given VPC.
import boto3
ec2 = boto3.resource("ec2", region_name="eu-west-1")
user_data = """#!/bin/bash
yum update -y
yum install httpd -y
systemctl enable httpd
systemctl start httpd"""
# TODO: configure these as needed
VPC_ID = 'vpc-1234'
SUBNET_ID = 'subnet-5678'
AMI_ID = 'ami-0fc970315c2d38f01'
KEYPAIR = 'AlexBpem'
sg = ec2.create_security_group(
GroupName="MyWebServer", Description="WebServer", VpcId=VPC_ID
)
instance = ec2.create_instances(
ImageId=AMI_ID,
MinCount=1,
MaxCount=1,
InstanceType="t2.nano",
KeyName=KEYPAIR,
UserData=user_data,
NetworkInterfaces=[
{
"SubnetId": SUBNET_ID,
"DeviceIndex": 0,
"AssociatePublicIpAddress": True,
"Groups": [sg.group_id],
}
],
)
response = sg.authorize_ingress(
IpPermissions=[
{
"FromPort": 22,
"ToPort": 22,
"IpProtocol": "tcp",
"IpRanges": [
{"CidrIp": "0.0.0.0/0", "Description": "internet"},
],
},
{
"FromPort": 80,
"ToPort": 80,
"IpProtocol": "tcp",
"IpRanges": [
{"CidrIp": "0.0.0.0/0", "Description": "internet"},
],
},
],
)
For more help, read How To Create And Configure An AWS VPC With Python.