首先需要准备一个角色,授权访问对应的S3 bucket(bucket的创建就不说了)
    角色权限(permissions)如下

    1. {
    2. "Version": "2012-10-17",
    3. "Statement": [
    4. {
    5. "Action": [
    6. "s3:ListBucket"
    7. ],
    8. "Effect": "Allow",
    9. "Resource": [
    10. "arn:aws:s3:::YOUR-S3-BUCKET"
    11. ]
    12. },
    13. {
    14. "Action": [
    15. "s3:GetObject",
    16. "s3:PutObject",
    17. "s3:DeleteObject"
    18. ],
    19. "Effect": "Allow",
    20. "Resource": [
    21. "arn:aws:s3:::YOUR-S3-BUCKET/*"
    22. ]
    23. }
    24. ]
    25. }

    信任关系(Trust Relationship)如下

    1. {
    2. "Version": "2012-10-17",
    3. "Statement": [
    4. {
    5. "Sid": "",
    6. "Effect": "Allow",
    7. "Principal": {
    8. "Service": "es.amazonaws.com"
    9. },
    10. "Action": "sts:AssumeRole"
    11. }
    12. ]
    13. }

    Python代码如下

    1. import boto3
    2. import requests
    3. from requests_aws4auth import AWS4Auth
    4. region = 'us-east-1'
    5. role_arn_for_snapshot = "YOUR-ROLE-ARN"
    6. s3_bucket_name = "YOUR-S3-BUCKET"
    7. host = 'https://YOUR.DOMAIN.es.amazonaws.com'
    8. repo_name = 'MY-SNAPSHOT'
    9. credentials = boto3.Session().get_credentials()
    10. awsauth = AWS4Auth(
    11. credentials.access_key,
    12. credentials.secret_key,
    13. region,
    14. "es",
    15. session_token=credentials.token
    16. )
    17. payload = {
    18. "type": "s3",
    19. "settings": {
    20. "base_path": repo_name,
    21. "bucket": s3_bucket_name,
    22. "endpoint": "s3.amazonaws.com",
    23. "role_arn": role_arn_for_snapshot,
    24. }
    25. }
    26. # Register repository
    27. r = requests.put(
    28. '/'.join((host.rstrip('/'), '_snapshot', repo_name)),
    29. auth=awsauth,
    30. json=payload,
    31. headers={"Content-Type": "application/json"}
    32. )
    33. print(r.status_code)
    34. print(r.text)