gpt4 book ai didi

python - AWS IAM Python Boto3 脚本 - 创建用户

转载 作者:行者123 更新时间:2023-12-01 07:41:52 31 4
gpt4 key购买 nike

我的问题:我正在尝试使用 Python 和 Boto3 库创建 AWS CLI 脚本。我希望脚本要求输入(用户名?编程访问?附加到哪个组?首次登录时更改密码?等)并使用这些详细信息设置用户。

我的尝试:我可以创建用户并授予用户编程访问权限或不授予用户编程访问权限。我的问题在于将选定的组 ARN 传递到 Attach_group_policy PolicyARN='aws:aws:iam::aws:policy/xxxx

我觉得这里确实适合,但不知道该怎么做。希望下面的代码能更好地显示我的问题。


iam = boto3.resource('iam')
iam_keys = boto3.resource('iam')
group_list = boto3.client('iam')
attach_group = boto3.client('iam')

mail = raw_input("Please enter your e-mail address: ")
response = iam.create_user(UserName=mail)

prog = raw_input("Do you require programmatic access?(y/n): ")
if prog == "y":
iam_keys.create_access_key(UserName=mail)
print("Make sure awscli is installed on your machine")
elif prog == "n":
print("Console access only")


### it is this area downwards that things break/get confusing
list = group_list.list_groups(MaxItems=150) ### works
for "GroupName" in list: ### works
print(list) ### works; prints as large JSON, need to output just u' GroupName

float(input("Please pick a Group {}".format(attach)))

var = attach_group.attach_group_policy(GroupName=attach, PolicyArn='aws:aws:iam::aws:policy/xxxx') ### Broke; need to fill in ARN somehow after forward slash

print(response, prog)

我希望将选定的策略(通过键入组的确切名称进行选择)附加到用户。

非常感谢任何帮助,我对Python知识知之甚少,但一直在关注https://boto3.amazonaws.com/v1/documentation/api/latest/index.html

谢谢。

最佳答案

以下是一个 Python 2 示例,说明如何列出 IAM 组、允许用户选择其中一个组,然后使用与所选 IAM 组对应的 ARN:

import boto3

iam = boto3.client('iam')

rsp = iam.list_groups()
groups = rsp['Groups']
print(groups)
index = 1

for group in groups:
print("%d: %s" % (index, group["GroupName"]))
index += 1

option = int(input("Please pick a group number: "))
arn = groups[option-1]["Arn"]
print("You selected group %d: %s" % (option, arn))

或者在Python3中:

import boto3

iam = boto3.client('iam')

rsp = iam.list_groups()
groups = rsp['Groups']
index = 1

for group in groups:
print(f'{index}: {group["GroupName"]}')
index += 1

option = int(input("Please pick a group number: "))
arn = groups[option-1]["Arn"]
print(f'You selected group {option}: {arn}')

这将导致如下结果:

1: admins
2: devops
3: programmers
Please pick a group number: 2
You selected option 2: arn:aws:iam::123456781234:group/devops

注意:您需要为此添加输入验证,例如,如果用户键入 -3 或字母 A。

如果,正如我怀疑的那样,您实际上需要用户按名称选择策略,以便您可以检索该策略的 ARN(以附加到 IAM 组),那么您可以执行以下操作:

rsp = iam.list_policies(Scope='Local', OnlyAttached=False)
policies = rsp['Policies']
index = 1

for policy in policies:
print("%d: %s" % (index, policy["PolicyName"]))
index += 1

option = int(input("Please pick a policy number: "))
arn = policies[option-1]["Arn"]
print("You selected policy %d: %s" % (option, arn))

关于python - AWS IAM Python Boto3 脚本 - 创建用户,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56665209/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com