上下文:我有一个Python脚本,可以创建一个User,决定是否以编程方式访问,并列出当前的Users组。 我的问题是我希望将新用户添加到显示的现有组之一中。
我尝试了下面的代码,但收到以下错误:
python ec2-play.py
Please enter your e-mail address: 1@1.com
Do you require programmatic access?(y/n): n
Console access only
[...list of Groups...]
1: admin-short-term
2: aws-admin
3: aws-admin-mfa
4: aws-training
Please pick a Group number: 4
You selected option 4: arn:aws:iam::xxxxxxxxxxxx:group/aws-training
Traceback (most recent call last):
File "ec2-play.py", line 41, in <module>
final = grp.add_user_to_group(GroupName=g, UserName=mail)
File "/opt/axe/local/python/local/lib/python2.7/site-packages/botocore/client.py", line 314, in _api_call
return self._make_api_call(operation_name, kwargs)
File "/opt/axe/local/python/local/lib/python2.7/site-packages/botocore/client.py", line 612, in _make_api_call
raise error_class(parsed_response, operation_name)
botocore.errorfactory.NoSuchEntityException: An error occurred (NoSuchEntity) when calling the AddUserToGroup operation: The group with name r cannot be found.
产生错误输出的代码如下:
import boto3
iam = boto3.resource('iam')
iam_keys = boto3.resource('iam')
group_list = boto3.client('iam')
attach_group = boto3.client('iam')
grp = 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")
list = group_list.list_groups()
groups = list['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 option %d: %s" % (option, arn))
var = "%s" % (arn)
var.split(":group/")[1]
g = var[1]
final = grp.add_user_to_group(GroupName=g, UserName=mail)
print("User has been added to Group %s you selected" % (g))
预期的行为:新用户将附加到选定的组。
实际行为: Python崩溃,提示找不到组r。
答案 0 :(得分:1)
您已经计算出选择了哪个组-这是©
列表中的第option-1
个元素。您可以通过常规方式检索其任何属性,例如:
groups
不用计算和使用group = groups[option-1]
group_name = group["GroupName"]
group_arn = group["Arn"]
,只需使用g
作为组名(或如上所述计算的groups[option-1][“GroupName”]
)。
这里的大局是,您将需要学习如何调试代码。一种方法是将输出的值打印出来(例如,var和g),并将其与期望的值进行比较。源级调试器是另一种方法。