下面是一个 boto3 脚本示例,该脚本在特定 VPC 中创建安全组,在端口 22 和 80 上授权来自 Internet 的入口,并将 EC2 实例启动到给定 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"},
],
},
],
)
如需更多帮助,请阅读如何使用 Python 创建和配置 AWS VPC。