in terraform-modules/cloud-functions/src/provide-billing-permissions/main.py [0:0]
def update_permissions(event, context):
import os
"""Background Cloud Function to be triggered by Cloud Storage.
Args:
event (dict): The dictionary with data specific to this type of event.
The `data` field contains a description of the event in
the Cloud Storage `object` format described here:
https://cloud.google.com/storage/docs/json_api/v1/objects#resource
context (google.cloud.functions.Context): Metadata of triggering event.
Returns:
None; the function reads the service accounts from blob and grant them IAM roles
"""
sa_list = []
validated_sa_list = []
roles = ['roles/billing.user']
billing_acc_secret_name = 'gcp-billingac'
project_id = os.environ['GCP_PROJECT']
secret_project = 'YOUR_SECRET_PROJECT_ID'
print('Printing the payload.\n')
print('EVENT:' , event)
print('Event ID:' , context.event_id)
print('Event type:', context.event_type)
print('Bucket:', event['bucket'])
print('File:', event['name'])
print('Metageneration:', event['metageneration'])
print('Created:', event['timeCreated'])
print('Updated:', event['updated'])
bucket_name = event['bucket']
blob_name = event['name']
print('Fetching Service Accounts from the file',bucket_name + '/' + blob_name)
try:
sa_list = fetch_sa_from_file(bucket_name,blob_name)
except Exception as e:
print('Unable to fetch Service Accounts from ' + bucket_name + '/' + blob_name + '.')
exception_handler('fetch_sa_from_file', str(e))
print('Fetch the billing account.\n')
try:
billing_ac = get_billing_ac(billing_acc_secret_name,secret_project)
print('The billing account is \n', billing_ac)
except Exception as e:
print('Unable to fetch billing account')
exception_handler('get_billing_ac', str(e))
print('Fetching policy of the billing account.\n')
try:
policy = get_policy(billing_ac)
print('The policy is \n', policy)
except Exception as e:
print('Unable to fetch policy of the billing account ' + billing_ac)
exception_handler('get_policy', str(e))
for sa in sa_list:
for role in roles:
try:
print('Adding role ' + role + ' to the member ' + sa)
policy = generate_modified_policy(policy,role,sa)
except Exception as e:
print('Unable to create modified policy')
exception_handler('generate_modified_policy', str(e))
print('Generated policy is ', policy)
print('Setting the generated policy so the Service Accounts get the required roles.\n')
try:
policy = set_policy(billing_ac,policy)
except Exception as e:
print('Unable to set the policy \n.')
exception_handler('set_policy', str(e))
print('Successfully set the policy ', policy)