"""Create Security Groups for Spinnaker Pipelines."""
import argparse
import configparser
import json
import logging
import os
import sys

from jinja2 import Environment, FileSystemLoader
import requests


class SpinnakerSecurityGroup:
    """Manipulate Spinnaker Security Groups."""

    def __init__(self):
        self.here = os.path.dirname(os.path.realpath(__file__))

        self.config = self.get_configs()

        self.gate_url = self.config['spinnaker']['gate_url']

        self.header = {'content-type': 'application/json'}

    def get_configs(self):
        """Get main configuration.

        Returns:
            configparser.ConfigParser object with configuration loaded.
        """
        config = configparser.ConfigParser()
        configpath = "{}/../../configs/spinnaker.conf".format(self.here)
        config.read(configpath)
        return config

    def get_template(self, template_name='', template_dict=None):
        """Get Jinja2 Template _template_name_.

        Args:
            template_name: Str of template name to retrieve.
            template_dict: Dict to use for template rendering.

        Returns:
            Dict of rendered JSON to send to Spinnaker.
        """
        templatedir = "{}/../../templates".format(self.here)
        jinja_env = Environment(loader=FileSystemLoader(templatedir))
        template = jinja_env.get_template(template_name)

        rendered_json = json.loads(template.render(**template_dict))
        return rendered_json

    def get_apps(self):
        """Gets all applications from spinnaker."""
        url = self.gate_url + "/applications"
        r = requests.get(url)
        if r.status_code == 200:
            self.apps = r.json()
        else:
            logging.error(r.text)
            sys.exit(1)


    def app_exists(self):
        """Checks to see if application already exists."""
        self.get_apps()
        for app in self.apps:
            if app['name'].lower() == self.appname.lower():
                logging.info('{} app already exists'.format(self.appname))
                return True
        logging.info('{} does not exist...creating'.format(self.appname))
        return False


    def create_security_group(self, appinfo=None):
        """Sends a POST to spinnaker to create a new application."""
        #setup class variables for processing
        self.appinfo = appinfo
        if appinfo:
            self.appname = appinfo['name']

        if not (self.app_exists()):
            url = "{}/applications/{}/tasks".format(self.gate_url, self.appname)
            jsondata = self.setup_appdata()
            r = requests.post(url, data=json.dumps(jsondata), headers=self.header)

            if r.status_code != 200:
                logging.error("Failed to create app: {}".format(r.text))
                sys.exit(1)

            logging.info("Successfully created {} application".format(self.appname))
            return


def main():
    """Run newer stuffs."""
    parser = argparse.ArgumentParser()
    parser.add_argument("--name",
                        help="The application name to create",
                        required=True)
    parser.add_argument("--region",
                        help="The application name to create",
                        required=True)
    parser.add_argument("--vpc",
                        help="The application name to create",
                        required=True)
    parser.add_argument("--environment",
                        help="The application name to create",
                        required=True)
    parser.add_argument("--subnet",
                        help="The application name to create",
                        required=True)

    args = parser.parse_args()

    logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)

    #Dictionary containing application info. This is passed to the class for processing
    appinfo = {'name': args.name,
               'vpc': args.vpc,
               'region': args.region,
               'environment': args.environment,
               'subnet': args.subnet, }

    spinnakerapps = SpinnakerSecurityGroup()
    sg_json = spinnakerapps.get_template(
        template_name='securitygroup_template.json',
        template_dict=appinfo)
    print('SG JSON:\n', sg_json)
    # spinnakerapps.create_security_group(appinfo=appinfo)


if __name__ == "__main__":
    main()

@@ -294,32 +294,80 @@
 __init__(self):%0A
+        self.log = logging.getLogger(__name__)%0A%0A
         self.her
@@ -3021,24 +3021,103 @@
  stuffs.%22%22%22%0A
+    logging.basicConfig(format='%25(asctime)s %25(message)s', level=logging.INFO)%0A%0A
     parser =
@@ -3870,87 +3870,8 @@
 ()%0A%0A
-    logging.basicConfig(format='%25(asctime)s %25(message)s', level=logging.INFO)%0A%0A
     

Use Class logger