Esempio n. 1
0
File: tests.py Progetto: atsaki/cs
    def test_env_vars(self):
        with env(CLOUDSTACK_KEY='test key from env',
                 CLOUDSTACK_SECRET='test secret from env',
                 CLOUDSTACK_ENDPOINT='https://api.example.com/from-env'):
            conf = read_config()
            self.assertEqual(conf, {
                'key': 'test key from env',
                'secret': 'test secret from env',
                'endpoint': 'https://api.example.com/from-env',
                'method': 'get',
                'timeout': '10',
            })

        with env(CLOUDSTACK_KEY='test key from env',
                 CLOUDSTACK_SECRET='test secret from env',
                 CLOUDSTACK_ENDPOINT='https://api.example.com/from-env',
                 CLOUDSTACK_METHOD='post',
                 CLOUDSTACK_TIMEOUT='99'):
            conf = read_config()
            self.assertEqual(conf, {
                'key': 'test key from env',
                'secret': 'test secret from env',
                'endpoint': 'https://api.example.com/from-env',
                'method': 'post',
                'timeout': '99',
            })
Esempio n. 2
0
File: tests.py Progetto: exoscale/cs
 def test_env_var_combined_with_dir_config(self):
     with open('/tmp/cloudstack.ini', 'w') as f:
         f.write('[hanibal]\n'
                 'endpoint = https://api.example.com/from-file\n'
                 'key = test key from file\n'
                 'secret = secret from file\n'
                 'theme = monokai\n'
                 'other = please ignore me\n'
                 'timeout = 50')
         self.addCleanup(partial(os.remove, '/tmp/cloudstack.ini'))
     # Secret gets read from env var
     with env(CLOUDSTACK_ENDPOINT='https://api.example.com/from-env',
              CLOUDSTACK_KEY='test key from env',
              CLOUDSTACK_SECRET='test secret from env',
              CLOUDSTACK_REGION='hanibal',
              CLOUDSTACK_DANGEROUS_NO_TLS_VERIFY='1',
              CLOUDSTACK_OVERRIDES='endpoint,secret'), cwd('/tmp'):
         conf = read_config()
         self.assertEqual({
             'endpoint': 'https://api.example.com/from-env',
             'key': 'test key from file',
             'secret': 'test secret from env',
             'expiration': 600,
             'theme': 'monokai',
             'timeout': '50',
             'trace': None,
             'poll_interval': 2.0,
             'name': 'hanibal',
             'poll_interval': 2.0,
             'verify': None,
             'dangerous_no_tls_verify': True,
             'retry': 0,
             'method': 'get',
             'cert': None,
         }, conf)
Esempio n. 3
0
    def __init__(self):

        parser = argparse.ArgumentParser()
        parser.add_argument('--host')
        parser.add_argument('--list', action='store_true')
        parser.add_argument('--project')

        options = parser.parse_args()
        try:
            self.cs = CloudStack(**read_config())
        except CloudStackException as e:
            print("Error: Could not connect to CloudStack API", file=sys.stderr)

        project_id = ''
        if options.project:
            project_id = self.get_project_id(options.project)

        if options.host:
            data = self.get_host(options.host)
            print(json.dumps(data, indent=2))

        elif options.list:
            data = self.get_list()
            print(json.dumps(data, indent=2))
        else:
            print("usage: --list | --host <hostname> [--project <project>]",
                  file=sys.stderr)
            sys.exit(1)
Esempio n. 4
0
File: tests.py Progetto: exoscale/cs
    def test_env_vars(self):
        with env(CLOUDSTACK_KEY='test key from env',
                 CLOUDSTACK_SECRET='test secret from env',
                 CLOUDSTACK_ENDPOINT='https://api.example.com/from-env'):
            conf = read_config()
            self.assertEqual({
                'key': 'test key from env',
                'secret': 'test secret from env',
                'endpoint': 'https://api.example.com/from-env',
                'expiration': 600,
                'method': 'get',
                'trace': None,
                'timeout': 10,
                'poll_interval': 2.0,
                'verify': None,
                'dangerous_no_tls_verify': False,
                'cert': None,
                'name': None,
                'retry': 0,
            }, conf)

        with env(CLOUDSTACK_KEY='test key from env',
                 CLOUDSTACK_SECRET='test secret from env',
                 CLOUDSTACK_ENDPOINT='https://api.example.com/from-env',
                 CLOUDSTACK_METHOD='post',
                 CLOUDSTACK_TIMEOUT='99',
                 CLOUDSTACK_RETRY='5',
                 CLOUDSTACK_VERIFY='/path/to/ca.pem',
                 CLOUDSTACK_CERT='/path/to/cert.pem'):
            conf = read_config()
            self.assertEqual({
                'key': 'test key from env',
                'secret': 'test secret from env',
                'endpoint': 'https://api.example.com/from-env',
                'expiration': 600,
                'method': 'post',
                'timeout': '99',
                'trace': None,
                'poll_interval': 2.0,
                'verify': '/path/to/ca.pem',
                'cert': '/path/to/cert.pem',
                'dangerous_no_tls_verify': False,
                'name': None,
                'retry': '5',
            }, conf)
Esempio n. 5
0
    def __init__(self):
        parser = argparse.ArgumentParser()
        parser.add_argument('--host')
        parser.add_argument('--list', action='store_true')

        options = parser.parse_args()
        try:
            self.cs = CloudStack(**read_config())
        except CloudStackException, e:
            print >> sys.stderr, "Error: Could not connect to CloudStack API"
Esempio n. 6
0
 def test_env_vars(self):
     with env(CLOUDSTACK_KEY='test key from env',
              CLOUDSTACK_SECRET='test secret from env',
              CLOUDSTACK_ENDPOINT='https://api.example.com/from-env'):
         conf = read_config()
         self.assertEqual(conf, {
             'key': 'test key from env',
             'secret': 'test secret from env',
             'endpoint': 'https://api.example.com/from-env',
         })
    def _connect(self):
        api_key = self.module.params.get("api_key")
        api_secret = self.module.params.get("secret_key")
        api_url = self.module.params.get("api_url")
        api_http_method = self.module.params.get("api_http_method")
        api_timeout = self.module.params.get("api_timeout")

        if api_key and api_secret and api_url:
            self.cs = CloudStack(
                endpoint=api_url, key=api_key, secret=api_secret, timeout=api_timeout, method=api_http_method
            )
        else:
            self.cs = CloudStack(**read_config())
Esempio n. 8
0
    def test_current_dir_config(self):
        with open('/tmp/cloudstack.ini', 'w') as f:
            f.write('[cloudstack]\n'
                    'endpoint = https://api.example.com/from-file\n'
                    'key = test key from file\n'
                    'secret = test secret from file')
            self.addCleanup(partial(os.remove, '/tmp/cloudstack.ini'))

        with cwd('/tmp'):
            conf = read_config()
            self.assertEqual(dict(conf), {
                'endpoint': 'https://api.example.com/from-file',
                'key': 'test key from file',
                'secret': 'test secret from file',
            })
    def _connect(self):
        api_key = self.module.params.get('api_key')
        api_secret = self.module.params.get('secret_key')
        api_url = self.module.params.get('api_url')
        api_http_method = self.module.params.get('api_http_method')

        if api_key and api_secret and api_url:
            self.cs = CloudStack(
                endpoint=api_url,
                key=api_key,
                secret=api_secret,
                method=api_http_method
                )
        else:
            self.cs = CloudStack(**read_config())
Esempio n. 10
0
    def _connect(self):
        api_key = self.module.params.get('api_key')
        api_secret = self.module.params.get('secret_key')
        api_url = self.module.params.get('api_url')
        api_http_method = self.module.params.get('api_http_method')
        api_timeout = self.module.params.get('api_timeout')

        if api_key and api_secret and api_url:
            self.cs = CloudStack(endpoint=api_url,
                                 key=api_key,
                                 secret=api_secret,
                                 timeout=api_timeout,
                                 method=api_http_method)
        else:
            api_region = self.module.params.get('api_region', 'cloudstack')
            self.cs = CloudStack(**read_config(api_region))
Esempio n. 11
0
    def test_current_dir_config(self):
        with open('/tmp/cloudstack.ini', 'w') as f:
            f.write('[cloudstack]\n'
                    'endpoint = https://api.example.com/from-file\n'
                    'key = test key from file\n'
                    'secret = test secret from file\n'
                    'timeout = 50')
            self.addCleanup(partial(os.remove, '/tmp/cloudstack.ini'))

        with cwd('/tmp'):
            conf = read_config()
            self.assertEqual(dict(conf), {
                'endpoint': 'https://api.example.com/from-file',
                'key': 'test key from file',
                'secret': 'test secret from file',
                'timeout': '50',
            })
    def _connect(self):
        api_key = self.module.params.get('api_key')
        api_secret = self.module.params.get('secret_key')
        api_url = self.module.params.get('api_url')
        api_http_method = self.module.params.get('api_http_method')
        api_timeout = self.module.params.get('api_timeout')

        if api_key and api_secret and api_url:
            self.cs = CloudStack(
                endpoint=api_url,
                key=api_key,
                secret=api_secret,
                timeout=api_timeout,
                method=api_http_method)
        else:
            api_region = self.module.params.get('api_region', 'cloudstack')
            self.cs = CloudStack(**read_config(api_region))
Esempio n. 13
0
 def __init__(self,
              group,
              chaos_action,
              max_not_running=0,
              min_wait=10,
              max_wait=300):
     self.actions = [
         'reboot',
         'stop',
         'stop-wait-start',
         'no-action',
     ]
     self.cs = CloudStack(**read_config())
     self.max_not_running = max_not_running
     self.group = group
     self.chaos_action = chaos_action
     self.min_wait = min_wait
     self.max_wait = max_wait
Esempio n. 14
0
def register(profile, name, url, custom_data):

    # The API client
    # While to config file that we are parsing contains multiple regions, we want to use 1 exact match.
    # We select this by passing it's name to the read_config function.
    cs = CloudStack(**read_config(ini_group=profile))

    # To register a template we need to have an `ostypeid`, so we resolve that here
    # All templates are treated equally and use the same type so we just do a static lookup.
    ostype = cs.listOsTypes(description="Other PV Virtio-SCSI (64-bit)")
    ostype = ostype['ostype'][0]['id']

    # Prepare template tags
    # With this we can look up the template without depending on the ID.
    # custom_data is a base64 encoded json, so we first need to decode that.
    data = json.loads(base64.b64decode(custom_data))
    tags = []
    for k, v in data.items():
        item = {"key": k, "value": v}
        tags.append(item)

    # Register the template and keep it's ID so we can find it later
    template = cs.registerTemplate(format="qcow2",
                                   hypervisor="kvm",
                                   isdynamicallyscalable="true",
                                   isextractable="true",
                                   passwordEnabled="true",
                                   isfeatured="true",
                                   ispublic="true",
                                   zoneids="-1",
                                   ostypeid=ostype,
                                   displaytext=name,
                                   name=name,
                                   url=url)
    template = template['template'][0]['id']

    # Attach tags to template
    cs.createTags(
        resourceids=template,
        resourcetype="Template",
        tags=tags,
    )
    def __init__(self):

        parser = argparse.ArgumentParser()
        parser.add_argument('--host')
        parser.add_argument('--list', action='store_true')
        parser.add_argument(
            '--tag',
            help="Filter machines by a tag. Should be in the form key=value.")
        parser.add_argument('--project')
        parser.add_argument('--domain')

        options = parser.parse_args()
        try:
            self.cs = CloudStack(**read_config())
        except CloudStackException:
            print("Error: Could not connect to CloudStack API",
                  file=sys.stderr)

        domain_id = None
        if options.domain:
            domain_id = self.get_domain_id(options.domain)

        project_id = None
        if options.project:
            project_id = self.get_project_id(options.project, domain_id)

        if options.host:
            data = self.get_host(options.host, project_id, domain_id)
            print(json.dumps(data, indent=2))

        elif options.list:
            tags = dict()
            if options.tag:
                tags['tags[0].key'], tags['tags[0].value'] = options.tag.split(
                    '=')
            data = self.get_list(project_id, domain_id, **tags)
            print(json.dumps(data, indent=2))
        else:
            print(
                "usage: --list [--tag <tag>] | --host <hostname> [--project <project>] [--domain <domain_path>]",
                file=sys.stderr)
            sys.exit(1)
Esempio n. 16
0
File: tests.py Progetto: ujjwalsh/cs
    def test_current_dir_config(self):
        with open('/tmp/cloudstack.ini', 'w') as f:
            f.write('[cloudstack]\n'
                    'endpoint = https://api.example.com/from-file\n'
                    'key = test key from file\n'
                    'secret = test secret from file\n'
                    'dangerous_no_tls_verify = true\n'
                    'theme = monokai\n'
                    'other = please ignore me\n'
                    'header_x-custom-header1 = foo\n'
                    'header_x-custom-header2 = bar\n'
                    'timeout = 50')
            self.addCleanup(partial(os.remove, '/tmp/cloudstack.ini'))

        with cwd('/tmp'):
            conf = read_config()
            self.assertEqual(
                {
                    'endpoint': 'https://api.example.com/from-file',
                    'key': 'test key from file',
                    'secret': 'test secret from file',
                    'expiration': 600,
                    'theme': 'monokai',
                    'timeout': '50',
                    'trace': None,
                    'poll_interval': 2.0,
                    'name': 'cloudstack',
                    'poll_interval': 2.0,
                    'verify': None,
                    'dangerous_no_tls_verify': True,
                    'retry': 0,
                    'method': 'get',
                    'cert': None,
                    'headers': {
                        'x-custom-header1': 'foo',
                        'x-custom-header2': 'bar',
                    },
                }, conf)
Esempio n. 17
0
def main():
    inventory = {"_meta": {"hostvars": {}}}

    try:
        cs = CloudStack(**read_config())
        vms = cs.listVirtualMachines()["virtualmachine"]

        for vm in vms:
            name = vm["name"]
            groups = get_groups(vm)
            for group in groups:
                # test if group already present in inventory
                if group in inventory:
                    inventory[group]["hosts"].append(name)
                else:
                    inventory[group] = {"hosts": [name]}
            inventory["_meta"]["hostvars"][name] = get_hostvars(vm)

        print(to_json(inventory))
    except Exception as e:
        sys.stderr.write('%s\n' % e.message)
        sys.exit(1)
    sys.exit(0)
Esempio n. 18
0
File: tests.py Progetto: exoscale/cs
    def test_current_dir_config(self):
        with open('/tmp/cloudstack.ini', 'w') as f:
            f.write('[cloudstack]\n'
                    'endpoint = https://api.example.com/from-file\n'
                    'key = test key from file\n'
                    'secret = test secret from file\n'
                    'dangerous_no_tls_verify = true\n'
                    'theme = monokai\n'
                    'other = please ignore me\n'
                    'header_x-custom-header1 = foo\n'
                    'header_x-custom-header2 = bar\n'
                    'timeout = 50')
            self.addCleanup(partial(os.remove, '/tmp/cloudstack.ini'))

        with cwd('/tmp'):
            conf = read_config()
            self.assertEqual({
                'endpoint': 'https://api.example.com/from-file',
                'key': 'test key from file',
                'secret': 'test secret from file',
                'expiration': 600,
                'theme': 'monokai',
                'timeout': '50',
                'trace': None,
                'poll_interval': 2.0,
                'name': 'cloudstack',
                'poll_interval': 2.0,
                'verify': None,
                'dangerous_no_tls_verify': True,
                'retry': 0,
                'method': 'get',
                'cert': None,
                'headers': {
                    'x-custom-header1': 'foo',
                    'x-custom-header2': 'bar',
                },
            }, conf)
Esempio n. 19
0
    def __init__(self):

        parser = argparse.ArgumentParser()
        parser.add_argument('--host')
        parser.add_argument('--list', action='store_true')
        parser.add_argument('--tag', help="Filter machines by a tag. Should be in the form key=value.")
        parser.add_argument('--project')
        parser.add_argument('--domain')

        options = parser.parse_args()
        try:
            self.cs = CloudStack(**read_config())
        except CloudStackException:
            print("Error: Could not connect to CloudStack API", file=sys.stderr)

        domain_id = None
        if options.domain:
            domain_id = self.get_domain_id(options.domain)

        project_id = None
        if options.project:
            project_id = self.get_project_id(options.project, domain_id)

        if options.host:
            data = self.get_host(options.host, project_id, domain_id)
            print(json.dumps(data, indent=2))

        elif options.list:
            tags = dict()
            if options.tag:
                tags['tags[0].key'], tags['tags[0].value'] = options.tag.split('=')
            data = self.get_list(project_id, domain_id, **tags)
            print(json.dumps(data, indent=2))
        else:
            print("usage: --list [--tag <tag>] | --host <hostname> [--project <project>] [--domain <domain_path>]",
                  file=sys.stderr)
            sys.exit(1)
Esempio n. 20
0
    def get_api_config(self):
        api_region = self.module.params.get('api_region') or os.environ.get(
            'CLOUDSTACK_REGION')
        try:
            config = read_config(api_region)
        except KeyError:
            config = {}

        api_config = {
            'endpoint':
            self.module.params.get('api_url') or config.get('endpoint'),
            'key':
            self.module.params.get('api_key') or config.get('key'),
            'secret':
            self.module.params.get('api_secret') or config.get('secret'),
            'timeout':
            self.module.params.get('api_timeout') or config.get('timeout')
            or 10,
            'method':
            self.module.params.get('api_http_method') or config.get('method')
            or 'get',
            'verify':
            self.module.params.get('api_verify_ssl_cert')
            or config.get('verify'),
        }
        self.result.update({
            'api_region': api_region,
            'api_url': api_config['endpoint'],
            'api_key': api_config['key'],
            'api_timeout': int(api_config['timeout']),
            'api_http_method': api_config['method'],
            'api_verify_ssl_cert': api_config['verify'],
        })
        if not all(
            [api_config['endpoint'], api_config['key'], api_config['secret']]):
            self.fail_json(msg="Missing api credentials: can not authenticate")
        return api_config
Esempio n. 21
0
    def _connect(self):
        api_region = self.module.params.get('api_region') or os.environ.get('CLOUDSTACK_REGION')
        try:
            config = read_config(api_region)
        except KeyError:
            config = {}

        api_config = {
            'endpoint': self.module.params.get('api_url') or config.get('endpoint'),
            'key': self.module.params.get('api_key') or config.get('key'),
            'secret': self.module.params.get('api_secret') or config.get('secret'),
            'timeout': self.module.params.get('api_timeout') or config.get('timeout'),
            'method': self.module.params.get('api_http_method') or config.get('method'),
        }
        self.result.update({
            'api_region': api_region,
            'api_url': api_config['endpoint'],
            'api_key': api_config['key'],
            'api_timeout': api_config['timeout'],
            'api_http_method': api_config['method'],
        })
        if not all([api_config['endpoint'], api_config['key'], api_config['secret']]):
            self.fail_json(msg="Missing api credentials: can not authenticate")
        self.cs = CloudStack(**api_config)
Esempio n. 22
0
    def __init__(self):

        parser = argparse.ArgumentParser()
        parser.add_argument('--host')
        parser.add_argument('--list', action='store_true')
        parser.add_argument('--project')
        parser.add_argument('--domain')

        options = parser.parse_args()
        try:
            self.cs = CloudStack(**read_config())
        except CloudStackException as e:
            print("Error: Could not connect to CloudStack API",
                  file=sys.stderr)
            sys.exit(1)

        domain_id = None
        if options.domain:
            domain_id = self.get_domain_id(options.domain)

        project_id = None
        if options.project:
            project_id = self.get_project_id(options.project, domain_id)

        if options.host:
            data = self.get_host(options.host, project_id, domain_id)
            print(json.dumps(data, indent=2))

        elif options.list:
            data = self.get_list(project_id, domain_id)
            print(json.dumps(data, indent=2))
        else:
            print(
                "usage: --list | --host <hostname> [--project <project>] [--domain <domain_path>]",
                file=sys.stderr)
            sys.exit(1)
Esempio n. 23
0
    def _connect(self):
        api_region = self.module.params.get('api_region') or os.environ.get('CLOUDSTACK_REGION')
        try:
            config = read_config(api_region)
        except KeyError:
            config = {}

        api_config = {
            'endpoint': self.module.params.get('api_url') or config.get('endpoint'),
            'key': self.module.params.get('api_key') or config.get('key'),
            'secret': self.module.params.get('api_secret') or config.get('secret'),
            'timeout': self.module.params.get('api_timeout') or config.get('timeout'),
            'method': self.module.params.get('api_http_method') or config.get('method'),
        }
        self.result.update({
            'api_region': api_region,
            'api_url': api_config['endpoint'],
            'api_key': api_config['key'],
            'api_timeout': api_config['timeout'],
            'api_http_method': api_config['method'],
        })
        if not all([api_config['endpoint'], api_config['key'], api_config['secret']]):
            self.fail_json(msg="Missing api credentials: can not authenticate")
        self.cs = CloudStack(**api_config)
Esempio n. 24
0
File: tests.py Progetto: ujjwalsh/cs
 def test_env_var_combined_with_dir_config(self):
     with open('/tmp/cloudstack.ini', 'w') as f:
         f.write('[hanibal]\n'
                 'endpoint = https://api.example.com/from-file\n'
                 'key = test key from file\n'
                 'secret = secret from file\n'
                 'theme = monokai\n'
                 'other = please ignore me\n'
                 'timeout = 50')
         self.addCleanup(partial(os.remove, '/tmp/cloudstack.ini'))
     # Secret gets read from env var
     with env(CLOUDSTACK_ENDPOINT='https://api.example.com/from-env',
              CLOUDSTACK_KEY='test key from env',
              CLOUDSTACK_SECRET='test secret from env',
              CLOUDSTACK_REGION='hanibal',
              CLOUDSTACK_DANGEROUS_NO_TLS_VERIFY='1',
              CLOUDSTACK_OVERRIDES='endpoint,secret'), cwd('/tmp'):
         conf = read_config()
         self.assertEqual(
             {
                 'endpoint': 'https://api.example.com/from-env',
                 'key': 'test key from file',
                 'secret': 'test secret from env',
                 'expiration': 600,
                 'theme': 'monokai',
                 'timeout': '50',
                 'trace': None,
                 'poll_interval': 2.0,
                 'name': 'hanibal',
                 'poll_interval': 2.0,
                 'verify': None,
                 'dangerous_no_tls_verify': True,
                 'retry': 0,
                 'method': 'get',
                 'cert': None,
             }, conf)
def security_group(name):
    con = cs.CloudStack(**cs.read_config())
    log("Creating security group named '{}'".format(name))
    sg = con.createSecurityGroup(name=name)['securitygroup']
    # For standard SSH access
    log("Add rule for SSH tcp/22")
    con.authorizeSecurityGroupIngress(protocol="TCP",
                                      cidrlist="0.0.0.0/0",
                                      startport=22,
                                      endport=22,
                                      securitygroupid=sg['id'])
    # For Docker marchine acess
    log("Add rule for docker access tcp/2376")
    con.authorizeSecurityGroupIngress(protocol="TCP",
                                      cidrlist="0.0.0.0/0",
                                      startport=2376,
                                      endport=2376,
                                      securitygroupid=sg['id'])
    # For tomcat webapp access
    log("Add rule for tomcat access tcp/8080")
    con.authorizeSecurityGroupIngress(protocol="TCP",
                                      cidrlist="0.0.0.0/0",
                                      startport=8080,
                                      endport=8080,
                                      securitygroupid=sg['id'])
    # For rancher OS
    log("Add rule for rancher OS udp/500, udp/4500, tcp/9345, tcp/9346")
    con.authorizeSecurityGroupIngress(protocol="UDP",
                                      cidrlist="0.0.0.0/0",
                                      startport=500,
                                      endport=500,
                                      securitygroupid=sg['id'])
    # For rancher OS
    con.authorizeSecurityGroupIngress(protocol="UDP",
                                      cidrlist="0.0.0.0/0",
                                      startport=4500,
                                      endport=4500,
                                      securitygroupid=sg['id'])
    # For Rancher OS UI
    con.authorizeSecurityGroupIngress(protocol="TCP",
                                      cidrlist="0.0.0.0/0",
                                      startport=9345,
                                      endport=9345,
                                      securitygroupid=sg['id'])
    # For Rancher OS UI
    con.authorizeSecurityGroupIngress(protocol="TCP",
                                      cidrlist="0.0.0.0/0",
                                      startport=9346,
                                      endport=9346,
                                      securitygroupid=sg['id'])
    # For OpenVPN
    log("Add rule for OpenVPN access tcp/1194")
    con.authorizeSecurityGroupIngress(protocol="TCP",
                                      cidrlist="0.0.0.0/0",
                                      startport=1194,
                                      endport=1194,
                                      securitygroupid=sg['id'])
    # For OpenVPN ssh access to extract configuration
    log("Add rule for OpenVPN configuration access tcp/2222")
    con.authorizeSecurityGroupIngress(protocol="TCP",
                                      cidrlist="0.0.0.0/0",
                                      startport=2222,
                                      endport=2222,
                                      securitygroupid=sg['id'])
    # For HTTPS access for rancher
    log("Add rule for HTTPS traffic tcp/443")
    con.authorizeSecurityGroupIngress(protocol="TCP",
                                      cidrlist="0.0.0.0/0",
                                      startport=443,
                                      endport=443,
                                      securitygroupid=sg['id'])
Esempio n. 26
0
try:
    from cs import CloudStack, CloudStackException, read_config
except ImportError:
    print 'python library required: cs'
    print 'pip install <library>'
    sys.exit(1)

parser = argparse.ArgumentParser()

parser.add_argument('--project')
parser.add_argument('--zone')

args = parser.parse_args()

try:
    cs = CloudStack(**read_config())

    project_id = ''
    if args.project:
        projects = cs.listProjects(listall=True)
        if projects:
            for p in projects['project']:
                if p['name'] == args.project:
                    project_id = p['id']
                    break

    if not project_id:
        print "project %s not found" % args.project
        sys.exit(1)

    zone_id = ''
Esempio n. 27
0
def main():
    """ main :) """
    args = prepare_arguments()

    if args.set_limits and args.print_limits:
        print(
                'Please use only one of the options ' +
                '--print-limits --set-limits --disable-limits.')
        sys.exit(1)
    if not args.set_limits and not args.print_limits and \
            not args.disable_limits:
        print(
                'Please use one of the paramters ' +
                '--print-limits --set-limits or --disable-limits.')
        sys.exit(1)
    if args.disable_limits and not args.disable_list:
        print(
                'Please provide a list of limit types to disable.:\n' +
                'e.g --disable-list=\"1,2,4,7\"\n' +
                'Limit types are: \n' +
                '     0 - Instance. Number of instances a user can create.\n' +
                '     1 - IP. Number of public IP addresses.\n' +
                '     2 - Volume. Number of disk volumes.\n' +
                '     3 - Snapshot. Number of snapshots a user can create.\n' +
                '     4 - Template. Number of templates.\n' +
                '     6 - Network. Number of guest network.\n' +
                '     7 - VPC. Number of VPC a user can create.\n' +
                '     8 - CPU. Total number of CPU cores a user can use.\n' +
                '     9 - Memory. Total Memory (in MB) a user can use.\n' +
                '    10 - PrimaryStorage. Primary storage space (in GiB).\n' +
                '    11 - SecondaryStorage.')
        sys.exit(1)

    # Reads ~/.cloudstack.ini
    cs = CloudStack(**read_config())

    projects_container = cs.listProjects(listall=True)
    projects = projects_container["project"]
    if args.project_id:
        projects_filtered = list(
                filter(
                    lambda project: project['id'] == args.project_id,
                    projects))
        if projects_filtered == []:
            print(
                    f'Project id \"{args.project_id}\" is not valid, ' +
                    'please choose a UUID from below:')
            for project in sorted(projects, key=lambda key: (
                    key["domain"],
                    key["name"])):
                print(
                    f'Domain: {project["domain"]}; ' +
                    f'Project Name: {project["name"]}; ' +
                    f'Project UUID: {project["id"]}')
            sys.exit(1)
    else:
        projects_filtered = projects

    project = projects_filtered

    if args.print_limits:
        print_limits(projects_filtered, args.outputfile)
    if args.set_limits:
        limit_matrix = prepare_limit_matrix(args.inputfile)
        set_limits(cs, projects_filtered, limit_matrix)
    if args.disable_limits:
        limit_matrix = prepare_disable_matrix(
                projects_filtered,
                args.disable_list)
        set_limits(cs, projects_filtered, limit_matrix)
Esempio n. 28
0
try:
    from cs import CloudStack, CloudStackException, read_config
except ImportError:
    print 'python library required: cs'
    print 'pip install <library>'
    sys.exit(1)

parser = argparse.ArgumentParser()

parser.add_argument('--project')
parser.add_argument('--zone')

args = parser.parse_args()

try:
    cs = CloudStack(**read_config())

    project_id = ''
    if args.project:
        projects = cs.listProjects(listall=True)
        if projects:
            for p in projects['project']:
                if p['name'] == args.project:
                    project_id = p['id']
                    break

    if not project_id:
        print "project %s not found" % args.project
        sys.exit(1)

    zone_id = ''
def main():
    module = AnsibleModule(
        argument_spec = dict(
            name = dict(default=None),
            display_name = dict(default=None),
            group = dict(default=None),
            state = dict(choices=['created', 'started', 'running', 'booted', 'stopped', 'halted', 'restarted', 'rebooted', 'present', 'absent', 'destroyed', 'expunged'], default='present'),
            service_offering = dict(default=None),
            template = dict(default=None),
            iso = dict(default=None),
            networks = dict(type='list', default=None),
            disk_offering = dict(default=None),
            disk_size = dict(default=None),
            hypervisor = dict(default=None),
            security_groups = dict(type='list', aliases= [ 'security_group' ], default=None),
            affinity_groups = dict(type='list', aliases= [ 'affinity_group' ], default=None),
            project = dict(default=None),
            user_data = dict(default=None),
            zone = dict(default=None),
            poll_async = dict(choices=BOOLEANS, default=True),
            ssh_key = dict(default=None),
            api_key = dict(default=None),
            api_secret = dict(default=None),
            api_url = dict(default=None),
            api_http_method = dict(default='get'),
        ),
        required_one_of = (
            ['name', 'display_name'],
        ),
        supports_check_mode=True
    )

    result = {}
    state = module.params.get('state')
    result['changed'] = False

    try:
        api_key = module.params.get('api_key')
        api_secret = module.params.get('api_secret')
        api_url = module.params.get('api_url')
        api_http_method = module.params.get('api_http_method')

        if api_key and api_secret and api_url:
            cs = CloudStack(
                endpoint=api_url,
                key=api_key,
                secret=api_secret,
                method=api_http_method
                )
        else:
            cs = CloudStack(**read_config())

        project_id = get_project_id(module, cs)
        vm = get_vm(module, cs, project_id)

        if state in ['absent', 'destroyed']:
            (result, vm) = remove_vm(module, cs, result, vm)

        elif state in ['expunged']:
            (result, vm) = expunge_vm(module, cs, result, vm)

        elif state in ['present', 'created']:
            if not vm:
                (result, vm) = create_vm(module, cs, result, vm, project_id)
            else:
                (result, vm) = scale_vm(module, cs, result, vm)

        elif state in ['stopped', 'halted']:
            (result, vm) = stop_vm(module, cs, result, vm)

        elif state in ['started', 'running', 'booted']:
            (result, vm) = start_vm(module, cs, result, vm)

        elif state in ['restarted', 'rebooted']:
            (result, vm) = restart_vm(module, cs, result, vm)

        if vm:

            if 'state' in vm and vm['state'] == 'Error':
                module.fail_json(msg="Virtual machine named '%s' in error state." % module.params.get('name'))

            if 'id' in vm:
                result['id'] = vm['id']

            if 'name' in vm:
                result['name'] = vm['name']

            if 'displayname' in vm:
                result['display_name'] = vm['displayname']

            if 'group' in vm:
                result['group'] = vm['group']

            if 'password' in vm:
                result['password'] = vm['password']

            if 'serviceofferingname' in vm:
                result['service_offering'] = vm['serviceofferingname']

            if 'zonename' in vm:
                result['zone'] = vm['zonename']

            if 'templatename' in vm:
                result['template'] = vm['templatename']

            if 'isoname' in vm:
                result['iso'] = vm['isoname']

            if 'created' in vm:
                result['created'] = vm['created']

            if 'state' in vm:
                result['vm_state'] = vm['state']

            if 'tags' in vm:
                tags = {}
                for tag in vm['tags']:
                    key = tag['key']
                    value = tag['value']
                    tags[key] = value
                result['tags'] = tags

            if 'nic' in vm:
                for nic in vm['nic']:
                    if nic['isdefault']:
                        result['default_ip'] = nic['ipaddress']
                result['nic'] = vm['nic']

    except CloudStackException, e:
        module.fail_json(msg='CloudStackException: %s' % str(e))