-1

UserData = user_data, SecurityGroupIds=[sg.group_id] )

对于 sys.argv[1:] 中的 bucket_name:try: response = s3.create_bucket(Bucket=ec2-assignbuke2, CreateBucketConfiguration={'LocationConstraint': 'eu-west-1'}) print (response) except Exception as error:打印(错误)

打印(sg.group_id)

4

1 回答 1

1

下面是一个 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

于 2021-03-02T17:39:12.643 回答