我是python和boto3的新手,所以如果我错过了一些简单的事情,请原谅我。
我正在尝试使用python和boto3在我的Lambda函数中创建角色。我的Lambda函数中有2个文件,它们是:Roles.py和Roles.config.json。从下面的代码中可以看到,我使用json.load引入了json文件。我尝试了以下方法: 1.使用json格式化程序和验证程序 2.使用json.loads,dump和dump 3.使用以下命令将前提条件中的单引号替换为双引号 .replace(尽管我不确定那是否仍然是一种方法) 4.更改策略(对于hypok_role_policy),使其不包括在内 “原理”
roles.py
import boto3
import botocore
import json
from pprint import pprint
from botocore.exceptions import ClientError
import time
import urllib
def lambda_handler(event, context):
# return
with open('roles.config.json') as roles_config:
config = json.load(roles_config)
print(config)
role_id = config['role_id']
role_name = config['role_name']
desired_policy = config['desired_policy']
topic_arn = config['topic_arn']
assumed_role = config['assumed_role']
assume_role_policy = config['assume_role_policy']
policy_name = config['policy_name']
assume_role_session = config['assume_role_session']
accounts = config['accounts']
region = config['region']
role_arn_compliance = config['role_arn_compliance']
role_arn_nonprod = config['role_arn_nonprod']
role_arn_demo = config['role_arn_demo']
session = create_session(role_arn=role_arn_nonprod)
print('session = '+str(session))
# client = boto3.client('iam')
# resource = boto3.client('iam')
client = session.client('iam')
resource = session.client('iam')
listRoles = client.list_roles()
# pprint(listRoles)
RolesList = listRoles['Roles'][0]['RoleName']
for roles in listRoles['Roles']:
# print(roles)
assumes_role_policy = str(assume_role_policy)
roles_names = roles['RoleName']
print(roles_names)
print(assume_role_policy)
print(type(assumes_role_policy))
if role_name in roles_names:
print("All's Well!!!")
else:
print("Create another one!")
print(role_name)
new_role = client.create_role(
RoleName = role_name,
AssumeRolePolicyDocument = assumes_role_policy
)
break
roles.config.json
{
"desired_policy":"arn:aws:iam::aws:policy/AmazonDynamoDBReadOnlyAccess",
"topic_arn":"arn:aws:sns:us-east-1:000000000000:Test",
"assumed_role":"arn:aws:iam::111111111111:role/Role1",
"role_id":"AeO4JD56FFWw4SPALPMGS",
"role_name":"sample_read_only",
"assume_role_policy":
{
"Version": "2012-10-17",
"Statement":
[
{
"Effect": "Allow",
"Principal":
{
"Service": "ec2.amazonaws.com"
},
"Action": "sts:AssumeRole"
}
]
},
"policy_name":"AmazonDynamoDBReadOnlyAccess",
"assume_role_session":"AssumeRoleSession",
"accounts":[
"000000000000",
"111111111111",
"222222222222"
],
"region":"us-east-1",
"role_arn_compliance":"arn:aws:iam::000000000000:role/Role0",
"role_arn_nonprod":"arn:aws:iam::111111111111:role/Role1",
"role_arn_demo":"arn:aws:iam::111111111111:role/Role2"
}
答案 0 :(得分:0)
这可能是编码问题,请尝试:
with open('roles.config.json', 'r') as myfile:
policy=myfile.read()
encodedPolicy = urllib.quote(policy)
new_role = iam.create_role(
AssumeRolePolicyDocument=encodedPolicy,
Path='/',
RoleName=role_name
)