gsutil iam ch 命令使用 python

gsutil iam ch command using python

我正在尝试使用 python 执行与此命令相同的功能:

gsutil iam ch group:group_name@gmail.com:objectAdmin gs://bucket_name

我正在尝试使用 python 向组授予 objectAdmin 角色。上面的命令在 cloud powershell 中运行良好,但在 python 中还不能运行

我试图通过在此处 add_bucket_iam_member 函数中将“成员”:{member} 替换为“组”:{group_name} 来做到这一点:

def add_bucket_iam_member(bucket_name, role, member):
"""Add a new member to an IAM Policy"""
   # bucket_name = "your-bucket-name"
   # role = "IAM role, e.g., roles/storage.objectViewer"
   # member = "IAM identity, e.g., user: name@example.com"

   storage_client = storage.Client()
   bucket = storage_client.bucket(bucket_name)

   policy = bucket.get_iam_policy(requested_policy_version=3)

   #policy.bindings.append({"role": role, "members": {member}})
   policy.bindings.append({"role": role, "groups": {group_name}})

   bucket.set_iam_policy(policy)

   print("Added {} with role {} to {}.".format(member, role, bucket_name))

它没有报错但也没有用,完成后,再次获取策略指令后,它删除了我坐的组权限。 (同时,它与成员一起工作正常)

我也试过:

os.system("gsutil iam ch group:group_name@gmail.com:objectAdmin gs://bucket_name")

subprocess.run("gsutil iam ch group:group_name@gmail.com:objectAdmin gs://bucket_name", shell=True) 但还没有工作。

有什么帮助吗?

好的,您的 policy.bindings.append 不正确。

你想要你原来拥有的东西:

role = "roles/storage.objectViewer"

group = "some@googlegroups.com"

member = f"group:{group}"

policy.bindings.append({
  "role": role,
  "members": {
    member,
  }
})

完整示例:

from os import getenv
from google.cloud import storage

bucket_name = getenv("BUCKET")
group = getenv("GROUP")
role = "roles/storage.objectViewer"

member = f"group:{group}"

storage_client = storage.Client()
bucket = storage_client.bucket(bucket_name)

policy = bucket.get_iam_policy(requested_policy_version=3)


policy.bindings.append({
    "role": role, 
    "members": {
        member,
    }
})
bucket.set_iam_policy(policy)

print("Added {} with role {} to {}.".format(member, role, bucket_name))

并且:

PROJECT="[[YOUR-PROJECT]]"
ACCOUNT="[[YOUR-SERVICE-ACCOUNT]]"
BUCKET="[[YOUR-BUCKET]]"
GROUP="[[YOUR-GROUP-EMAIL]]"

gcloud projects create ${PROJECT}

gcloud iam service-accounts create ${ACCOUNT} \
--project=${PROJECT}

EMAIL="${ACCOUNT}@${PROJECT}.iam.gserviceaccount.com"

gcloud iam service-accounts keys create ${PWD}/${ACCOUNT}.json \
--iam-account=${EMAIL} \
--project=${PROJECT}

gcloud projects add-iam-policy-binding ${PROJECT} \
--member=serviceAccount:${EMAIL} \
--role=roles/storage.admin

export GOOGLE_APPLICATION_CREDENTIALS=${PWD}/${ACCOUNT}.json
export GROUP
export BUCKET

python3 -m venv venv
source venv/bin/activate
python3 -m pip install google-cloud-storage
python3 main.py

产量:

Added group:${GROUP} with role roles/storage.objectViewer to ${BUCKET}.

并且:

FILTER=".bindings[]|select(.members|index(\"group:${GROUP}\")).role"

gsutil iam get gs://${BUCKET} \
| jq -r "${FILTER}"

产量:

roles/storage.objectViewer