简体   繁体   中英

s3 policy update through lambda/boto3 - list index out of range error

I have a requirement to update S3 bucket policy (Get the current resource ARNs and append new Resource ARN). Here is the snippet of code:

import os
import boto3
import pprint
import json
import sys

s3 = boto3.resource('s3')
buckets = ["test090909"]
for s3b in buckets:
        print("processing bucket" + s3b)
        bucket = s3.Bucket(s3b)
        policy = bucket.Policy()
        p =  json.loads(policy.policy)  
        print(p)                        # Good until here
        stmt = p["Statement"][1]
        print(stmt)

The output of p is as below all good until that but if I want to get Resource section then it should be stmt = p["Statement"][1] as this is dict and list index is 1 but I am getting an error IndexError: list index out of range but if I do stmt = p["Statement"][0] it returning everything. I believe I am doing some thing wrong with string/json items I believe.

{
  u'Version': u'2012-10-17',
  u'Id': u'Policy1544682557303',
  u'Statement': [
    {
      u'Action': u's3:DeleteBucket',
      u'Principal': {
        u'Service': u'config.amazonaws.com'
      },
      u'Resource': [
        u'arn:aws:s3:::test090909',
        u'arn:aws:s3:::test090909/AWSLogs/111111111111/Config/*'
      ],
      u'Effect': u'Allow',
      u'Sid': u'Stmt1544682555302'
    }
  ]
}

it should be "stmt = p["Statement"][1]" as this is dict and list index is 1 but i am getting an error " IndexError: list index out of range" but if i do "stmt = p["Statement"][0]" it returning everything

This is not correct. Given the json output, p["Statement"][1] doesn't exist hence the out of range error is raised. p["Statement"] contains only one item. Using your words, p["Statement"][0] returns "everything" because it actually contains everything. It contains a list of Item and one of the item is a list of arn resources.

There you go:

>>print(p["Statement"][0])
[ { u'Action': u's3:DeleteBucket', u'Principal': { u'Service': u'config.amazonaws.com' }, u'Resource': [ u'arn:aws:s3:::test090909', u'arn:aws:s3:::test090909/AWSLogs/111111111111/Config/*' ], u'Effect': u'Allow', u'Sid': u'Stmt1544682555302' } ]

>>print(p["Statement"][0]["Resource"])
[ u'arn:aws:s3:::test090909', u'arn:aws:s3:::test090909/AWSLogs/111111111111/Config/*' ]

Then if you want to access one of the specific resource:

>>print(p["Statement"][0]["Resource"][0])
arn:aws:s3:::test090909

>>print(p["Statement"][0]["Resource"][1])
arn:aws:s3:::test090909/AWSLogs/111111111111/Config/*

Happy coding!

Python索引从0开始,因此p["Statement"][0]将返回该列表中的第一项。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM