簡體   English   中英

AWS IAM Python Boto3腳本-創建用戶

[英]AWS IAM Python Boto3 script - Create User

我的問題:我正在嘗試使用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))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM