trigger_first_build.py 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #
  2. # Copyright (c) Contributors to the Open 3D Engine Project.
  3. # For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. #
  5. # SPDX-License-Identifier: Apache-2.0 OR MIT
  6. #
  7. #
  8. import boto3
  9. import logging
  10. import json
  11. import os
  12. import requests
  13. from botocore.exceptions import ClientError
  14. from requests.adapters import HTTPAdapter
  15. from requests.packages.urllib3.util.retry import Retry
  16. from requests.exceptions import RetryError
  17. log = logging.getLogger(__name__)
  18. log.setLevel(logging.INFO)
  19. JENKINS_CREDENTIAL_STORE = os.environ['JENKINS_CREDENTIAL_STORE']
  20. JENKINS_ENDPOINT = os.environ['JENKINS_ENDPOINT']
  21. REGION = os.environ['REGION']
  22. def get_secret(secret_name):
  23. secrets = boto3.client(service_name='secretsmanager', region_name=REGION)
  24. try:
  25. response = secrets.get_secret_value(SecretId=secret_name)
  26. return json.loads(response['SecretString'])
  27. except ClientError as e:
  28. log.error(f'Unable to get secret value: {e}')
  29. return None
  30. def lambda_handler(event, context):
  31. event_record = event['Records'][0]
  32. log.info(f'Received Event: {event_record}')
  33. ref_prefix = "refs/heads/"
  34. branch_name = event_record['codecommit']['references'][0]['ref'][len(ref_prefix):]
  35. repo_name = event_record['eventSourceARN'].split(":")[-1]
  36. credentials = get_secret(JENKINS_CREDENTIAL_STORE)
  37. if credentials:
  38. retries = 3
  39. backoff = 30
  40. status_list = [404] # Retry if the branch doesn't exist yet and provide time for Jenkins to discover it.
  41. method_list = ['POST']
  42. retry_config = Retry(total=retries, backoff_factor=backoff, status_forcelist=status_list, allowed_methods=method_list)
  43. session = requests.Session()
  44. session.mount('https://', HTTPAdapter(max_retries=retry_config))
  45. encoded_branch_name = requests.utils.quote(branch_name, safe='')
  46. build_path = f'/job/{repo_name}/job/{encoded_branch_name}/build'
  47. jenkins_url = requests.compat.urljoin(JENKINS_ENDPOINT, build_path)
  48. try:
  49. response = session.post(jenkins_url, auth=(credentials['username'], credentials['apitoken']))
  50. if response.status_code == 201:
  51. log.info(f'Successfully triggered build on {repo_name}/{branch_name}')
  52. elif response.status_code == 400:
  53. log.info(f'Initial build already started for {repo_name}/{branch_name}. Parameters are already available.')
  54. else:
  55. log.error(f'Failed to start build on {repo_name}/{branch_name}. Status code: {response.status_code}')
  56. except RetryError as e:
  57. log.error(f'Pipeline for {repo_name}/{branch_name} does not exist in Jenkins: {e}')