AWS IAM Python Boto3脚本-创建用户

时间:2019-06-19 10:10:11

标签: python amazon-web-services aws-sdk boto3 aws-cli

我的问题:我正在尝试使用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)

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

非常感谢您的帮助,我对https://boto3.amazonaws.com/v1/documentation/api/latest/index.html

的了解很少,

谢谢。

1 个答案:

答案 0 :(得分:1)

这是一个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))