How to create a s3 bucket using Boto3?

后端 未结 4 1555
离开以前
离开以前 2021-02-13 03:53

I want to enable cloudtrail logs for my account and so need to create an s3 bucket.I wanted to automate this task using Boto3.Currently I am using the following script



        
4条回答
  •  攒了一身酷
    2021-02-13 04:20

    To create an S3 Bucket using Python on AWS, you need to have "aws_access_key_id_value" and "aws_secret_access_key_value". You can store such variables in config.properties and write your code in create-s3-blucket.py file

    Create a config.properties and save the following code in it.

    aws_access_key_id_value='YOUR-ACCESS-KEY-OF-THE-AWS-ACCOUNT'
    aws_secret_access_key_value='TOUR-SECRETE-KEY-OF-THE-AWS-ACCOUNT'
    Bucket_value='S3-BUCKET-NAME'
    LocationConstraint_value='REGION-FOR-S3-BUCKET'
    

    Create create-s3-blucket.py and save the following code in it.

    import boto3
    
    def getVarFromFile(filename):
        import imp
        f = open(filename)
        global data
        data = imp.load_source('data', '', f)
        f.close()
    
    getVarFromFile('config.properties')
    
    client = boto3.client(
        's3',
        aws_access_key_id=data.aws_access_key_id_value,
        aws_secret_access_key=data.aws_secret_access_key_value
    )
    client.create_bucket(Bucket=data.Bucket_value, CreateBucketConfiguration={'LocationConstraint': data.LocationConstraint_value})
    

    Use the following command to execute the python code.

    python create-s3-blucket.py
    

    In the same way, you can add different parameters and customise this code. Refer AWS's official documentation for more understanding.

提交回复
热议问题