Python запуск деплоя в opsworks или рецeптов

Скрипт запускается с параметрами script_name.py -h покажет справку по параметрам

#!/usr/bin/python
# by Eduard
import boto3
import time
import sys
import argparse

parser = argparse.ArgumentParser(description="Script to start deploy Opsworks.")
parser.add_argument('-s', '--stack', help='Opsworks Stack Name.')
parser.add_argument('-a', '--app', help='Application name.')
parser.add_argument('-r', '--repo', help='Repository URL.')
parser.add_argument('-aws', '--aws-profile', help='AWS Profile in ~/.aws/cresentials.')
parser.add_argument('-d', '--deploy', help='Deploy command -d deploy -execute_recipes.')
parser.add_argument('-rec', '--recipes', nargs='+', type=str, help='Recipes list separated by a space.')
parser.add_argument('-c', '--comment', type = str, help='Comment', default="Run from Jenkins")

args = parser.parse_args()

profname = args.aws_profile
boto3.setup_default_session(profile_name=profname)

if (not args.aws_profile) or (not args.stack) or (not args.deploy):
  print("Error arguments!!!")

client = boto3.client('opsworks')

response = client.describe_stacks()
for i in response['Stacks']:
    if i["Name"] == args.stack:
        stack_id = i["StackId"]

if args.app and args.repo:
  response_app = client.describe_apps(StackId=stack_id)
  app_id = response_app["Apps"][0]["AppId"]
  response_app["Apps"][0]["AppSource"]["Url"] = args.repo
  response = client.update_app(
             AppId=app_id,
             AppSource={
                'Url': args.repo
             })

  print("Stack ID: %s" % stack_id)
  print("App ID: %s" % app_id)

  if response["ResponseMetadata"]["HTTPStatusCode"] == 200:
      print("Repo URL updated: %s" % args.repo)

def wait_for_deployment(deployment_id):
    print('Waiting for deployment %s to complete' % deployment_id)
    while True:
        result = client.describe_deployments(DeploymentIds=[deployment_id])
        data = result['Deployments'][0]
        if data['Status'] == 'running':
            sys.stdout.write('.')
        elif data['Status'] == 'successful':
            print('Done %s' % deployment_id)
            return
        elif data['Status'] == 'failed':
            print('Failed %s' % deployment_id)
            raise Exception('Deployment failed')
        else:
            raise Exception('Unknown deployment stauts: %s' % data['Status'])
        sys.stdout.flush()
        time.sleep(3)

if args.deploy == "deploy":
  if (not args.app) or (not args.repo):
    print("Error arguments!!!")
    exit(1)
  result = client.create_deployment(StackId=stack_id, Command={"Name":"deploy"}, AppId=app_id)


if args.deploy == "execute_recipes":
  if args.recipes:
    result = client.create_deployment(StackId=stack_id, Command={"Name":"execute_recipes", "Args": {"recipes":args.recipes}}, Comment=args.comment)
  else:
    print("No recipes for run!!!")
    exit(1)
#print('Deploy %s' % result)
wait_for_deployment(result['DeploymentId'])

 

Python

Related Articles

0 Comment

Leave a Comment

Ваш адрес email не будет опубликован.