in radlab-launcher/radlab.py [0:0]
def moduleperm(projid, module_name, currentusr):
# Check if any of the org policy is used in orgpolicy.tf
setorgpolicy = True
try:
## Finding policy variables in orgpolicy.tf
with open(os.path.dirname(os.getcwd()) + '/modules/' + module_name + '/orgpolicy.tf', "r") as file:
policy_vars = []
for line in file:
if ('count' in line and 'var.' in line and '||' not in line):
policy_vars.append(line[line.find("var.") + len("var."):line.find("?")].strip())
# print("Org Policy Variables:")
# print(policy_vars)
## [CHECK 1] Checking for commented orgpolicy resource in orgpolicy.tf
numCommentedOrgPolicy = 0
for policy in policy_vars:
with open(os.path.dirname(os.getcwd()) + '/modules/' + module_name + '/orgpolicy.tf', "r") as file:
for line in file:
# Finding Org policy resource block
if ('count' in line and 'var.' + policy in line and '?' in line):
# Checking for commented resource block line
if (line.startswith('#') or line.startswith('//')):
numCommentedOrgPolicy = numCommentedOrgPolicy + 1
# If No. of commented Org Policies are equal to total policies; No Org policy set
if (numCommentedOrgPolicy == len(policy_vars)):
setorgpolicy = False
## [CHECK 2] Checking if policy variables in variables.tf are set to 'false'
numDisabledOrgPolicyVar = 0
for var in policy_vars:
varblock = ""
block = False
with open(os.path.dirname(os.getcwd()) + '/modules/' + module_name + '/variables.tf', "r") as file:
for line in file:
if (var in line):
block = True
elif ('}' in line):
block = False
if (block == True):
varblock = varblock + line
# print(varblock + '}')
# Count number of disabled policies
if ('false' in varblock.split('default')[1]):
numDisabledOrgPolicyVar = numDisabledOrgPolicyVar + 1
# If No. of disabled Org Policies are equal to total policies; No Org policy set
if (numDisabledOrgPolicyVar == len(policy_vars)):
setorgpolicy = False
## [CHECK 3] Checking if policy variables in variables.tf are commented
numCommentedOrgPolicyVar = 0
for var in policy_vars:
with open(os.path.dirname(os.getcwd()) + '/modules/' + module_name + '/variables.tf', "r") as file:
for line in file:
# Finding Org policy resource block
if ('variable' in line and policy in line):
# Checking for commented resource block line
if (line.startswith('#') or line.startswith('//') or line.startswith('/*')):
numCommentedOrgPolicyVar = numCommentedOrgPolicyVar + 1
# If No. of commented Org Policies Variables are equal to total policies; No Org policy set
if (numCommentedOrgPolicyVar == len(policy_vars)):
setorgpolicy = False
except:
setorgpolicy = False
# Check if reusing project
create_project = True
try:
## Finding 'create_project' variable in variables.tf
varblock = ""
block = False
with open(os.path.dirname(os.getcwd()) + '/modules/' + module_name + '/variables.tf', "r") as file:
for line in file:
if ('create_project' in line):
block = True
elif ('}' in line):
block = False
if (block == True):
varblock = varblock + line
# print(varblock + '}')
if ('false' in varblock.split('default')[1]):
create_project = False
except Exception as e:
print(e)
print("\nSET ORG POLICY: " + str(setorgpolicy))
print("CREATE PROJECT: " + str(create_project))
# Scrape out Module specific permissions for the module
try:
with open(os.path.dirname(os.getcwd()) + '/modules/' + module_name + '/README.md', "r") as file:
section = False
orgroles = []
projroles = []
for line in file:
if (line.startswith("## IAM Permissions Prerequisites")):
section = True
# Identifying Roles if New Project is supposed to be created
if (create_project == True):
if (section == True and line.startswith('- Parent: `')):
orgroles.append(re.search("\`(.*?)\`", line).group(1))
if (section == True and line.startswith('- Project: `')):
projroles.append(re.search("\`(.*?)\`", line).group(1))
# Identifying Roles if Reusing any Existing project
else:
if (section == True and (line.startswith('- `') or line.startswith('- `'))):
projroles.append(re.search("\`(.*?)\`", line).group(1))
if (line.startswith('#') and not line.startswith("## IAM Permissions Prerequisites")):
section = False
# Removing optional role 'roles/orgpolicy.policyAdmin' if Org Policy is not set
if (setorgpolicy == False and 'roles/orgpolicy.policyAdmin' in orgroles):
orgroles.remove('roles/orgpolicy.policyAdmin')
except:
print(Fore.RED + 'IAM Permissions Prerequisites are missing in the README.md or the README.md file do not exisits for module : ' + module_name + Style.RESET_ALL)
# Check Module permissions permission
credentials = GoogleCredentials.get_application_default()
service = discovery.build('cloudresourcemanager', 'v3', credentials=credentials)
# Check Project level permissions
if len(projroles) != 0:
# print("Project Roles to check:")
# print(projroles)
# print("/*************** PROJECT IAM POLICY *************/")
request1 = service.projects().getIamPolicy(resource='projects/' + projid)
response1 = request1.execute()
projiam = True
for role in projroles:
rolefound = False
for y in range(len(response1['bindings'])):
# print("ROLE --->")
# print(response1['bindings'][y]['role'])
# print("MEMBERS --->")
# print(response1['bindings'][y]['members'])
if (role == response1['bindings'][y]['role']):
rolefound = True
if ('user:' + currentusr not in response1['bindings'][y]['members']):
projiam = False
sys.exit(Fore.RED + "\nError Occured - RADLAB MODULE PERMISSION ISSUE | " + role + " permission missing...\n(Review https://github.com/GoogleCloudPlatform/rad-lab/tree/main/modules/" + module_name + "#iam-permissions-prerequisites for more details)\n" + Style.RESET_ALL)
else:
pass
if rolefound == False:
sys.exit(Fore.RED + "\nError Occured - RADLAB MODULE PERMISSION ISSUE | " + role + " permission missing...\n(Review https://github.com/GoogleCloudPlatform/rad-lab/tree/main/modules/" + module_name + "#iam-permissions-prerequisites for more details)\n" + Style.RESET_ALL)
if projiam == True:
print(Fore.GREEN + '\nRADLAB MODULE (' + module_name + ')- Project Permission check passed' + Style.RESET_ALL)
# Check Org level permissions
if len(orgroles) != 0:
# print("Org Roles to check:")
# print(orgroles)
request = service.projects().get(name='projects/' + projid)
response = request.execute()
if 'parent' in response.keys():
# print("/*************** ORG IAM POLICY *************/")
org = findorg(response['parent'])
request2 = service.organizations().getIamPolicy(resource=org)
response2 = request2.execute()
# pprint(response2)
orgiam = True
for role in orgroles:
rolefound = False
for x in range(len(response2['bindings'])):
# print("ROLE --->")
# print(response2['bindings'][x]['role'])
# print("MEMBERS --->")
# print(response2['bindings'][x]['members'])
if (role == response2['bindings'][x]['role']):
rolefound = True
if ('user:' + currentusr not in response2['bindings'][x]['members']):
orgiam = False
sys.exit(Fore.RED + "\nError Occured - RADLAB MODULE (" + module_name + ") PERMISSION ISSUE | " + role + " permission missing...\n(Review https://github.com/GoogleCloudPlatform/rad-lab/tree/main/modules/" + module_name + "#iam-permissions-prerequisites for more details)\n" + Style.RESET_ALL)
else:
pass
if rolefound == False:
sys.exit(Fore.RED + "\nError Occured - RADLAB MODULE (" + module_name + ") PERMISSION ISSUE | " + role + " permission missing...\n(Review https://github.com/GoogleCloudPlatform/rad-lab/tree/main/modules/" + module_name + "#iam-permissions-prerequisites for more details)\n" + Style.RESET_ALL)
if orgiam == True:
print(Fore.GREEN + '\nRADLAB MODULE (' + module_name + ') - Organization Permission check passed' + Style.RESET_ALL)
else:
print(Fore.YELLOW + '\nRADLAB LAUNCHER - Skipping Organization Permission check. No Organization associated with the project: ' + projid + Style.RESET_ALL)