├── Makefile ├── tests ├── keystone_service.py └── test_keystone_service.py ├── .gitignore ├── README.md ├── nova_manage ├── cinder_manage ├── heat_manage ├── keystone_manage ├── cinder_volume_types ├── glance_manage ├── glance ├── nova_quota ├── nova_aggregate ├── neutron_router ├── cinder_qos ├── neutron_router_gateway ├── nova_flavor ├── neutron_router_interface ├── neutron_network ├── neutron_floating_ip ├── keystone_service ├── neutron_subnet ├── neutron_sec_group └── LICENSE /Makefile: -------------------------------------------------------------------------------- 1 | test: 2 | nosetests 3 | -------------------------------------------------------------------------------- /tests/keystone_service.py: -------------------------------------------------------------------------------- 1 | ../keystone_service -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.py[cod] 2 | 3 | # C extensions 4 | *.so 5 | 6 | # Packages 7 | *.egg 8 | *.egg-info 9 | dist 10 | build 11 | eggs 12 | parts 13 | bin 14 | var 15 | sdist 16 | develop-eggs 17 | .installed.cfg 18 | lib 19 | lib64 20 | 21 | # Installer logs 22 | pip-log.txt 23 | 24 | # Unit test / coverage reports 25 | .coverage 26 | .tox 27 | nosetests.xml 28 | 29 | # Translations 30 | *.mo 31 | 32 | # Mr Developer 33 | .mr.developer.cfg 34 | .project 35 | .pydevproject 36 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ansible modules for managing OpenStack 2 | 3 | These are additional, unofficial Ansible modules for managing OpenStack. 4 | 5 | These are a dependency of the [openstack-ansible][1] repo for doing a test deployment of OpenStack into virtual machines managed by vagrant. 6 | 7 | To use this, add this directory to to the ANSIBLE_LIBRARY environment variable, or symlink this directory to ./library relative to the playbook that uses it. 8 | 9 | [1]: http://github.com/lorin/openstack-ansible 10 | 11 | ## keystone_manage 12 | 13 | Initialize the keystone database: 14 | 15 | keystone_manage: action=db_sync 16 | 17 | This is the equivalent of: 18 | 19 | # keystone-manage db_sync 20 | 21 | 22 | ## keystone_user 23 | 24 | Manage users, tenants, and roles 25 | 26 | Create a tenant 27 | 28 | keystone_user: token=$admin_token tenant=demo tenant_description="Default Tenant" 29 | 30 | Create a user 31 | 32 | keystone_user: token=$admin_token user=admin tenant=demo password=secrete 33 | 34 | Create and apply a role: 35 | 36 | keystone_user: token=$admin_token role=admin user=admin tenant=demo 37 | 38 | ## keystone_service 39 | 40 | Manage services and endpoints 41 | 42 | keystone_service: token=$admin_token name=keystone type=identity description="Identity Service" public_url="http://192.168.206.130:5000/v2.0" internal_url="http://192.168.206.130:5000/v2.0" admin_url="http://192.168.206.130:35357/v2.0" 43 | 44 | You can use `url` as an alias for `public_url`. If you don't specify internal and admin urls, they will default to the same value of public url. For example: 45 | 46 | keystone_service: token=$admin_token name=nova type=compute description="Compute Service" url=http://192.168.206.130:8774/v2/%(tenant_id)s 47 | 48 | 49 | ## glance_manage 50 | 51 | Initialize the glance database: 52 | 53 | glance_manage: action=db_sync 54 | 55 | This is the (idempotent) equivalent of: 56 | 57 | # glance-manage version_control 0 58 | # glance-manage db_sync 59 | 60 | 61 | ## glance 62 | 63 | Add images 64 | 65 | glance: name=cirros file=/tmp/cirros-0.3.0-x86_64-disk.img disk_format=qcow2 is_public=true user=admin tenant=demo password=secrete region=RegionOne auth_url=http://192.168.206.130:5000/v2.0 66 | 67 | ## Not yet supported 68 | - Disabled tenants 69 | - Deleting users 70 | - Deleting roles 71 | - Deleting services 72 | - Deleting endpoints 73 | - Deleting images 74 | - Updating tenants 75 | - Updating users 76 | - Updating services 77 | - Updating endpoints 78 | - Multiple endpoints per service 79 | - Updating images 80 | 81 | 82 | ## Will probably never be supported 83 | - Non-unique names for tenants, users, roles, services and images. 84 | 85 | -------------------------------------------------------------------------------- /nova_manage: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | DOCUMENTATION = ''' 5 | --- 6 | module: nova_manage 7 | short_description: Initialize OpenStack Compute (nova) database 8 | description: Create the tables for the database backend used by nova 9 | options: 10 | action: 11 | description: 12 | - action to perform. Currently only dbsync is supported 13 | required: true 14 | requirements: [ nova ] 15 | ''' 16 | 17 | EXAMPLES = ''' 18 | nova_manage: action=dbsync 19 | ''' 20 | 21 | import subprocess 22 | 23 | try: 24 | from nova.db.sqlalchemy import migration 25 | from nova import config 26 | except ImportError: 27 | nova_found = False 28 | else: 29 | nova_found = True 30 | 31 | 32 | def load_config_file(): 33 | config.parse_args([]) 34 | 35 | 36 | def will_db_change(): 37 | """ Check if the database version will change after the sync. 38 | 39 | """ 40 | # Load the config file options 41 | current_version = migration.db_version() 42 | repository = migration._find_migrate_repo() 43 | repo_version = repository.latest 44 | return current_version != repo_version 45 | 46 | 47 | def do_dbsync(): 48 | """Do the dbsync. Returns (returncode, stdout, stderr)""" 49 | # We call nova-manage db_sync on the shell rather than trying to 50 | # do this in Python since we have no guarantees about changes to the 51 | # internals. 52 | args = ['nova-manage', 'db', 'sync'] 53 | 54 | call = subprocess.Popen(args, shell=False, 55 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) 56 | out, err = call.communicate() 57 | return (call.returncode, out, err) 58 | 59 | 60 | def main(): 61 | 62 | module = AnsibleModule( 63 | argument_spec=dict( 64 | action=dict(required=True), 65 | ), 66 | supports_check_mode=True 67 | ) 68 | 69 | if not nova_found: 70 | module.fail_json(msg="nova package could not be found") 71 | 72 | action = module.params['action'] 73 | 74 | if action not in ['dbsync', 'db_sync']: 75 | module.fail_json(msg="Only supported action is 'dbsync'") 76 | 77 | load_config_file() 78 | 79 | changed = will_db_change() 80 | if module.check_mode: 81 | module.exit_json(changed=changed) 82 | 83 | (res, stdout, stderr) = do_dbsync() 84 | 85 | if res == 0: 86 | module.exit_json(changed=changed, stdout=stdout, stderr=stderr) 87 | else: 88 | module.fail_json(msg="nova-manage returned non-zero value: %d" % res, 89 | stdout=stdout, stderr=stderr) 90 | 91 | # this is magic, see lib/ansible/module_common.py 92 | #<> 93 | main() 94 | -------------------------------------------------------------------------------- /cinder_manage: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | DOCUMENTATION = ''' 5 | --- 6 | module: cinder_manage 7 | short_description: Initialize OpenStack Block Storage (cinder) database 8 | description: Create the tables for the database backend used by cinder 9 | options: 10 | action: 11 | description: 12 | - action to perform. Currently only dbysnc is supported 13 | required: true 14 | conf: 15 | description: 16 | - path to cinder config file. 17 | required: false 18 | default: /etc/cinder/cinder.conf 19 | requirements: [ cinder ] 20 | author: Lorin Hochstein 21 | ''' 22 | 23 | EXAMPLES = ''' 24 | cinder_manage: action=dbsync 25 | ''' 26 | 27 | import subprocess 28 | 29 | cinder_found = True 30 | try: 31 | from cinder.db.sqlalchemy import migration 32 | try: 33 | from cinder import flags 34 | FLAGS = flags.FLAGS 35 | except ImportError: 36 | # Starting with icehouse 37 | import cinder.common.config 38 | FLAGS = cinder.common.config.CONF 39 | except ImportError: 40 | cinder_found = False 41 | 42 | 43 | def load_config_file(conf): 44 | FLAGS(args=[], project='cinder', default_config_files=[conf]) 45 | 46 | def will_db_change(): 47 | """ Check if the database version will change after the sync. 48 | 49 | """ 50 | # Load the config file options 51 | current_version = migration.db_version() 52 | repository = migration._find_migrate_repo() 53 | repo_version = repository.latest 54 | return current_version != repo_version 55 | 56 | 57 | def do_dbsync(): 58 | """Do the dbsync. Returns (returncode, stdout, stderr)""" 59 | # We call cinder-manage db_sync on the shell rather than trying to 60 | # do this in Python since we have no guarantees about changes to the 61 | # internals. 62 | args = ['cinder-manage', 'db', 'sync'] 63 | 64 | call = subprocess.Popen(args, shell=False, 65 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) 66 | out, err = call.communicate() 67 | return (call.returncode, out, err) 68 | 69 | 70 | def main(): 71 | 72 | module = AnsibleModule( 73 | argument_spec=dict( 74 | action=dict(required=True), 75 | conf=dict(required=False, default="/etc/cinder/cinder.conf") 76 | ), 77 | supports_check_mode=True 78 | ) 79 | 80 | if not cinder_found: 81 | module.fail_json(msg="cinder package could not be found") 82 | 83 | action = module.params['action'] 84 | conf = module.params['conf'] 85 | 86 | if action not in ['dbsync', 'db_sync']: 87 | module.fail_json(msg="Only supported action is 'dbsync'") 88 | 89 | load_config_file(conf) 90 | 91 | changed = will_db_change() 92 | if module.check_mode: 93 | module.exit_json(changed=changed) 94 | 95 | (res, stdout, stderr) = do_dbsync() 96 | 97 | if res == 0: 98 | module.exit_json(changed=changed, stdout=stdout, stderr=stderr) 99 | else: 100 | module.fail_json(msg="cinder-manage returned non-zero value: %d" % res, 101 | stdout=stdout, stderr=stderr) 102 | 103 | # this is magic, see lib/ansible/module_common.py 104 | #<> 105 | main() 106 | -------------------------------------------------------------------------------- /heat_manage: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | DOCUMENTATION = ''' 5 | --- 6 | module: heat_manage 7 | short_description: Initialize Orchestration (heat) database 8 | description: Create the tables for the database backend used by heat 9 | options: 10 | action: 11 | description: 12 | - action to perform. Currently only dbysnc is supported 13 | required: true 14 | conf: 15 | description: 16 | - path to keystone config file. 17 | required: false 18 | default: /etc/heat/heat.conf 19 | requirements: [ python-heatclient ] 20 | author: Gauvain Pocentek 21 | ''' 22 | 23 | EXAMPLES = ''' 24 | heat_manage: action=dbsync 25 | ''' 26 | 27 | import subprocess 28 | 29 | try: 30 | import heat 31 | from heat.db.sqlalchemy import migration 32 | from migrate.versioning import api as versioning_api 33 | from heat.db import api 34 | from oslo.config import cfg 35 | except ImportError: 36 | heat_found = False 37 | else: 38 | heat_found = True 39 | 40 | 41 | def will_db_change(conf): 42 | """ Check if the database version will change after the sync. 43 | 44 | conf is the path to the heat config file 45 | 46 | """ 47 | # Load the config file options 48 | cfg.CONF(project='heat', default_config_files=[conf]) 49 | try: 50 | current_version = migration.db_version() 51 | except TypeError: # juno 52 | current_version = api.db_version(api.get_engine()) 53 | 54 | repo_path = os.path.join(os.path.dirname(heat.__file__), 55 | 'db', 'sqlalchemy', 'migrate_repo') 56 | repo_version = versioning_api.repository.Repository(repo_path).latest 57 | return current_version != repo_version 58 | 59 | 60 | def do_dbsync(): 61 | """Do the dbsync. Returns (returncode, stdout, stderr)""" 62 | # We call heat-manage db_sync on the shell rather than trying to 63 | # do this in Python since we have no guarantees about changes to the 64 | # internals. 65 | args = ['heat-manage', 'db_sync'] 66 | 67 | call = subprocess.Popen(args, shell=False, 68 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) 69 | out, err = call.communicate() 70 | return (call.returncode, out, err) 71 | 72 | 73 | def main(): 74 | 75 | module = AnsibleModule( 76 | argument_spec=dict( 77 | action=dict(required=True), 78 | conf=dict(required=False, default="/etc/heat/heat.conf") 79 | ), 80 | supports_check_mode=True 81 | ) 82 | 83 | if not heat_found: 84 | module.fail_json(msg="python-heatclient could not be found") 85 | 86 | action = module.params['action'] 87 | conf = module.params['conf'] 88 | if action not in ['dbsync', 'db_sync']: 89 | module.fail_json(msg="Only supported action is 'dbsync'") 90 | 91 | changed = will_db_change(conf) 92 | if module.check_mode: 93 | module.exit_json(changed=changed) 94 | 95 | (res, stdout, stderr) = do_dbsync() 96 | 97 | if res == 0: 98 | module.exit_json(changed=changed, stdout=stdout, stderr=stderr) 99 | else: 100 | module.fail_json(msg="heat-manage returned non-zero value: %d" % res, 101 | stdout=stdout, stderr=stderr) 102 | 103 | 104 | from ansible.module_utils.basic import * 105 | main() 106 | -------------------------------------------------------------------------------- /keystone_manage: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | DOCUMENTATION = ''' 5 | --- 6 | module: keystone_manage 7 | short_description: Initialize OpenStack Identity (keystone) database 8 | description: Create the tables for the database backend used by keystone 9 | options: 10 | action: 11 | description: 12 | - action to perform. Currently only dbysnc is supported 13 | required: true 14 | conf: 15 | description: 16 | - path to keystone config file. 17 | required: false 18 | default: /etc/keystone/keystone.conf 19 | requirements: [ keystone ] 20 | author: Lorin Hochstein 21 | ''' 22 | 23 | EXAMPLES = ''' 24 | keystone_manage: action=dbsync 25 | ''' 26 | 27 | import subprocess 28 | 29 | try: 30 | # this is necessary starting from havana release due to bug 885529 31 | # https://bugs.launchpad.net/glance/+bug/885529 32 | from keystone.openstack.common import gettextutils 33 | gettextutils.install('keystone') 34 | except ImportError: 35 | # this is not havana 36 | pass 37 | 38 | try: 39 | from keystone.common import sql 40 | from migrate.versioning import api as versioning_api 41 | except ImportError: 42 | keystone_found = False 43 | else: 44 | keystone_found = True 45 | 46 | try: 47 | # for icehouse 48 | from keystone.common.sql import migration_helpers as migration 49 | except ImportError: 50 | pass 51 | 52 | 53 | def will_db_change(conf): 54 | """ Check if the database version will change after the sync. 55 | 56 | conf is the path to the keystone config file 57 | 58 | """ 59 | # Load the config file options 60 | try: 61 | # before icehouse 62 | sql.migration.CONF(project='keystone', default_config_files=[conf]) 63 | current_version = sql.migration.db_version() 64 | except AttributeError: 65 | # starting with icehouse 66 | sql.core.CONF(project='keystone', default_config_files=[conf]) 67 | current_version = migration.get_db_version() 68 | 69 | # in havana the method _find_migrate_repo has been renamed to find_migrate_repo 70 | try: 71 | repo_path = migration.find_migrate_repo() 72 | except AttributeError: 73 | repo_path = migration._find_migrate_repo() 74 | repo_version = versioning_api.repository.Repository(repo_path).latest 75 | return current_version != repo_version 76 | 77 | 78 | def do_dbsync(): 79 | """Do the dbsync. Returns (returncode, stdout, stderr)""" 80 | # We call keystone-manage db_sync on the shell rather than trying to 81 | # do this in Python since we have no guarantees about changes to the 82 | # internals. 83 | args = ['keystone-manage', 'db_sync'] 84 | 85 | call = subprocess.Popen(args, shell=False, 86 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) 87 | out, err = call.communicate() 88 | return (call.returncode, out, err) 89 | 90 | 91 | def main(): 92 | 93 | module = AnsibleModule( 94 | argument_spec=dict( 95 | action=dict(required=True), 96 | conf=dict(required=False, default="/etc/keystone/keystone.conf") 97 | ), 98 | supports_check_mode=True 99 | ) 100 | 101 | if not keystone_found: 102 | module.fail_json(msg="keystone package could not be found") 103 | 104 | action = module.params['action'] 105 | conf = module.params['conf'] 106 | if action not in ['dbsync', 'db_sync']: 107 | module.fail_json(msg="Only supported action is 'dbsync'") 108 | 109 | changed = will_db_change(conf) 110 | if module.check_mode: 111 | module.exit_json(changed=changed) 112 | 113 | (res, stdout, stderr) = do_dbsync() 114 | 115 | if res == 0: 116 | module.exit_json(changed=changed, stdout=stdout, stderr=stderr) 117 | else: 118 | module.fail_json(msg="keystone-manage returned non-zero value: %d" % res, 119 | stdout=stdout, stderr=stderr) 120 | 121 | # this is magic, see lib/ansible/module_common.py 122 | #<> 123 | main() 124 | -------------------------------------------------------------------------------- /cinder_volume_types: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | from ansible.module_utils.basic import * 4 | try: 5 | from cinderclient.v2 import client 6 | except ImportError: 7 | print("failed=True msg='cinder client is required'") 8 | 9 | 10 | DOCUMENTATION = ''' 11 | --- 12 | module: cinder_configure 13 | short_description: Configure Openstack Block Storage (Cinder) 14 | description: Create Volume Types needed for deploying Cinder 15 | options: 16 | action: 17 | description: 18 | - Currently only supported option is create 19 | required: true 20 | choices: [create] 21 | username: 22 | description: 23 | - username used to authenticate with keystone. 24 | required: true 25 | password: 26 | description: 27 | - password used to authenticate with keystone. 28 | required: true 29 | url_auth: 30 | description: 31 | - keystone url for authentication. 32 | required: true 33 | tenant_name: 34 | description: 35 | - tenant name or project name of the login user 36 | required: true 37 | region_name: 38 | description: 39 | - region to connect to 40 | required: true 41 | name: 42 | description: 43 | - Name to be given to the volume type. 44 | required: true 45 | extra_specs: 46 | description: 47 | - A dictionary of extra specs to add to the volume type. 48 | required: false 49 | requirements: [ cinder ] 50 | author: Rodrigo Soto 51 | ''' 52 | 53 | EXAMPLES = ''' 54 | cinder_volume_types: 55 | action: create 56 | username: admin 57 | password: "{{keystone_admin_password}}" 58 | tenant_name: admin 59 | region_name: RegionOne 60 | url_auth: "{{keystone_admin_url}}" 61 | name: some-name 62 | extra_specs: "volume_backend_name=some-name" 63 | ''' 64 | 65 | 66 | def _get_cinderclient(module): 67 | try: 68 | cinder_client = client.Client( 69 | module.params.get('username'), 70 | module.params.get('password'), 71 | module.params.get('tenant_name'), 72 | module.params.get('url_auth'), 73 | region_name=module.params.get('region_name') 74 | ) 75 | except Exception as e: 76 | module.fail_json(msg="Error authenticating to cinder: %s" % e.message) 77 | return cinder_client 78 | 79 | 80 | def _get_volume_type(module, cinderclient): 81 | name = module.params.get('name') 82 | try: 83 | volume_type = cinderclient.volume_types.find(name=name) 84 | if volume_type is not None: 85 | return volume_type 86 | except Exception: 87 | return None 88 | return None 89 | 90 | 91 | def _create_volume_type(module, cinderclient): 92 | name = module.params.get('name') 93 | try: 94 | volume_type_result = cinderclient.volume_types.create(name) 95 | except Exception as e: 96 | module.fail_json(msg="Error in creating volume type: %s" % e.message) 97 | return volume_type_result 98 | 99 | 100 | def _delete_volume_type(module, cinderclient): 101 | name = module.params.get('name') 102 | try: 103 | volume_type = cinderclient.volume_types.find(name=name) 104 | except Exception as e: 105 | module.fail_json( 106 | msg="Error finding volume type to delete: %s" % e.message 107 | ) 108 | try: 109 | cinderclient.volume_types.delete(volume_type.id) 110 | except Exception as e: 111 | module.fail_json( 112 | msg="Error in deleting the volume type: %s" % e.message 113 | ) 114 | return True 115 | 116 | 117 | def _volume_type_set_keys(volume_type, extra_specs): 118 | if extra_specs is not None: 119 | extra_specs_dict = {} 120 | extra_specs = extra_specs.split(',') 121 | for extra_spec in extra_specs: 122 | key, value = extra_spec.split('=') 123 | extra_specs_dict[key] = value 124 | try: 125 | volume_type.set_keys(extra_specs_dict) 126 | except Exception as e: 127 | raise e 128 | 129 | 130 | def _get_volume_type_id(module, cinderclient): 131 | name = module.params.get('name') 132 | try: 133 | volume_type = cinderclient.volume_types.find(name=name) 134 | except Exception as e: 135 | module.fail_json( 136 | msg="Error finding volume type %s: %s" % (name, e.message) 137 | ) 138 | return volume_type.id 139 | 140 | 141 | def main(): 142 | module = AnsibleModule( 143 | argument_spec={ 144 | 'action': {'default': 'create'}, 145 | 'username': {'required': True}, 146 | 'password': {'required': True}, 147 | 'url_auth': {'required': True}, 148 | 'tenant_name': {'required': True}, 149 | 'region_name': {'required': True}, 150 | 'name': {'required': True}, 151 | 'extra_specs': {'required': False}, 152 | }, 153 | ) 154 | 155 | cinderclient = _get_cinderclient(module) 156 | 157 | if module.params.get('action') == 'create': 158 | volume_type = _get_volume_type(module, cinderclient) 159 | if volume_type is None: 160 | volume_type = _create_volume_type(module, cinderclient) 161 | _volume_type_set_keys( 162 | volume_type, module.params.get('extra_specs') 163 | ) 164 | module.exit_json( 165 | changed=True, 166 | result="Created", 167 | msg=volume_type.id 168 | ) 169 | else: 170 | _volume_type_set_keys( 171 | volume_type, module.params.get('extra_specs') 172 | ) 173 | module.exit_json( 174 | changed=False, 175 | result="Success", 176 | msg=_get_volume_type_id(module, cinderclient) 177 | ) 178 | 179 | main() -------------------------------------------------------------------------------- /glance_manage: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | DOCUMENTATION = ''' 5 | --- 6 | module: glance_manage 7 | short_description: Initialize OpenStack Image (glance) database 8 | description: Create the tables for the database backend used by glance 9 | options: 10 | action: 11 | description: 12 | - action to perform. Currently only dbsync is supported. 13 | required: true 14 | conf: 15 | description: 16 | - path to glance-registry config file. 17 | required: false 18 | default: /etc/glance/glance-registry.conf 19 | requirements: [ glance ] 20 | author: Lorin Hochstein 21 | ''' 22 | 23 | EXAMPLES = ''' 24 | glance_manage: action=dbsync 25 | ''' 26 | 27 | from distutils.version import LooseVersion 28 | import os 29 | import subprocess 30 | import sys 31 | 32 | try: 33 | import glance 34 | import sqlalchemy 35 | except ImportError: 36 | print("failed=True msg='glance is not installed'") 37 | sys.exit(1) 38 | 39 | from glance.version import version_info 40 | # this is necessary between the havana and juno releases due to bug 885529 41 | # https://bugs.launchpad.net/glance/+bug/885529 42 | try: 43 | from glance.openstack.common import gettextutils 44 | gettextutils.install('glance') 45 | except ImportError: 46 | # gettextutils has been removed in version 2015.1, ignoring the error 47 | pass 48 | 49 | import glance.db.sqlalchemy.api 50 | 51 | try: 52 | glance_version = version_info.version_string() 53 | except AttributeError: 54 | glance_version = version_info.version 55 | 56 | if LooseVersion(glance_version) >= LooseVersion('2014.2'): 57 | from oslo.config.cfg import CONF 58 | from oslo.db.sqlalchemy import migration 59 | from migrate.versioning import api as versioning_api 60 | from glance.db import migration as db_migration 61 | from glance.db.sqlalchemy import api as db_api 62 | elif glance_version.startswith('2014.1'): 63 | from oslo.config.cfg import CONF 64 | from glance.openstack.common.db.sqlalchemy import migration 65 | from migrate.versioning import api as versioning_api 66 | else: 67 | from glance.db.sqlalchemy import migration 68 | from glance.common.exception import DatabaseMigrationError 69 | from migrate.versioning import api as versioning_api 70 | CONF = migration.CONF 71 | 72 | def is_under_version_control(conf): 73 | """ Return true if the database is under version control""" 74 | CONF(project='glance', default_config_files=[conf]) 75 | try: 76 | migration.db_version() 77 | except DatabaseMigrationError: 78 | return False 79 | # db_version() will fail with TypeError on icehouse. Icehouse uses db 80 | # migration so we're good. 81 | finally: 82 | return True 83 | 84 | 85 | def will_db_change(conf): 86 | """ Check if the database version will change after the sync """ 87 | # Load the config file options 88 | if not is_under_version_control(conf): 89 | return True 90 | if LooseVersion(glance_version) >= LooseVersion('2014.2'): 91 | engine = db_api.get_engine() 92 | repo_path = db_migration.MIGRATE_REPO_PATH 93 | current_version = migration.db_version(db_api.get_engine(), 94 | repo_path, 95 | db_migration.INIT_VERSION) 96 | elif glance_version.startswith('2014.1'): 97 | repo_path = os.path.join(os.path.dirname(glance.__file__), 98 | 'db', 'sqlalchemy', 'migrate_repo') 99 | engine = sqlalchemy.create_engine(CONF.database.connection) 100 | current_version = migration.db_version(engine, repo_path, 0) 101 | else: 102 | repo_path = migration.get_migrate_repo_path() 103 | current_version = migration.db_version() 104 | 105 | repo_version = versioning_api.repository.Repository(repo_path).latest 106 | return current_version != repo_version 107 | 108 | 109 | def put_under_version_control(): 110 | """ Create the initial sqlalchemy migrate database tables. """ 111 | args = ['glance-manage', 'version_control', '0'] 112 | 113 | call = subprocess.Popen(args, shell=False, 114 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) 115 | out, err = call.communicate() 116 | return (call.returncode, out, err) 117 | 118 | 119 | def do_dbsync(): 120 | """ Do a database migration """ 121 | args = ['glance-manage', 'db_sync'] 122 | 123 | call = subprocess.Popen(args, shell=False, 124 | stdout=subprocess.PIPE, stderr=subprocess.PIPE) 125 | out, err = call.communicate() 126 | return (call.returncode, out, err) 127 | 128 | 129 | def main(): 130 | 131 | module = AnsibleModule( 132 | argument_spec=dict( 133 | action=dict(required=True), 134 | conf=dict(required=False, 135 | default="/etc/glance/glance-registry.conf") 136 | ), 137 | supports_check_mode=True 138 | ) 139 | 140 | action = module.params['action'] 141 | if action not in ['dbsync', 'db_sync']: 142 | module.fail_json(msg="Only supported action is 'dbsync'") 143 | 144 | conf = module.params['conf'] 145 | 146 | changed = will_db_change(conf) 147 | if module.check_mode: 148 | module.exit_json(changed=changed) 149 | 150 | if not is_under_version_control(conf): 151 | (res, stdout, stderr) = put_under_version_control() 152 | if res != 0: 153 | msg = "failed to put glance db under version control" 154 | module.fail_json(msg=msg, stdout=stdout, stderr=stderr) 155 | 156 | (res, stdout, stderr) = do_dbsync() 157 | if res != 0: 158 | msg = "failed to synchronize glance db with repository" 159 | module.fail_json(msg=msg, stdout=stdout, stderr=stderr) 160 | 161 | module.exit_json(changed=changed) 162 | 163 | #<> 164 | main() 165 | -------------------------------------------------------------------------------- /glance: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | DOCUMENTATION = ''' 5 | --- 6 | module: glance 7 | short_description: Manage OpenStack virtual machine images 8 | description: 9 | - Upload virtual machine images to OpenStack Image Service (glance) 10 | requirements: [ python-glanceclient ] 11 | options: 12 | name: 13 | description: 14 | - name of the image 15 | required: true 16 | format: 17 | description: 18 | - disk format 19 | choices: [ami, ari, aki, vhd, vmdk, raw, qcow2, vdi, iso] 20 | required: true 21 | is_public: 22 | description: 23 | - if true, image is public 24 | choices: [true, false] 25 | aliases: [public] 26 | required: false 27 | default: false 28 | file: 29 | description: 30 | - path to the file that contains the image 31 | required: true 32 | aliases: [path] 33 | auth_url: 34 | description: 35 | - URL to Identity service (keystone) catalog endpoint 36 | required: true 37 | region: 38 | description: 39 | - OpenStack region name 40 | required: false 41 | aliases: [region_name] 42 | username: 43 | description: 44 | - user name to authenticate against Identity service 45 | aliases: [user, user_name, login_user] 46 | password: 47 | description: 48 | - password to authenticate against Identity service 49 | aliases: [pass, login_password] 50 | tenant_name: 51 | description: 52 | - name of the tenant 53 | endpoint_type: 54 | description: 55 | - endpoint URL type 56 | choices: [publicURL, internalURL] 57 | required: false 58 | default: publicURL 59 | 60 | examples: 61 | - code: 'glance: name=cirros file=/tmp/cirros.img format=qcow2 is_public=true auth_url=http://192.168.206.130:5000/v2.0/ username=admin tenant_name=demo password=secrete region=RegionOne endpoint_type=publicURL ' 62 | ''' 63 | 64 | 65 | try: 66 | from glanceclient import Client 67 | from keystoneclient.v2_0 import client as ksclient 68 | except ImportError: 69 | glanceclient_found = False 70 | else: 71 | glanceclient_found = True 72 | 73 | 74 | def get_token_and_endpoint(auth_url, username, password, tenant_name, 75 | region_name, endpoint_type): 76 | 77 | keystone = ksclient.Client(username=username, 78 | password=password, 79 | tenant_name=tenant_name, 80 | auth_url=auth_url, 81 | region_name=region_name) 82 | glance_endpoint = keystone.service_catalog.url_for( 83 | service_type="image", 84 | endpoint_type=endpoint_type) 85 | return (keystone.auth_token, glance_endpoint) 86 | 87 | 88 | def authenticate(auth_url, username, password, tenant_name, region, 89 | endpoint_type, version='1'): 90 | """Return a keystone client object""" 91 | 92 | (token, endpoint) = get_token_and_endpoint(auth_url, username, password, 93 | tenant_name, region, 94 | endpoint_type) 95 | 96 | return Client(version, endpoint=endpoint, token=token) 97 | 98 | 99 | def get_images(glance, name): 100 | """ Retrieve all images with a certain name """ 101 | images = [x for x in glance.images.list() if x.name == name] 102 | return images 103 | 104 | 105 | def create_image(glance, name, path, disk_format, is_public, check_mode): 106 | """ Create a new image from a file on the path. 107 | 108 | Return a pair. First element indicates whether a change occurred, 109 | second one is the ID of the iamge """ 110 | 111 | # If the image(s) already exists, we're done 112 | images = get_images(glance, name) 113 | if len(images) > 0: 114 | return (False, images[0].id) 115 | 116 | if check_mode: 117 | return (True, None) 118 | 119 | image = glance.images.create(name=name, disk_format=disk_format, 120 | container_format='bare', 121 | is_public=is_public) 122 | image.update(data=open(path, 'rb')) 123 | return (True, image.id) 124 | 125 | 126 | def main(): 127 | 128 | module = AnsibleModule( 129 | argument_spec=dict( 130 | name=dict(required=True), 131 | file=dict(required=True, aliases=['path']), 132 | auth_url=dict(required=True), 133 | region=dict(required=False, aliases=['region_name']), 134 | username=dict(required=True, aliases=['user', 135 | 'user_name', 136 | 'login_user']), 137 | password=dict(required=True, aliases=['pass', 'login_password']), 138 | tenant_name=dict(required=True, aliases=['tenant']), 139 | disk_format=dict(required=True, 140 | choices=['ami', 'ari', 'aki', 'vhd', 'vmdk', 'raw', 141 | 'qcow2', 'vdi', 'iso'], 142 | aliases=['disk-format', 'format']), 143 | is_public=dict(required=False, 144 | default=False, 145 | aliases=['public']), 146 | endpoint_type=dict(required=False, 147 | choices=['publicURL', 'internalURL'], 148 | default='publicURL') 149 | ), 150 | supports_check_mode=True 151 | ) 152 | 153 | name = module.params['name'] 154 | path = module.params['file'] 155 | auth_url = module.params['auth_url'] 156 | region = module.params['region'] 157 | username = module.params['username'] 158 | password = module.params['password'] 159 | tenant_name = module.params['tenant_name'] 160 | disk_format = module.params['disk_format'] 161 | is_public = module.params['is_public'] 162 | endpoint_type = module.params['endpoint_type'] 163 | check_mode = module.check_mode 164 | 165 | glance = authenticate(auth_url, username, password, tenant_name, region, 166 | endpoint_type) 167 | 168 | (changed, id) = create_image(glance, name, path, disk_format, is_public, 169 | check_mode) 170 | 171 | module.exit_json(changed=changed, name=name, id=id) 172 | 173 | # this is magic, see lib/ansible/module_common.py 174 | #<> 175 | if __name__ == '__main__': 176 | main() 177 | -------------------------------------------------------------------------------- /nova_quota: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding: utf-8 -*- 3 | 4 | # (c) 2014, Toni Ylenius 5 | # 6 | # This module is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | try: 20 | from novaclient import client 21 | from keystoneclient.v2_0 import client as ksclient 22 | except ImportError: 23 | print("failed=True msg='novaclient and keystone client are required'") 24 | 25 | DOCUMENTATION = ''' 26 | --- 27 | module: nova_quota 28 | short_description: Manage OpenStack Nova Quotas 29 | description: 30 | - Sets tenant Quota in Nova 31 | requirements: [ python-keystoneclient, python-novaclient ] 32 | options: 33 | login_username: 34 | description: 35 | - user name to authenticate against Identity service 36 | required: True 37 | login_password: 38 | description: 39 | - password to authenticate against Identity service 40 | required: True 41 | login_tenant_name: 42 | description: 43 | - tenant name of the login user 44 | required: True 45 | auth_url: 46 | description: 47 | - The keystone URL for authentication 48 | required: false 49 | default: 'http://127.0.0.1:35357/v2.0/' 50 | region_name: 51 | description: 52 | - Name of the region 53 | required: False 54 | default: None 55 | tenant_name: 56 | description: 57 | - tenant name 58 | required: False 59 | default: [login_tenant_name] 60 | instances: 61 | description: 62 | - Number of Instances per tenant 63 | required: False 64 | cores: 65 | description: 66 | - Number of VCPUs per tenant 67 | required: False 68 | ram: 69 | description: 70 | - Memory in MB per tenant 71 | required: False 72 | ''' 73 | 74 | EXAMPLES = ''' 75 | - nova_quota: 76 | login_username: admin 77 | login_password: 1234 78 | login_tenant_name: admin 79 | tenant_name: tenant1 80 | instances: 50 81 | cores: 100 82 | ram: 1024000 83 | ''' 84 | 85 | def _get_keystone_client(module): 86 | """ 87 | Return a Keystone client object. 88 | :param module: module 89 | :return: keystone client 90 | """ 91 | try: 92 | keystone = ksclient.Client(auth_url=module.params.get('auth_url'), 93 | username=module.params['login_username'], 94 | password=module.params['login_password'], 95 | tenant_name=module.params['login_tenant_name'], 96 | region=module.params.get('region')) 97 | except Exception, e: 98 | module.fail_json( 99 | msg = "Could not authenticate with Keystone: %s" % e.message) 100 | 101 | return keystone 102 | 103 | def _get_nova_client(module, keystone): 104 | """ 105 | Return a Nova client object. 106 | :param module: module 107 | :return: nova client 108 | """ 109 | 110 | try: 111 | nova = client.Client('2', keystone.username, 112 | keystone.password, 113 | keystone.tenant_name, 114 | keystone.auth_url) 115 | except Exception, e: 116 | module.fail_json(msg = "Could not get Nova client: %s" % e.message) 117 | 118 | return nova 119 | 120 | def _get_tenant_id(module, keystone): 121 | """ 122 | Returns the tenant_id 123 | if tenant_name is not specified in the module params uses login_tenant_name 124 | :param module: module 125 | :param keystone: a keystone client used to get the tenant_id from its 126 | name. 127 | :return: tenant id 128 | """ 129 | if not module.params['tenant_name']: 130 | tenant_name = module.params['login_tenant_name'] 131 | else: 132 | tenant_name = module.params['tenant_name'] 133 | 134 | tenants = keystone.tenants.list() 135 | tenant = next((t for t in tenants if t.name == tenant_name), None) 136 | if not tenant: 137 | module.fail_json(msg ="Tenant with name '%s' not found." % tenant_name) 138 | 139 | return tenant.id 140 | 141 | def _ensure_quota(module, nova, tenant_id): 142 | """ 143 | Ensures quota. Returns quota and changed 144 | :param module: module 145 | :param nova: a nova client 146 | :return: changed (True/False), quota_set object 147 | """ 148 | cur_quota = nova.quotas.get(tenant_id) 149 | new_quota = {} 150 | changed = False 151 | 152 | for key in ('instances', 'cores', 'ram'): 153 | if module.params[key]: 154 | new_quota[key] = module.params[key] 155 | 156 | if getattr(cur_quota, key) != new_quota[key]: 157 | changed = True 158 | 159 | if module.check_mode: 160 | return changed, cur_quota.to_dict() 161 | 162 | if changed: 163 | try: 164 | nova.quotas.update(tenant_id, **new_quota) 165 | cur_quota = nova.quotas.get(tenant_id) 166 | except Exception, e: 167 | module.fail_json(msg = "Could not update quota: %s" % e.message) 168 | 169 | return changed, cur_quota.to_dict() 170 | 171 | 172 | def main(): 173 | module = AnsibleModule( 174 | argument_spec = dict( 175 | login_username = dict(default='admin'), 176 | login_password = dict(required=True), 177 | login_tenant_name = dict(required='True'), 178 | auth_url = dict(default='http://127.0.0.1:35357/v2.0/'), 179 | region_name = dict(default=None), 180 | tenant_name = dict(required=False), 181 | instances = dict(required=False), 182 | cores = dict(required=False), 183 | ram = dict(required=False), 184 | ), 185 | supports_check_mode = True 186 | ) 187 | 188 | keystone = _get_keystone_client(module) 189 | nova = _get_nova_client(module, keystone) 190 | 191 | tenant_id = _get_tenant_id(module, keystone) 192 | changed, quota = _ensure_quota(module, nova, tenant_id) 193 | 194 | module.exit_json(changed=changed, tenant_id=tenant_id, quota=quota) 195 | 196 | # this is magic, see lib/ansible/module_common.py 197 | #<> 198 | if __name__ == '__main__': 199 | main() 200 | -------------------------------------------------------------------------------- /nova_aggregate: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding: utf-8 -*- 3 | 4 | # (c) 2015, Christian Zunker 5 | # 6 | # This module is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | try: 20 | from novaclient import client 21 | from keystoneclient.v2_0 import client as ksclient 22 | except ImportError: 23 | print("failed=True msg='novaclient and keystone client are required'") 24 | 25 | DOCUMENTATION = ''' 26 | --- 27 | module: nova_aggregate 28 | short_description: Manage OpenStack host aggregates 29 | description: 30 | - Create host aggregates with OpenStack Nova service 31 | requirements: [ python-novaclient ] 32 | options: 33 | login_username: 34 | description: 35 | - user name to authenticate against Identity service 36 | required: True 37 | aliases: [username] 38 | login_password: 39 | description: 40 | - password to authenticate against Identity service 41 | aliases: [password] 42 | required: True 43 | login_tenant_name: 44 | description: 45 | - tenant name of the login user 46 | aliases: [tenant_name] 47 | required: True 48 | auth_url: 49 | description: 50 | - The keystone URL for authentication 51 | required: false 52 | default: 'http://127.0.0.1:35357/v2.0/' 53 | region_name: 54 | description: 55 | - Name of the region 56 | required: False 57 | default: None 58 | name: 59 | description: 60 | - Descriptive name of the aggregate 61 | required: True 62 | availability_zone: 63 | description: 64 | - Availability Zone of the aggregate 65 | required: False 66 | hosts: 67 | description: 68 | - Hosts asigned to the aggregate 69 | required: False 70 | metadata: 71 | description: 72 | - Metadata for the aggregate, used as reference inside flavors 73 | required: False 74 | state: 75 | description: 76 | - Create or delete aggregate 77 | required: False 78 | choices: ['present', 'absent'] 79 | default: 'present' 80 | ''' 81 | 82 | EXAMPLES = ''' 83 | - nova_aggregate: 84 | login_username: admin 85 | login_password: 1234 86 | login_tenant_name: admin 87 | name: medium 88 | ''' 89 | 90 | def authenticate(module, auth_url, username, password, tenant_name, region): 91 | """ 92 | Return a Nova client object. 93 | """ 94 | try: 95 | keystone = ksclient.Client(auth_url=auth_url, 96 | username=username, 97 | password=password, 98 | tenant_name=tenant_name, 99 | region=region) 100 | except Exception as e: 101 | module.fail_json( 102 | msg = "Could not authenticate with Keystone: {}".format( 103 | e.message)) 104 | 105 | try: 106 | nova = client.Client('2', keystone.username, 107 | keystone.password, 108 | keystone.tenant_name, 109 | keystone.auth_url) 110 | except Exception as e: 111 | module.fail_json(msg = "Could not get Nova client: {}".format( 112 | e.message)) 113 | 114 | return nova 115 | 116 | def get_aggregates(nova, name, id=None): 117 | if not id: 118 | aggregates = [x for x in nova.aggregates.list() if x.name == name] 119 | else: 120 | aggregates = [x for x in nova.aggregates.list() if x.name == name and x.id == str(id)] 121 | return aggregates 122 | 123 | def create_aggregate(module, nova, name, availability_zone, hosts, metadata, id): 124 | aggregate_name = name + "-" + availability_zone 125 | aggregates = get_aggregates(nova, aggregate_name, id) 126 | if len(aggregates) >0: 127 | present_aggregate = aggregates[0] 128 | changed = False 129 | for host in hosts: 130 | if not host in present_aggregate.hosts: 131 | nova.aggregates.add_host(present_aggregate, host) 132 | changed = True 133 | if metadata != present_aggregate.metadata: 134 | nova.aggregates.set_metadata(present_aggregate, metadata) 135 | changed = True 136 | return changed, aggregates[0].id 137 | 138 | try: 139 | aggregate = nova.aggregates.create(name=aggregate_name, availability_zone=availability_zone) 140 | for host in hosts: 141 | nova.aggregates.add_host(aggregate, host) 142 | nova.aggregates.set_metadata(aggregate, metadata) 143 | except Exception as e: 144 | module.fail_json(msg = "Could not create aggregate: {0}".format(e.message)) 145 | 146 | return True, aggregate.id 147 | 148 | def delete_aggregate(module, nova, name): 149 | aggregates = get_aggregates(nova, name) 150 | if len(aggregates) == 0: 151 | return False 152 | for aggregate in aggregates: 153 | try: 154 | nova.aggregates.delete(aggregate); 155 | except Exception as e: 156 | module.fail_json(msg = "Could not delete aggregate {0}: {1}".format(name, e.message)) 157 | 158 | return True 159 | 160 | def main(): 161 | module = AnsibleModule( 162 | argument_spec = dict( 163 | login_username = dict(default='admin', aliases=["username"]), 164 | login_password = dict(required=True, aliases=["password"]), 165 | login_tenant_name = dict(required='True', aliases=["tenant_name"]), 166 | auth_url = dict(default='http://127.0.0.1:35357/v2.0/'), 167 | region_name = dict(default=None), 168 | name = dict(required=True), 169 | id = dict(default=None), 170 | availability_zone = dict(required=False), 171 | hosts = dict(required=False), 172 | metadata = dict(required=False, default=None), 173 | state = dict(default='present'), 174 | ) 175 | ) 176 | auth_url = module.params['auth_url'] 177 | region = module.params['region_name'] 178 | username = module.params['login_username'] 179 | password = module.params['login_password'] 180 | tenant_name = module.params['login_tenant_name'] 181 | name = module.params['name'] 182 | availability_zone = module.params['availability_zone'] 183 | hosts = module.params['hosts'] 184 | metadata = module.params['metadata'] 185 | id = module.params['id'] 186 | state = module.params['state'] 187 | 188 | nova = authenticate(module, auth_url, username, password, tenant_name, region) 189 | 190 | if state == 'present': 191 | changed, id = create_aggregate(module, nova, name, availability_zone, hosts, metadata, id) 192 | module.exit_json(changed=changed, name=name, id=id) 193 | elif state == 'absent': 194 | changed = delete_aggregate(module, nova, name) 195 | module.exit_json(changed=changed, name=name) 196 | else: 197 | raise ValueError("Code should never reach here") 198 | 199 | 200 | 201 | # this is magic, see lib/ansible/module_common.py 202 | #<> 203 | if __name__ == '__main__': 204 | main() 205 | -------------------------------------------------------------------------------- /neutron_router: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding: utf-8 -*- 3 | 4 | # (c) 2013, Benno Joy 5 | # 6 | # This module is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | try: 20 | from neutronclient.neutron import client 21 | from keystoneclient.v2_0 import client as ksclient 22 | except ImportError: 23 | print("failed=True msg='neutronclient and keystone client are required'") 24 | 25 | DOCUMENTATION = ''' 26 | --- 27 | module: neutron_router 28 | version_added: "1.2" 29 | short_description: Create or Remove router from openstack 30 | description: 31 | - Create or Delete routers from OpenStack 32 | options: 33 | login_username: 34 | description: 35 | - login username to authenticate to keystone 36 | required: true 37 | default: admin 38 | login_password: 39 | description: 40 | - Password of login user 41 | required: true 42 | default: 'yes' 43 | login_tenant_name: 44 | description: 45 | - The tenant name of the login user 46 | required: true 47 | default: 'yes' 48 | auth_url: 49 | description: 50 | - The keystone url for authentication 51 | required: false 52 | default: 'http://127.0.0.1:35357/v2.0/' 53 | region_name: 54 | description: 55 | - Name of the region 56 | required: false 57 | default: None 58 | state: 59 | description: 60 | - Indicate desired state of the resource 61 | choices: ['present', 'absent'] 62 | default: present 63 | name: 64 | description: 65 | - Name to be give to the router 66 | required: true 67 | default: None 68 | tenant_name: 69 | description: 70 | - Name of the tenant for which the router has to be created, if none router would be created for the login tenant. 71 | required: false 72 | default: None 73 | admin_state_up: 74 | description: 75 | - desired admin state of the created router . 76 | required: false 77 | default: true 78 | requirements: ["neutronclient", "keystoneclient"] 79 | ''' 80 | 81 | EXAMPLES = ''' 82 | # Creates a router for tenant admin 83 | - neutron_router: state=present 84 | login_username=admin 85 | login_password=admin 86 | login_tenant_name=admin 87 | name=router1" 88 | ''' 89 | 90 | _os_keystone = None 91 | _os_tenant_id = None 92 | 93 | def _get_ksclient(module, kwargs): 94 | try: 95 | kclient = ksclient.Client( 96 | username=module.params.get('login_username'), 97 | password=module.params.get('login_password'), 98 | tenant_name=module.params.get('login_tenant_name'), 99 | auth_url=module.params.get('auth_url'), 100 | region_name=module.params.get('region_name')) 101 | except Exception as e: 102 | module.fail_json(msg = "Error authenticating to the keystone: %s " % e.message) 103 | global _os_keystone 104 | _os_keystone = kclient 105 | return kclient 106 | 107 | 108 | def _get_endpoint(module, ksclient): 109 | try: 110 | endpoint = ksclient.service_catalog.url_for(service_type='network', endpoint_type='publicURL') 111 | except Exception as e: 112 | module.fail_json(msg = "Error getting endpoint for glance: %s" % e.message) 113 | return endpoint 114 | 115 | def _get_neutron_client(module, kwargs): 116 | _ksclient = _get_ksclient(module, kwargs) 117 | token = _ksclient.auth_token 118 | endpoint = _get_endpoint(module, _ksclient) 119 | kwargs = { 120 | 'token': token, 121 | 'endpoint_url': endpoint 122 | } 123 | try: 124 | neutron = client.Client('2.0', **kwargs) 125 | except Exception as e: 126 | module.fail_json(msg = "Error in connecting to Neutron: %s " % e.message) 127 | return neutron 128 | 129 | def _set_tenant_id(module): 130 | global _os_tenant_id 131 | if module.params['tenant_name']: 132 | # We need admin power in order retrieve the tenant_id of a given 133 | # tenant name and to create/delete networks for a tenant that is not 134 | # the one used to authenticate the user. 135 | tenant_name = module.params['tenant_name'] 136 | for tenant in _os_keystone.tenants.list(): 137 | if tenant.name == tenant_name: 138 | _os_tenant_id = tenant.id 139 | break 140 | else: 141 | _os_tenant_id = _os_keystone.tenant_id 142 | 143 | if not _os_tenant_id: 144 | module.fail_json(msg = "The tenant id cannot be found, please check the paramters") 145 | 146 | def _get_router_id(module, neutron): 147 | kwargs = { 148 | 'name': module.params['name'], 149 | 'tenant_id': _os_tenant_id, 150 | } 151 | try: 152 | routers = neutron.list_routers(**kwargs) 153 | except Exception as e: 154 | module.fail_json(msg = "Error in getting the router list: %s " % e.message) 155 | if not routers['routers']: 156 | return None 157 | return routers['routers'][0]['id'] 158 | 159 | def _create_router(module, neutron): 160 | router = { 161 | 'name': module.params['name'], 162 | 'tenant_id': _os_tenant_id, 163 | 'admin_state_up': module.params['admin_state_up'], 164 | } 165 | try: 166 | new_router = neutron.create_router(dict(router=router)) 167 | except Exception as e: 168 | module.fail_json( msg = "Error in creating router: %s" % e.message) 169 | return new_router['router']['id'] 170 | 171 | def _delete_router(module, neutron, router_id): 172 | try: 173 | neutron.delete_router(router_id) 174 | except: 175 | module.fail_json("Error in deleting the router") 176 | return True 177 | 178 | def main(): 179 | module = AnsibleModule( 180 | argument_spec = dict( 181 | login_username = dict(default='admin'), 182 | login_password = dict(required=True), 183 | login_tenant_name = dict(required='True'), 184 | auth_url = dict(default='http://127.0.0.1:35357/v2.0/'), 185 | region_name = dict(default=None), 186 | name = dict(required=True), 187 | tenant_name = dict(default=None), 188 | state = dict(default='present', choices=['absent', 'present']), 189 | admin_state_up = dict(type='bool', default=True), 190 | ), 191 | ) 192 | 193 | neutron = _get_neutron_client(module, module.params) 194 | _set_tenant_id(module) 195 | 196 | if module.params['state'] == 'present': 197 | router_id = _get_router_id(module, neutron) 198 | if not router_id: 199 | router_id = _create_router(module, neutron) 200 | module.exit_json(changed=True, result="Created", id=router_id) 201 | else: 202 | module.exit_json(changed=False, result="success" , id=router_id) 203 | 204 | else: 205 | router_id = _get_router_id(module, neutron) 206 | if not router_id: 207 | module.exit_json(changed=False, result="success") 208 | else: 209 | _delete_router(module, neutron, router_id) 210 | module.exit_json(changed=True, result="deleted") 211 | 212 | # this is magic, see lib/ansible/module.params['common.py 213 | from ansible.module_utils.basic import * 214 | main() 215 | -------------------------------------------------------------------------------- /cinder_qos: -------------------------------------------------------------------------------- 1 | #!/bin/python 2 | 3 | from ansible.module_utils.basic import * 4 | try: 5 | from cinderclient.v2 import client 6 | except ImportError: 7 | print("failed=True msg='cinder client is required'") 8 | 9 | DOCUMENTATION = ''' 10 | --- 11 | module: cinder_configure 12 | short_description: Configure Openstack Block Storage (Cinder) 13 | description: Create QoS needed for deploying Cinder 14 | options: 15 | action: 16 | description: 17 | - The action corresponds to a Cinder qos command, such as cinder qos-create. 18 | required: true 19 | choices: [create, associate, disassociate, key] 20 | username: 21 | description: 22 | - username used to authenticate with keystone 23 | required: true 24 | password: 25 | description: 26 | - password used to authenticate with keystone 27 | required: true 28 | url_auth: 29 | description: 30 | - keystone url for authentication 31 | required: true 32 | tenant_name: 33 | description: 34 | - tenant name or project name of the login user 35 | required: true 36 | region_name: 37 | description: 38 | - region to connect to 39 | required: true 40 | name: 41 | description: 42 | - Name to be given to the QoS 43 | required: true 44 | extra_specs: 45 | description: 46 | - A dictionary of extra specs to add to the QoS 47 | required: true 48 | qos_volume_type: 49 | description: 50 | - The name of the volume-type to assign QoS to. 51 | required: true 52 | requirements: [ cinder ] 53 | author: Rodrigo Soto 54 | ''' 55 | 56 | EXAMPLES = ''' 57 | cinder_qos: 58 | action: create 59 | username: admin 60 | password: admin 61 | url_auth: "http://keystone/v2" 62 | tenant_name: admin 63 | region_name: RegionOne 64 | name: qos-test 65 | extra_specs: "test=hello,test2=world" 66 | qos_volume_type: some-type 67 | ''' 68 | 69 | def _get_cinderclient(module): 70 | try: 71 | cinder_client = client.Client( 72 | module.params.get('username'), 73 | module.params.get('password'), 74 | module.params.get('tenant_name'), 75 | module.params.get('url_auth'), 76 | region_name=module.params.get('region_name') 77 | ) 78 | except Exception as e: 79 | module.fail_json(msg="Error authenticating to cinder: %s" % e.message) 80 | return cinder_client 81 | 82 | def _get_qos_id(module, cinderclient): 83 | name = module.params.get('name') 84 | try: 85 | qos_list = cinderclient.qos_specs.list() 86 | for qos in qos_list: 87 | if qos.name == name: 88 | return qos.id 89 | except Exception: 90 | return None 91 | 92 | 93 | def _create_qos(module, cinderclient): 94 | name = module.params.get('name') 95 | extra_specs = module.params.get('extra_specs').split(',') 96 | extra_specs_dict = {} 97 | for extra_spec in extra_specs: 98 | key, value = extra_spec.split('=') 99 | extra_specs_dict[key] = value 100 | 101 | before = cinderclient.qos_specs.list() 102 | try: 103 | qos = cinderclient.qos_specs.create(name, extra_specs_dict) 104 | except Exception as e: 105 | module.fail_json(msg="Error creating qos: %s" % e.message) 106 | 107 | after = cinderclient.qos_specs.list() 108 | changes = _qos_changes(before, after) 109 | changed = True if changes else False 110 | results = {'action': 'create'} 111 | results.update(changes) 112 | return (changed, results) 113 | 114 | def _get_volume_type_id(module, cinderclient): 115 | name = module.params.get('qos_volume_type') 116 | type_list = cinderclient.volume_types.list() 117 | 118 | volume_type_id = '' 119 | try: 120 | for type in type_list: 121 | if type.name == name: 122 | volume_type_id = type.id 123 | except Exception as e: 124 | module.fail_json(msg="Error getting QoS Volume Type ID: %s" % e.message) 125 | 126 | return volume_type_id 127 | 128 | def _associate_qos(module, cinderclient): 129 | volume_type_id = _get_volume_type_id(module, cinderclient) 130 | qos_id = _get_qos_id(module, cinderclient) 131 | before = cinderclient.qos_specs.get_associations(qos_id) 132 | try: 133 | associate = cinderclient.qos_specs.associate(qos_id, volume_type_id) 134 | 135 | except Exception as e: 136 | module.fail_json(msg="Error associating qos: %s" % e.message) 137 | after = cinderclient.qos_specs.get_associations(qos_id) 138 | changes = _qos_changes(before, after) 139 | changed = True if changes else False 140 | results = {'action': 'associate'} 141 | results.update(changes) 142 | return (changed, results) 143 | 144 | def _disassociate_qos(module, cinderclient): 145 | volume_type_id = _get_volume_type_id(module, cinderclient) 146 | qos_id = _get_qos_id(module, cinderclient) 147 | 148 | before = cinderclient.qos_specs.get_associations(qos_id) 149 | 150 | try: 151 | cinderclient.qos_specs.disassociate(qos_id, volume_type_id) 152 | 153 | except Exception as e: 154 | module.fail_json(msg="Error disassociating qos: %s" % e.message) 155 | 156 | after = cinderclient.qos_specs.get_associations(qos_id) 157 | changes = _qos_changes(before, after) 158 | changed = True if changes else False 159 | results = {'action': 'disassociate'} 160 | results.update(changes) 161 | return (changed, results) 162 | 163 | 164 | def _set_qos_keys(module, cinderclient): 165 | volume_type_id = _get_volume_type_id(module, cinderclient) 166 | qos_id = _get_qos_id(module, cinderclient) 167 | name = module.params.get('name') 168 | extra_specs = module.params.get('extra_specs').split(',') 169 | extra_specs_dict = {} 170 | 171 | for extra_spec in extra_specs: 172 | key, value = extra_spec.split('=') 173 | extra_specs_dict[key] = value 174 | 175 | before = cinderclient.qos_specs.get(qos_id) 176 | try: 177 | cinderclient.qos_specs.set_keys(qos_id, extra_specs_dict) 178 | 179 | except Exception as e: 180 | module.fail_json(msg="Error setting key(s) for qos: %s" % e.message) 181 | 182 | after = cinderclient.qos_specs.get(qos_id) 183 | changes = _qos_changes(before, after) 184 | changed = True if changes else False 185 | results = {'action': 'set-key'} 186 | results.update(changes) 187 | return (changed, results) 188 | 189 | 190 | def _qos_changes(before, after): 191 | 192 | changes = {} 193 | 194 | if type(before) is list: 195 | if before == after: 196 | return changes 197 | else: 198 | changes['Changed']='True' 199 | return changes 200 | 201 | before_dict = {} 202 | for attr,value in before.__dict__.iteritems(): 203 | before_dict[attr] = value 204 | 205 | after_dict = {} 206 | for attr,value in after.__dict__.iteritems(): 207 | after_dict[attr] = value 208 | 209 | for key in before_dict: 210 | if before_dict[key] != after_dict[key]: 211 | changes[key] = after_dict[key] 212 | 213 | return changes 214 | 215 | def main(): 216 | module = AnsibleModule( 217 | argument_spec={ 218 | 'action': {'required': True, 'default': None}, 219 | 'username': {'required': True}, 220 | 'password': {'required': True}, 221 | 'url_auth': {'required': True}, 222 | 'tenant_name': {'required': True}, 223 | 'region_name': {'required': True}, 224 | 'name': {'required': True}, 225 | 'extra_specs': {'required': True}, 226 | 'qos_volume_type': {'required': True} 227 | }, 228 | ) 229 | cinderclient = _get_cinderclient(module) 230 | if module.params.get('action') == 'create': 231 | qos_id = _get_qos_id(module, cinderclient) 232 | if qos_id is None: 233 | changed, results = _create_qos(module, cinderclient) 234 | else: 235 | module.exit_json(changed=False, result="Success", msg=qos_id) 236 | 237 | elif module.params.get('action') == 'associate': 238 | qos_id = _get_qos_id(module, cinderclient) 239 | changed, results = _associate_qos(module, cinderclient) 240 | 241 | elif module.params.get('action') == 'key': 242 | qos_id = _get_qos_id(module, cinderclient) 243 | changed, results = _set_qos_keys(module, cinderclient) 244 | 245 | elif module.params.get('action') == 'disassociate': 246 | qos_id = _get_qos_id(module, cinderclient) 247 | changed, results = _disassociate_qos(module, cinderclient) 248 | 249 | module.exit_json(changed=changed, item=results) 250 | main() -------------------------------------------------------------------------------- /neutron_router_gateway: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding: utf-8 -*- 3 | 4 | # (c) 2013, Benno Joy 5 | # 6 | # This module is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | try: 20 | from neutronclient.neutron import client 21 | from keystoneclient.v2_0 import client as ksclient 22 | except ImportError: 23 | print("failed=True msg='neutronclient and keystone client are required'") 24 | DOCUMENTATION = ''' 25 | --- 26 | module: neutron_router_gateway 27 | version_added: "1.2" 28 | short_description: set/unset a gateway interface for the router with the specified external network 29 | description: 30 | - Creates/Removes a gateway interface from the router, used to associate a external network with a router to route external traffic. 31 | options: 32 | login_username: 33 | description: 34 | - login username to authenticate to keystone 35 | required: true 36 | default: admin 37 | login_password: 38 | description: 39 | - Password of login user 40 | required: true 41 | default: 'yes' 42 | login_tenant_name: 43 | description: 44 | - The tenant name of the login user 45 | required: true 46 | default: 'yes' 47 | auth_url: 48 | description: 49 | - The keystone URL for authentication 50 | required: false 51 | default: 'http://127.0.0.1:35357/v2.0/' 52 | region_name: 53 | description: 54 | - Name of the region 55 | required: false 56 | default: None 57 | state: 58 | description: 59 | - Indicate desired state of the resource 60 | choices: ['present', 'absent'] 61 | default: present 62 | router_name: 63 | description: 64 | - Name of the router to which the gateway should be attached. 65 | required: true 66 | default: None 67 | network_name: 68 | description: 69 | - Name of the external network which should be attached to the router. 70 | required: true 71 | default: None 72 | enable_snat: 73 | description: 74 | - Enable SNAT on traffic using this gateway (may require admin role). 75 | required: false 76 | default: true 77 | requirements: ["neutronclient", "keystoneclient"] 78 | ''' 79 | 80 | EXAMPLES = ''' 81 | # Attach an external network with a router to allow flow of external traffic 82 | - neutron_router_gateway: state=present login_username=admin login_password=admin 83 | login_tenant_name=admin router_name=external_router 84 | network_name=external_network 85 | ''' 86 | 87 | _os_keystone = None 88 | def _get_ksclient(module, kwargs): 89 | try: 90 | kclient = ksclient.Client( 91 | username=module.params.get('login_username'), 92 | password=module.params.get('login_password'), 93 | tenant_name=module.params.get('login_tenant_name'), 94 | auth_url=module.params.get('auth_url'), 95 | region_name=module.params.get('region_name')) 96 | except Exception as e: 97 | module.fail_json(msg = "Error authenticating to the keystone: %s " % e.message) 98 | global _os_keystone 99 | _os_keystone = kclient 100 | return kclient 101 | 102 | 103 | def _get_endpoint(module, ksclient): 104 | try: 105 | endpoint = ksclient.service_catalog.url_for(service_type='network', endpoint_type='publicURL') 106 | except Exception as e: 107 | module.fail_json(msg = "Error getting endpoint for glance: %s" % e.message) 108 | return endpoint 109 | 110 | def _get_neutron_client(module, kwargs): 111 | _ksclient = _get_ksclient(module, kwargs) 112 | token = _ksclient.auth_token 113 | endpoint = _get_endpoint(module, _ksclient) 114 | kwargs = { 115 | 'token': token, 116 | 'endpoint_url': endpoint 117 | } 118 | try: 119 | neutron = client.Client('2.0', **kwargs) 120 | except Exception as e: 121 | module.fail_json(msg = "Error in connecting to neutron: %s " % e.message) 122 | return neutron 123 | 124 | def _get_router(module, neutron): 125 | kwargs = { 126 | 'name': module.params['router_name'], 127 | } 128 | try: 129 | routers = neutron.list_routers(**kwargs) 130 | except Exception as e: 131 | module.fail_json(msg = "Error in getting the router list: %s " % e.message) 132 | if not routers['routers']: 133 | return None 134 | return routers['routers'][0] 135 | 136 | def _get_net_id(neutron, module): 137 | kwargs = { 138 | 'name': module.params['network_name'], 139 | 'router:external': True 140 | } 141 | try: 142 | networks = neutron.list_networks(**kwargs) 143 | except Exception as e: 144 | module.fail_json("Error in listing neutron networks: %s" % e.message) 145 | if not networks['networks']: 146 | return None 147 | return networks['networks'][0]['id'] 148 | 149 | def _add_gateway_router(neutron, module, router_id, network_id): 150 | kwargs = { 151 | 'network_id': network_id, 152 | 'enable_snat': module.params['enable_snat'] 153 | } 154 | 155 | try: 156 | neutron.add_gateway_router(router_id, kwargs) 157 | except Exception as e: 158 | module.fail_json(msg = "Error in adding gateway to router: %s" % e.message) 159 | return True 160 | 161 | def _remove_gateway_router(neutron, module, router_id): 162 | try: 163 | neutron.remove_gateway_router(router_id) 164 | except Exception as e: 165 | module.fail_json(msg = "Error in removing gateway to router: %s" % e.message) 166 | return True 167 | 168 | def main(): 169 | 170 | module = AnsibleModule( 171 | argument_spec = dict( 172 | login_username = dict(default='admin'), 173 | login_password = dict(required=True), 174 | login_tenant_name = dict(required='True'), 175 | auth_url = dict(default='http://127.0.0.1:35357/v2.0/'), 176 | region_name = dict(default=None), 177 | router_name = dict(required=True), 178 | network_name = dict(required=True), 179 | enable_snat = dict(default=True, type='bool'), 180 | state = dict(default='present', choices=['absent', 'present']), 181 | ), 182 | ) 183 | 184 | neutron = _get_neutron_client(module, module.params) 185 | router = _get_router(module, neutron) 186 | 187 | if not router: 188 | module.fail_json(msg="failed to get the router id, please check the router name") 189 | 190 | network_id = _get_net_id(neutron, module) 191 | if not network_id: 192 | module.fail_json(msg="failed to get the network id, please check the network name and make sure it is external") 193 | 194 | if module.params['state'] == 'present': 195 | if router.get('external_gateway_info') is None: 196 | _add_gateway_router(neutron, module, router['id'], network_id) 197 | module.exit_json(changed=True, updated=False, result="created") 198 | else: 199 | if router['external_gateway_info']['network_id'] == network_id \ 200 | and router['external_gateway_info']['enable_snat'] == \ 201 | module.params['enable_snat']: 202 | module.exit_json(changed=False, updated=False, result="success") 203 | elif router['external_gateway_info']['network_id'] == network_id: 204 | _add_gateway_router(neutron, module, router['id'], network_id) 205 | module.exit_json(changed=True, updated=True, result="updated") 206 | else: 207 | _remove_gateway_router(neutron, module, router['id']) 208 | _add_gateway_router(neutron, module, router['id'], network_id) 209 | module.exit_json(changed=True, updated=True, result="created") 210 | 211 | if module.params['state'] == 'absent': 212 | if router.get('external_gateway_info') is None: 213 | module.exit_json(changed=False, updated=False, result="success") 214 | else: 215 | _remove_gateway_router(neutron, module, router['id']) 216 | module.exit_json(changed=True, updated=False, result="deleted") 217 | 218 | # this is magic, see lib/ansible/module.params['common.py 219 | from ansible.module_utils.basic import * 220 | main() 221 | -------------------------------------------------------------------------------- /nova_flavor: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding: utf-8 -*- 3 | 4 | # https://github.com/openstack-ansible/openstack-ansible-modules/blob/master/nova_flavor 5 | 6 | # (c) 2014, Adam Samalik 7 | # 8 | # This module is free software: you can redistribute it and/or modify 9 | # it under the terms of the GNU General Public License as published by 10 | # the Free Software Foundation, either version 3 of the License, or 11 | # (at your option) any later version. 12 | # 13 | # This software is distributed in the hope that it will be useful, 14 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 15 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | # GNU General Public License for more details. 17 | # 18 | # You should have received a copy of the GNU General Public License 19 | # along with this software. If not, see . 20 | 21 | try: 22 | from novaclient import client 23 | from keystoneclient.v2_0 import client as ksclient 24 | except ImportError: 25 | print("failed=True msg='novaclient and keystone client are required'") 26 | 27 | DOCUMENTATION = ''' 28 | --- 29 | module: nova_flavor 30 | short_description: Manage OpenStack flavors 31 | description: 32 | - Create VM flavors with OpenStack Nova service 33 | requirements: [ python-novaclient ] 34 | options: 35 | login_username: 36 | description: 37 | - user name to authenticate against Identity service 38 | required: True 39 | aliases: [username] 40 | login_password: 41 | description: 42 | - password to authenticate against Identity service 43 | aliases: [password] 44 | required: True 45 | login_tenant_name: 46 | description: 47 | - tenant name of the login user 48 | aliases: [tenant_name] 49 | required: True 50 | auth_url: 51 | description: 52 | - The keystone URL for authentication 53 | required: false 54 | default: 'http://127.0.0.1:35357/v2.0/' 55 | region_name: 56 | description: 57 | - Name of the region 58 | required: False 59 | default: None 60 | name: 61 | description: 62 | - Descriptive name of the flavor 63 | required: True 64 | ram: 65 | description: 66 | - Memory in MB for the flavor 67 | required: False 68 | vcpus: 69 | description: 70 | - Number of VCPUs for the flavor 71 | required: False 72 | root: 73 | description: 74 | - Size of root disk in GB 75 | required: False 76 | ephemeral: 77 | description: 78 | - Size of ephemeral space in GB 79 | required: False 80 | swap: 81 | description: 82 | - Swap space in MB 83 | required: False 84 | default: 0 85 | id: 86 | description: 87 | - ID for the flavor (optional). 88 | required: False 89 | default: ID will be automatically generated 90 | is_public: 91 | description: 92 | - Decide if the flavor is public 93 | choices: ['true', 'false'] 94 | default: 'true' 95 | extra_specs: 96 | description: 97 | - Metadata used by scheduling to select correct host aggregate 98 | default: None 99 | state: 100 | description: 101 | - Create or delete flavor 102 | required: False 103 | choices: ['present', 'absent'] 104 | default: 'present' 105 | ''' 106 | 107 | EXAMPLES = ''' 108 | - nova_flavor: 109 | login_username: admin 110 | login_password: 1234 111 | login_tenant_name: admin 112 | name: medium 113 | ram: 2048 114 | vcpus: 2 115 | root: 0 116 | ephemeral: 20 117 | ''' 118 | 119 | def authenticate(module, auth_url, username, password, tenant_name, region): 120 | """ 121 | Return a Nova client object. 122 | """ 123 | try: 124 | keystone = ksclient.Client(auth_url=auth_url, 125 | username=username, 126 | password=password, 127 | tenant_name=tenant_name, 128 | region=region) 129 | except Exception as e: 130 | module.fail_json( 131 | msg = "Could not authenticate with Keystone: {}".format( 132 | e.message)) 133 | 134 | try: 135 | nova = client.Client('2', keystone.username, 136 | keystone.password, 137 | keystone.tenant_name, 138 | keystone.auth_url) 139 | except Exception as e: 140 | module.fail_json(msg = "Could not get Nova client: {}".format( 141 | e.message)) 142 | 143 | return nova 144 | 145 | def get_flavors(nova, name, id=None): 146 | if not id: 147 | flavors = [x for x in nova.flavors.list() if x.name == name] 148 | else: 149 | flavors = [x for x in nova.flavors.list() if x.name == name and x.id == str(id)] 150 | return flavors 151 | 152 | def create_flavor(module, nova, name, ram, vcpus, root, ephemeral, swap, id, is_public, extra_specs): 153 | flavors = get_flavors(nova, name, id) 154 | if len(flavors) >0: 155 | present_flavor = flavors[0] 156 | # When flavor is created with 0 swap, nova will use an empty value 157 | if present_flavor.swap == "": 158 | present_flavor.swap = 0 159 | # flavor create expects lower case is_public values, but converts them into capitalized value 160 | if present_flavor.ram == int(ram) and present_flavor.vcpus == int(vcpus) and present_flavor.disk == int(root) and present_flavor.ephemeral == int(ephemeral) and present_flavor.swap == int(swap) and str(present_flavor.is_public) == is_public.capitalize(): 161 | if present_flavor.get_keys() == extra_specs: 162 | return False, flavors[0].id 163 | else: 164 | present_flavor.set_keys(extra_specs) 165 | return True, flavors[0].id 166 | else: 167 | module.fail_json(msg = "Flavor {0} already present, but specs have changed!".format(name)) 168 | 169 | try: 170 | flavor = nova.flavors.create(name=name, ram=ram, vcpus=vcpus, disk=root, ephemeral=ephemeral, flavorid=id, swap=swap, is_public=is_public) 171 | flavor.set_keys(extra_specs) 172 | except Exception as e: 173 | module.fail_json(msg = "Could not create a flavor: {0}".format(e.message)) 174 | 175 | return True, flavor.id 176 | 177 | def delete_flavor(module, nova, name): 178 | flavors = get_flavors(nova, name) 179 | if len(flavors) == 0: 180 | return False 181 | for flavor in flavors: 182 | try: 183 | nova.flavors.delete(flavor.id); 184 | except Exception as e: 185 | module.fail_json(msg = "Could not delete flavor {0}: {1}".format(name, e.message)) 186 | 187 | return True 188 | 189 | def main(): 190 | module = AnsibleModule( 191 | argument_spec = dict( 192 | login_username = dict(default='admin', aliases=["username"]), 193 | login_password = dict(required=True, aliases=["password"]), 194 | login_tenant_name = dict(required='True', aliases=["tenant_name"]), 195 | auth_url = dict(default='http://127.0.0.1:35357/v2.0/'), 196 | region_name = dict(default=None), 197 | name = dict(required=True), 198 | ram = dict(required=False,default=0), 199 | vcpus = dict(required=False,default=0), 200 | root = dict(required=False,default=0), 201 | ephemeral = dict(required=False,default=0), 202 | extra_specs = dict(required=False,default={},type='dict'), 203 | swap = dict(default=0), 204 | id = dict(default=None), 205 | is_public = dict(default='true'), 206 | state = dict(default='present'), 207 | ) 208 | ) 209 | auth_url = module.params['auth_url'] 210 | region = module.params['region_name'] 211 | username = module.params['login_username'] 212 | password = module.params['login_password'] 213 | tenant_name = module.params['login_tenant_name'] 214 | name = module.params['name'] 215 | ram = module.params['ram'] 216 | vcpus = module.params['vcpus'] 217 | root = module.params['root'] 218 | ephemeral = module.params['ephemeral'] 219 | extra_specs = module.params['extra_specs'] 220 | swap = module.params['swap'] 221 | id = module.params['id'] 222 | state = module.params['state'] 223 | is_public = module.params['is_public'] 224 | 225 | nova = authenticate(module, auth_url, username, password, tenant_name, region) 226 | 227 | if state == 'present': 228 | changed, id = create_flavor(module, nova, name, ram, vcpus, root, ephemeral, swap, id, 229 | is_public, extra_specs) 230 | module.exit_json(changed=changed, name=name, id=id) 231 | elif state == 'absent': 232 | changed = delete_flavor(module, nova, name) 233 | module.exit_json(changed=changed, name=name) 234 | else: 235 | raise ValueError("Code should never reach here") 236 | 237 | 238 | 239 | # this is magic, see lib/ansible/module_common.py 240 | #<> 241 | if __name__ == '__main__': 242 | main() 243 | -------------------------------------------------------------------------------- /neutron_router_interface: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding: utf-8 -*- 3 | 4 | # (c) 2013, Benno Joy 5 | # 6 | # This module is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | try: 20 | from neutronclient.neutron import client 21 | from keystoneclient.v2_0 import client as ksclient 22 | except ImportError: 23 | print("failed=True msg='neutronclient and keystone client are required'") 24 | DOCUMENTATION = ''' 25 | --- 26 | module: neutron_router_interface 27 | version_added: "1.2" 28 | short_description: Attach/Dettach a subnet's interface to a router 29 | description: 30 | - Attach/Dettach a subnet interface to a router, to provide a gateway for the subnet. 31 | options: 32 | login_username: 33 | description: 34 | - login username to authenticate to keystone 35 | required: true 36 | default: admin 37 | login_password: 38 | description: 39 | - Password of login user 40 | required: true 41 | default: 'yes' 42 | login_tenant_name: 43 | description: 44 | - The tenant name of the login user 45 | required: true 46 | default: 'yes' 47 | auth_url: 48 | description: 49 | - The keystone URL for authentication 50 | required: false 51 | default: 'http://127.0.0.1:35357/v2.0/' 52 | region_name: 53 | description: 54 | - Name of the region 55 | required: false 56 | default: None 57 | state: 58 | description: 59 | - Indicate desired state of the resource 60 | choices: ['present', 'absent'] 61 | default: present 62 | router_name: 63 | description: 64 | - Name of the router to which the subnet's interface should be attached. 65 | required: true 66 | default: None 67 | subnet_name: 68 | description: 69 | - Name of the subnet to whose interface should be attached to the router. 70 | required: true 71 | default: None 72 | tenant_name: 73 | description: 74 | - Name of the tenant whose subnet has to be attached. 75 | required: false 76 | default: None 77 | requirements: ["neutronclient", "keystoneclient"] 78 | ''' 79 | 80 | EXAMPLES = ''' 81 | # Attach tenant1's subnet to the external router 82 | - neutron_router_interface: state=present login_username=admin 83 | login_password=admin 84 | login_tenant_name=admin 85 | tenant_name=tenant1 86 | router_name=external_route 87 | subnet_name=t1subnet 88 | ''' 89 | 90 | 91 | _os_keystone = None 92 | _os_tenant_id = None 93 | 94 | def _get_ksclient(module, kwargs): 95 | try: 96 | kclient = ksclient.Client( 97 | username=module.params.get('login_username'), 98 | password=module.params.get('login_password'), 99 | tenant_name=module.params.get('login_tenant_name'), 100 | auth_url=module.params.get('auth_url'), 101 | region_name=module.params.get('region_name')) 102 | except Exception as e: 103 | module.fail_json(msg = "Error authenticating to the keystone: %s " % e.message) 104 | global _os_keystone 105 | _os_keystone = kclient 106 | return kclient 107 | 108 | 109 | def _get_endpoint(module, ksclient): 110 | try: 111 | endpoint = ksclient.service_catalog.url_for(service_type='network', endpoint_type='publicURL') 112 | except Exception as e: 113 | module.fail_json(msg = "Error getting endpoint for glance: %s" % e.message) 114 | return endpoint 115 | 116 | def _get_neutron_client(module, kwargs): 117 | _ksclient = _get_ksclient(module, kwargs) 118 | token = _ksclient.auth_token 119 | endpoint = _get_endpoint(module, _ksclient) 120 | kwargs = { 121 | 'token': token, 122 | 'endpoint_url': endpoint 123 | } 124 | try: 125 | neutron = client.Client('2.0', **kwargs) 126 | except Exception as e: 127 | module.fail_json(msg = "Error in connecting to neutron: %s " % e.message) 128 | return neutron 129 | 130 | def _set_tenant_id(module): 131 | global _os_tenant_id 132 | if module.params['tenant_name']: 133 | # We need admin power in order retrieve the tenant_id of a given 134 | # tenant name and to create/delete networks for a tenant that is not 135 | # the one used to authenticate the user. 136 | tenant_name = module.params['tenant_name'] 137 | for tenant in _os_keystone.tenants.list(): 138 | if tenant.name == tenant_name: 139 | _os_tenant_id = tenant.id 140 | break 141 | else: 142 | _os_tenant_id = _os_keystone.tenant_id 143 | 144 | if not _os_tenant_id: 145 | module.fail_json(msg = "The tenant id cannot be found, please check the paramters") 146 | 147 | def _get_router_id(module, neutron): 148 | kwargs = { 149 | 'name': module.params['router_name'], 150 | } 151 | try: 152 | routers = neutron.list_routers(**kwargs) 153 | except Exception as e: 154 | module.fail_json(msg = "Error in getting the router list: %s " % e.message) 155 | if not routers['routers']: 156 | return None 157 | return routers['routers'][0]['id'] 158 | 159 | 160 | def _get_subnet_id(module, neutron): 161 | subnet_id = None 162 | kwargs = { 163 | 'tenant_id': _os_tenant_id, 164 | 'name': module.params['subnet_name'], 165 | } 166 | try: 167 | subnets = neutron.list_subnets(**kwargs) 168 | except Exception as e: 169 | module.fail_json( msg = " Error in getting the subnet list:%s " % e.message) 170 | if not subnets['subnets']: 171 | return None 172 | return subnets['subnets'][0]['id'] 173 | 174 | def _get_port_id(neutron, module, router_id, subnet_id): 175 | kwargs = { 176 | 'tenant_id': _os_tenant_id, 177 | 'device_id': router_id, 178 | } 179 | try: 180 | ports = neutron.list_ports(**kwargs) 181 | except Exception as e: 182 | module.fail_json( msg = "Error in listing ports: %s" % e.message) 183 | if not ports['ports']: 184 | return None 185 | for port in ports['ports']: 186 | for subnet in port['fixed_ips']: 187 | if subnet['subnet_id'] == subnet_id: 188 | return port['id'] 189 | return None 190 | 191 | def _add_interface_router(neutron, module, router_id, subnet_id): 192 | kwargs = { 193 | 'subnet_id': subnet_id 194 | } 195 | try: 196 | neutron.add_interface_router(router_id, kwargs) 197 | except Exception as e: 198 | module.fail_json(msg = "Error in adding interface to router: %s" % e.message) 199 | return True 200 | 201 | def _remove_interface_router(neutron, module, router_id, subnet_id): 202 | kwargs = { 203 | 'subnet_id': subnet_id 204 | } 205 | try: 206 | neutron.remove_interface_router(router_id, kwargs) 207 | except Exception as e: 208 | module.fail_json(msg="Error in removing interface from router: %s" % e.message) 209 | return True 210 | 211 | def main(): 212 | module = AnsibleModule( 213 | argument_spec = dict( 214 | login_username = dict(default='admin'), 215 | login_password = dict(required=True), 216 | login_tenant_name = dict(required='True'), 217 | auth_url = dict(default='http://127.0.0.1:35357/v2.0/'), 218 | region_name = dict(default=None), 219 | router_name = dict(required=True), 220 | subnet_name = dict(required=True), 221 | tenant_name = dict(default=None), 222 | state = dict(default='present', choices=['absent', 'present']), 223 | ), 224 | ) 225 | 226 | neutron = _get_neutron_client(module, module.params) 227 | _set_tenant_id(module) 228 | 229 | router_id = _get_router_id(module, neutron) 230 | if not router_id: 231 | module.fail_json(msg="failed to get the router id, please check the router name") 232 | 233 | subnet_id = _get_subnet_id(module, neutron) 234 | if not subnet_id: 235 | module.fail_json(msg="failed to get the subnet id, please check the subnet name") 236 | 237 | if module.params['state'] == 'present': 238 | port_id = _get_port_id(neutron, module, router_id, subnet_id) 239 | if not port_id: 240 | _add_interface_router(neutron, module, router_id, subnet_id) 241 | module.exit_json(changed=True, result="created", id=port_id) 242 | module.exit_json(changed=False, result="success", id=port_id) 243 | 244 | if module.params['state'] == 'absent': 245 | port_id = _get_port_id(neutron, module, router_id, subnet_id) 246 | if not port_id: 247 | module.exit_json(changed = False, result = "Success") 248 | _remove_interface_router(neutron, module, router_id, subnet_id) 249 | module.exit_json(changed=True, result="Deleted") 250 | 251 | # this is magic, see lib/ansible/module.params['common.py 252 | from ansible.module_utils.basic import * 253 | main() 254 | -------------------------------------------------------------------------------- /neutron_network: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding: utf-8 -*- 3 | 4 | # (c) 2013, Benno Joy 5 | # 6 | # This module is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | try: 20 | from neutronclient.neutron import client 21 | from keystoneclient.v2_0 import client as ksclient 22 | except ImportError: 23 | print("failed=True msg='neutronclient and keystone client are required'") 24 | 25 | DOCUMENTATION = ''' 26 | --- 27 | module: neutron_network 28 | version_added: "1.4" 29 | short_description: Creates/Removes networks from OpenStack 30 | description: 31 | - Add or Remove network from OpenStack. 32 | options: 33 | login_username: 34 | description: 35 | - login username to authenticate to keystone 36 | required: true 37 | default: admin 38 | login_password: 39 | description: 40 | - Password of login user 41 | required: true 42 | default: 'yes' 43 | login_tenant_name: 44 | description: 45 | - The tenant name of the login user 46 | required: true 47 | default: 'yes' 48 | tenant_name: 49 | description: 50 | - The name of the tenant for whom the network is created 51 | required: false 52 | default: None 53 | auth_url: 54 | description: 55 | - The keystone url for authentication 56 | required: false 57 | default: 'http://127.0.0.1:35357/v2.0/' 58 | region_name: 59 | description: 60 | - Name of the region 61 | required: false 62 | default: None 63 | state: 64 | description: 65 | - Indicate desired state of the resource 66 | choices: ['present', 'absent'] 67 | default: present 68 | name: 69 | description: 70 | - Name to be assigned to the nework 71 | required: true 72 | default: None 73 | provider_network_type: 74 | description: 75 | - The type of the network to be created, gre, vxlan, vlan, local. Available types depend on the plugin. The Neutron service decides if not specified. 76 | required: false 77 | default: None 78 | provider_physical_network: 79 | description: 80 | - The physical network which would realize the virtual network for flat and vlan networks. 81 | required: false 82 | default: None 83 | provider_segmentation_id: 84 | description: 85 | - The id that has to be assigned to the network, in case of vlan networks that would be vlan id, for gre the tunnel id and for vxlan the VNI. 86 | required: false 87 | default: None 88 | router_external: 89 | description: 90 | - If 'yes', specifies that the virtual network is a external network (public). 91 | required: false 92 | default: false 93 | shared: 94 | description: 95 | - Whether this network is shared or not 96 | required: false 97 | default: false 98 | admin_state_up: 99 | description: 100 | - Whether the state should be marked as up or down 101 | required: false 102 | default: true 103 | requirements: ["neutronclient", "keystoneclient"] 104 | 105 | ''' 106 | 107 | EXAMPLES = ''' 108 | # Create a GRE backed Neutron network with tunnel id 1 for tenant1 109 | - neutron_network: name=t1network tenant_name=tenant1 state=present 110 | provider_network_type=gre provider_segmentation_id=1 111 | login_username=admin login_password=admin login_tenant_name=admin 112 | 113 | # Create an external network 114 | - neutron_network: name=external_network state=present 115 | provider_network_type=local router_external=yes 116 | login_username=admin login_password=admin login_tenant_name=admin 117 | ''' 118 | 119 | _os_keystone = None 120 | _os_tenant_id = None 121 | 122 | def _get_ksclient(module, kwargs): 123 | try: 124 | kclient = ksclient.Client( 125 | username=module.params.get('login_username'), 126 | password=module.params.get('login_password'), 127 | tenant_name=module.params.get('login_tenant_name'), 128 | auth_url=module.params.get('auth_url'), 129 | region_name=module.params.get('region_name')) 130 | except Exception as e: 131 | module.fail_json(msg = "Error authenticating to the keystone: %s" %e.message) 132 | global _os_keystone 133 | _os_keystone = kclient 134 | return kclient 135 | 136 | 137 | def _get_endpoint(module, ksclient): 138 | try: 139 | endpoint = ksclient.service_catalog.url_for(service_type='network', endpoint_type='publicURL') 140 | except Exception as e: 141 | module.fail_json(msg = "Error getting endpoint for Neutron: %s " %e.message) 142 | return endpoint 143 | 144 | def _get_neutron_client(module, kwargs): 145 | _ksclient = _get_ksclient(module, kwargs) 146 | token = _ksclient.auth_token 147 | endpoint = _get_endpoint(module, _ksclient) 148 | kwargs = { 149 | 'token': token, 150 | 'endpoint_url': endpoint 151 | } 152 | try: 153 | neutron = client.Client('2.0', **kwargs) 154 | except Exception as e: 155 | module.fail_json(msg = " Error in connecting to Neutron: %s " %e.message) 156 | return neutron 157 | 158 | def _set_tenant_id(module): 159 | global _os_tenant_id 160 | if module.params['tenant_name']: 161 | # We need admin power in order retrieve the tenant_id of a given 162 | # tenant name and to create/delete networks for a tenant that is not 163 | # the one used to authenticate the user. 164 | tenant_name = module.params['tenant_name'] 165 | for tenant in _os_keystone.tenants.list(): 166 | if tenant.name == tenant_name: 167 | _os_tenant_id = tenant.id 168 | break 169 | else: 170 | _os_tenant_id = _os_keystone.tenant_id 171 | 172 | if not _os_tenant_id: 173 | module.fail_json(msg = "The tenant id cannot be found, please check the paramters") 174 | 175 | 176 | def _get_net_id(neutron, module): 177 | kwargs = { 178 | 'tenant_id': _os_tenant_id, 179 | 'name': module.params['name'], 180 | } 181 | try: 182 | networks = neutron.list_networks(**kwargs) 183 | except Exception as e: 184 | module.fail_json(msg = "Error in listing Neutron networks: %s" % e.message) 185 | if not networks['networks']: 186 | return None 187 | return networks['networks'][0]['id'] 188 | 189 | def _create_network(module, neutron): 190 | 191 | neutron.format = 'json' 192 | 193 | network = { 194 | 'name': module.params.get('name'), 195 | 'tenant_id': _os_tenant_id, 196 | 'provider:network_type': module.params.get('provider_network_type'), 197 | 'provider:physical_network': module.params.get('provider_physical_network'), 198 | 'provider:segmentation_id': module.params.get('provider_segmentation_id'), 199 | 'shared': module.params.get('shared'), 200 | 'admin_state_up': module.params.get('admin_state_up'), 201 | } 202 | 203 | # Older neutron versions wil reject explicitly router:external set 204 | # to false 205 | if module.params.get('router_external'): 206 | network['router:external'] = True 207 | 208 | if module.params['provider_network_type'] == 'local': 209 | network.pop('provider:physical_network', None) 210 | network.pop('provider:segmentation_id', None) 211 | 212 | if module.params['provider_network_type'] == 'flat': 213 | network.pop('provider:segmentation_id', None) 214 | 215 | if module.params['provider_network_type'] == 'gre': 216 | network.pop('provider:physical_network', None) 217 | 218 | if module.params['provider_network_type'] == 'vxlan': 219 | network.pop('provider:physical_network', None) 220 | 221 | if module.params['provider_network_type'] is None: 222 | network.pop('provider:network_type', None) 223 | network.pop('provider:physical_network', None) 224 | network.pop('provider:segmentation_id', None) 225 | 226 | try: 227 | net = neutron.create_network({'network':network}) 228 | except Exception as e: 229 | module.fail_json(msg = "Error in creating network: %s" % e.message) 230 | return net['network']['id'] 231 | 232 | def _delete_network(module, net_id, neutron): 233 | 234 | try: 235 | id = neutron.delete_network(net_id) 236 | except Exception as e: 237 | module.fail_json(msg = "Error in deleting the network: %s" % e.message) 238 | return True 239 | 240 | def main(): 241 | 242 | module = AnsibleModule( 243 | argument_spec = dict( 244 | login_username = dict(default='admin'), 245 | login_password = dict(required=True), 246 | login_tenant_name = dict(required='True'), 247 | auth_url = dict(default='http://127.0.0.1:35357/v2.0/'), 248 | region_name = dict(default=None), 249 | name = dict(required=True), 250 | tenant_name = dict(default=None), 251 | provider_network_type = dict(default=None, choices=['local', 'vlan', 'flat', 'gre', 'vxlan']), 252 | provider_physical_network = dict(default=None), 253 | provider_segmentation_id = dict(default=None), 254 | router_external = dict(default=False, type='bool'), 255 | shared = dict(default=False, type='bool'), 256 | admin_state_up = dict(default=True, type='bool'), 257 | state = dict(default='present', choices=['absent', 'present']) 258 | ), 259 | ) 260 | 261 | if module.params['provider_network_type'] in ['vlan' , 'flat']: 262 | if not module.params['provider_physical_network']: 263 | module.fail_json(msg = " for vlan and flat networks, variable provider_physical_network should be set.") 264 | 265 | if module.params['provider_network_type'] in ['vlan', 'gre', 'vxlan']: 266 | if not module.params['provider_segmentation_id']: 267 | module.fail_json(msg = " for vlan, gre & vxlan networks, variable provider_segmentation_id should be set.") 268 | 269 | neutron = _get_neutron_client(module, module.params) 270 | 271 | _set_tenant_id(module) 272 | 273 | if module.params['state'] == 'present': 274 | network_id = _get_net_id(neutron, module) 275 | if not network_id: 276 | network_id = _create_network(module, neutron) 277 | module.exit_json(changed = True, result = "Created", id = network_id) 278 | else: 279 | module.exit_json(changed = False, result = "Success", id = network_id) 280 | 281 | if module.params['state'] == 'absent': 282 | network_id = _get_net_id(neutron, module) 283 | if not network_id: 284 | module.exit_json(changed = False, result = "Success") 285 | else: 286 | _delete_network(module, network_id, neutron) 287 | module.exit_json(changed = True, result = "Deleted") 288 | 289 | # this is magic, see lib/ansible/module.params['common.py 290 | from ansible.module_utils.basic import * 291 | main() 292 | -------------------------------------------------------------------------------- /neutron_floating_ip: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding: utf-8 -*- 3 | 4 | # (c) 2013, Benno Joy 5 | # 6 | # This module is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | try: 20 | from novaclient.v1_1 import client as nova_client 21 | from neutronclient.neutron import client 22 | from keystoneclient.v2_0 import client as ksclient 23 | import time 24 | except ImportError: 25 | print("failed=True msg='glanceclient,keystoneclient and neutronclient client are required'") 26 | 27 | DOCUMENTATION = ''' 28 | --- 29 | module: neutron_floating_ip 30 | version_added: "1.2" 31 | short_description: Add/Remove floating IP from an instance 32 | description: 33 | - Add or Remove a floating IP to an instance 34 | options: 35 | login_username: 36 | description: 37 | - login username to authenticate to keystone 38 | required: true 39 | default: admin 40 | login_password: 41 | description: 42 | - Password of login user 43 | required: true 44 | default: 'yes' 45 | login_tenant_name: 46 | description: 47 | - The tenant name of the login user 48 | required: true 49 | default: 'yes' 50 | auth_url: 51 | description: 52 | - The keystone url for authentication 53 | required: false 54 | default: 'http://127.0.0.1:35357/v2.0/' 55 | region_name: 56 | description: 57 | - Name of the region 58 | required: false 59 | default: None 60 | state: 61 | description: 62 | - Indicate desired state of the resource 63 | choices: ['present', 'absent'] 64 | default: present 65 | network_name: 66 | description: 67 | - Name of the network from which IP has to be assigned to VM. Please make sure the network is an external network 68 | required: true 69 | default: None 70 | port_network_name: 71 | description: 72 | - Name of the network where the VM port lives. Useful when the VM has more than one port 73 | required: false 74 | default: None 75 | instance_name: 76 | description: 77 | - The name of the instance to which the IP address should be assigned 78 | required: true 79 | default: None 80 | fixed_ip: 81 | description: 82 | - IP address on the instance's port. Useful when the port has more than one IP 83 | required: false 84 | default: None 85 | requirements: ["novaclient", "neutronclient", "keystoneclient"] 86 | ''' 87 | 88 | EXAMPLES = ''' 89 | # Assign a floating ip to the instance from an external network 90 | - neutron_floating_ip: state=present login_username=admin login_password=admin 91 | login_tenant_name=admin network_name=external_network 92 | instance_name=vm1 93 | ''' 94 | 95 | def _get_ksclient(module, kwargs): 96 | try: 97 | kclient = ksclient.Client( 98 | username=module.params.get('login_username'), 99 | password=module.params.get('login_password'), 100 | tenant_name=module.params.get('login_tenant_name'), 101 | auth_url=module.params.get('auth_url'), 102 | region_name=module.params.get('region_name')) 103 | except Exception as e: 104 | module.fail_json(msg = "Error authenticating to the keystone: %s " % e.message) 105 | global _os_keystone 106 | _os_keystone = kclient 107 | return kclient 108 | 109 | 110 | def _get_endpoint(module, ksclient): 111 | try: 112 | endpoint = ksclient.service_catalog.url_for(service_type='network', endpoint_type='publicURL') 113 | except Exception as e: 114 | module.fail_json(msg = "Error getting endpoint for glance: %s" % e.message) 115 | return endpoint 116 | 117 | def _get_neutron_client(module, kwargs): 118 | _ksclient = _get_ksclient(module, kwargs) 119 | token = _ksclient.auth_token 120 | endpoint = _get_endpoint(module, _ksclient) 121 | kwargs = { 122 | 'token': token, 123 | 'endpoint_url': endpoint 124 | } 125 | try: 126 | neutron = client.Client('2.0', **kwargs) 127 | except Exception as e: 128 | module.fail_json(msg = "Error in connecting to neutron: %s " % e.message) 129 | return neutron 130 | 131 | def _get_server_state(module, nova): 132 | server_info = None 133 | server = None 134 | try: 135 | for server in nova.servers.list(): 136 | if server: 137 | info = server._info 138 | if info['name'] == module.params['instance_name']: 139 | if info['status'] != 'ACTIVE' and module.params['state'] == 'present': 140 | module.fail_json( msg="The VM is available but not Active. state:" + info['status']) 141 | server_info = info 142 | break 143 | except Exception as e: 144 | module.fail_json(msg = "Error in getting the server list: %s" % e.message) 145 | return server_info, server 146 | 147 | def _get_port_info(neutron, module, instance_id): 148 | if module.params['port_network_name'] is None: 149 | kwargs = { 150 | 'device_id': instance_id 151 | } 152 | else: 153 | network_id = _get_net_id(neutron, module.params['port_network_name']) 154 | if not network_id: 155 | module.fail_json(msg = "cannot find the network specified, please check") 156 | 157 | kwargs = { 158 | 'device_id': instance_id, 159 | 'network_id': network_id 160 | } 161 | try: 162 | ports = neutron.list_ports(**kwargs) 163 | except Exception as e: 164 | module.fail_json( msg = "Error in listing ports: %s" % e.message) 165 | if not ports['ports']: 166 | return None, None 167 | return ports['ports'][0]['fixed_ips'][0]['ip_address'], ports['ports'][0]['id'] 168 | 169 | def _get_floating_ip(module, neutron, fixed_ip_address): 170 | kwargs = { 171 | 'fixed_ip_address': fixed_ip_address 172 | } 173 | try: 174 | ips = neutron.list_floatingips(**kwargs) 175 | except Exception as e: 176 | module.fail_json(msg = "error in fetching the floatingips's %s" % e.message) 177 | if not ips['floatingips']: 178 | return None, None 179 | return ips['floatingips'][0]['id'], ips['floatingips'][0]['floating_ip_address'] 180 | 181 | def _get_tenant_id(module): 182 | tenants = _get_ksclient(module, {}).tenants.list() 183 | tenant = next((t for t in tenants if t.name == module.params.get('login_tenant_name')), None) 184 | return tenant.id 185 | 186 | def _assign_floating_ip(neutron, module, port_id, net_id): 187 | kwargs = { 188 | 'floating_network_id': net_id 189 | } 190 | try: 191 | ips = neutron.list_floatingips(**kwargs) 192 | except Exception as e: 193 | module.fail_json(msg = "error in fetching the floatingips's %s" % e.message) 194 | 195 | tenant_id = _get_tenant_id(module) 196 | fip = next((fip for fip in ips['floatingips'] if fip['port_id'] is None and fip['tenant_id'] == tenant_id), None) 197 | 198 | if fip is None: 199 | _create_floating_ip(neutron, module, port_id, net_id) 200 | else: 201 | _update_floating_ip(neutron, module, port_id, fip['id']) 202 | 203 | def _create_floating_ip(neutron, module, port_id, net_id): 204 | kwargs = { 205 | 'port_id': port_id, 206 | 'floating_network_id': net_id 207 | } 208 | if 'fixed_ip' in module.params: 209 | kwargs['fixed_ip_address'] = module.params['fixed_ip'] 210 | try: 211 | result = neutron.create_floatingip({'floatingip': kwargs}) 212 | except Exception as e: 213 | module.fail_json(msg="There was an error in updating the floating ip address: %s" % e.message) 214 | module.exit_json(changed=True, result=result, public_ip=result['floatingip']['floating_ip_address']) 215 | 216 | def _get_net_id(neutron, network_name): 217 | kwargs = { 218 | 'name': network_name, 219 | } 220 | try: 221 | networks = neutron.list_networks(**kwargs) 222 | except Exception as e: 223 | module.fail_json("Error in listing neutron networks: %s" % e.message) 224 | if not networks['networks']: 225 | return None 226 | return networks['networks'][0]['id'] 227 | 228 | def _update_floating_ip(neutron, module, port_id, floating_ip_id): 229 | kwargs = { 230 | 'port_id': port_id 231 | } 232 | try: 233 | result = neutron.update_floatingip(floating_ip_id, {'floatingip': kwargs}) 234 | except Exception as e: 235 | module.fail_json(msg="There was an error in updating the floating ip address: %s" % e.message) 236 | module.exit_json(changed=True, result=result, public_ip=result['floatingip']['floating_ip_address']) 237 | 238 | 239 | def main(): 240 | 241 | module = AnsibleModule( 242 | argument_spec = dict( 243 | login_username = dict(default='admin'), 244 | login_password = dict(required=True), 245 | login_tenant_name = dict(required='True'), 246 | auth_url = dict(default='http://127.0.0.1:35357/v2.0/'), 247 | region_name = dict(default=None), 248 | network_name = dict(required=True), 249 | instance_name = dict(required=True), 250 | port_network_name = dict(default=None), 251 | fixed_ip = dict(default=None), 252 | state = dict(default='present', choices=['absent', 'present']) 253 | ), 254 | ) 255 | 256 | try: 257 | nova = nova_client.Client(module.params['login_username'], module.params['login_password'], 258 | module.params['login_tenant_name'], module.params['auth_url'], service_type='compute', 259 | region_name=module.params.get('region_name')) 260 | neutron = _get_neutron_client(module, module.params) 261 | except Exception as e: 262 | module.fail_json(msg="Error in authenticating to nova: %s" % e.message) 263 | 264 | server_info, server_obj = _get_server_state(module, nova) 265 | if not server_info: 266 | module.fail_json(msg="The instance name provided cannot be found") 267 | 268 | fixed_ip, port_id = _get_port_info(neutron, module, server_info['id']) 269 | if not port_id: 270 | module.fail_json(msg="Cannot find a port for this instance, maybe fixed ip is not assigned") 271 | 272 | floating_id, floating_ip = _get_floating_ip(module, neutron, fixed_ip) 273 | 274 | if module.params['state'] == 'present': 275 | if floating_ip: 276 | module.exit_json(changed = False, public_ip=floating_ip) 277 | net_id = _get_net_id(neutron, module.params['network_name']) 278 | if not net_id: 279 | module.fail_json(msg = "cannot find the network specified, please check") 280 | _assign_floating_ip(neutron, module, port_id, net_id) 281 | 282 | if module.params['state'] == 'absent': 283 | if floating_ip: 284 | _update_floating_ip(neutron, module, None, floating_id) 285 | module.exit_json(changed=False) 286 | 287 | # this is magic, see lib/ansible/module.params['common.py 288 | from ansible.module_utils.basic import * 289 | main() 290 | 291 | -------------------------------------------------------------------------------- /keystone_service: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # -*- coding: utf-8 -*- 3 | 4 | DOCUMENTATION = ''' 5 | --- 6 | module: keystone_service 7 | short_description: Manage OpenStack Identity (keystone) service endpoints 8 | options: 9 | name: 10 | description: 11 | - name of service (e.g., keystone) 12 | required: yes 13 | type: 14 | description: 15 | - type of service (e.g., identity) 16 | required: yes 17 | description: 18 | description: 19 | - description of service (e.g., Identity Service) 20 | required: yes 21 | public_url: 22 | description: 23 | - public url of service. 24 | - 'Alias: I(url)' 25 | - 'Alias: I(publicurl)' 26 | required: yes 27 | internal_url: 28 | description: 29 | - internal url of service. 30 | - 'Alias: I(internalurl)' 31 | required: no 32 | default: value of public_url 33 | admin_url: 34 | description: 35 | - admin url of service. 36 | - 'Alias: I(adminurl)' 37 | required: no 38 | default: value of public_url 39 | insecure: 40 | description: 41 | - allow use of self-signed SSL certificates 42 | required: no 43 | choices: [ "yes", "no" ] 44 | default: no 45 | region: 46 | description: 47 | - region of service 48 | required: no 49 | default: RegionOne 50 | ignore_other_regions: 51 | description: 52 | - allow endpoint to exist in other regions 53 | required: no 54 | choices: [ "yes", "no" ] 55 | default: no 56 | state: 57 | description: 58 | - Indicate desired state of the resource 59 | choices: ['present', 'absent'] 60 | default: present 61 | 62 | 63 | 64 | requirements: [ python-keystoneclient ] 65 | author: Lorin Hochstein 66 | ''' 67 | 68 | EXAMPLES = ''' 69 | examples: 70 | keystone_service: > 71 | name=keystone 72 | type=identity 73 | description="Keystone Identity Service" 74 | publicurl=http://192.168.206.130:5000/v2.0 75 | internalurl=http://192.168.206.130:5000/v2.0 76 | adminurl=http://192.168.206.130:35357/v2.0 77 | 78 | keystone_service: > 79 | name=glance 80 | type=image 81 | description="Glance Identity Service" 82 | url=http://192.168.206.130:9292 83 | 84 | ''' 85 | 86 | try: 87 | from keystoneclient.v2_0 import client 88 | except ImportError: 89 | keystoneclient_found = False 90 | else: 91 | keystoneclient_found = True 92 | 93 | import traceback 94 | 95 | 96 | def authenticate(endpoint, token, login_user, login_password, tenant_name, 97 | insecure): 98 | """Return a keystone client object""" 99 | 100 | if token: 101 | return client.Client(endpoint=endpoint, token=token, insecure=insecure) 102 | else: 103 | return client.Client(auth_url=endpoint, username=login_user, 104 | password=login_password, tenant_name=tenant_name, 105 | insecure=insecure) 106 | 107 | 108 | def get_service(keystone, name): 109 | """ Retrieve a service by name """ 110 | services = [x for x in keystone.services.list() if x.name == name] 111 | count = len(services) 112 | if count == 0: 113 | raise KeyError("No keystone services with name %s" % name) 114 | elif count > 1: 115 | raise ValueError("%d services with name %s" % (count, name)) 116 | else: 117 | return services[0] 118 | 119 | 120 | def get_endpoint(keystone, name, region, ignore_other_regions): 121 | """ Retrieve a service endpoint by name """ 122 | service = get_service(keystone, name) 123 | endpoints = [x for x in keystone.endpoints.list() 124 | if x.service_id == service.id] 125 | 126 | # If this is a multi-region cloud only look at this region's endpoints 127 | if ignore_other_regions: 128 | endpoints = [x for x in endpoints if x.region == region] 129 | 130 | count = len(endpoints) 131 | if count == 0: 132 | raise KeyError("No keystone endpoints with service name %s" % name) 133 | elif count > 1: 134 | raise ValueError("%d endpoints with service name %s" % (count, name)) 135 | else: 136 | return endpoints[0] 137 | 138 | 139 | def ensure_present(keystone, name, service_type, description, public_url, 140 | internal_url, admin_url, region, ignore_other_regions, 141 | check_mode): 142 | """ Ensure the service and its endpoint are present and have the right values. 143 | 144 | Returns a tuple, where the first element is a boolean that indicates 145 | a state change, the second element is the service uuid (or None in 146 | check mode), and the third element is the endpoint uuid (or None in 147 | check mode).""" 148 | # Fetch service and endpoint, if they exist. 149 | service = None 150 | endpoint = None 151 | try: service = get_service(keystone, name) 152 | except KeyError: pass 153 | try: endpoint = get_endpoint(keystone, name, region, ignore_other_regions) 154 | except KeyError: pass 155 | 156 | changed = False 157 | 158 | # Delete endpoint if it exists and doesn't match. 159 | if endpoint is not None: 160 | identical = endpoint.publicurl == public_url and \ 161 | endpoint.adminurl == admin_url and \ 162 | endpoint.internalurl == internal_url and \ 163 | endpoint.region == region 164 | if not identical: 165 | changed = True 166 | ensure_endpoint_absent(keystone, name, check_mode, region, 167 | ignore_other_regions) 168 | endpoint = None 169 | 170 | # Delete service and its endpoint if the service exists and doesn't match. 171 | if service is not None: 172 | identical = service.name == name and \ 173 | service.type == service_type and \ 174 | service.description == description 175 | if not identical: 176 | changed = True 177 | ensure_endpoint_absent(keystone, name, check_mode, region, 178 | ignore_other_regions) 179 | endpoint = None 180 | ensure_service_absent(keystone, name, check_mode) 181 | service = None 182 | 183 | # Recreate service, if necessary. 184 | if service is None: 185 | if not check_mode: 186 | service = keystone.services.create( 187 | name=name, 188 | service_type=service_type, 189 | description=description, 190 | ) 191 | changed = True 192 | 193 | # Recreate endpoint, if necessary. 194 | if endpoint is None: 195 | if not check_mode: 196 | endpoint = keystone.endpoints.create( 197 | region=region, 198 | service_id=service.id, 199 | publicurl=public_url, 200 | adminurl=admin_url, 201 | internalurl=internal_url, 202 | ) 203 | changed = True 204 | 205 | if check_mode: 206 | # In check mode, the service/endpoint uuids will be the old uuids, 207 | # so omit them. 208 | return changed, None, None 209 | return changed, service.id, endpoint.id 210 | 211 | 212 | def ensure_service_absent(keystone, name, check_mode): 213 | """ Ensure the service is absent""" 214 | try: 215 | service = get_service(keystone, name) 216 | endpoints = [x for x in keystone.endpoints.list() 217 | if x.service_id == service.id] 218 | 219 | # Don't delete the service if it still has endpoints 220 | if endpoints: 221 | return False 222 | 223 | if not check_mode: 224 | keystone.services.delete(service.id) 225 | return True 226 | except KeyError: 227 | # Service doesn't exist, so we're done. 228 | return False 229 | 230 | 231 | def ensure_endpoint_absent(keystone, name, check_mode, region, 232 | ignore_other_regions): 233 | """ Ensure the service endpoint """ 234 | try: 235 | endpoint = get_endpoint(keystone, name, region, ignore_other_regions) 236 | if not check_mode: 237 | keystone.endpoints.delete(endpoint.id) 238 | return True 239 | except KeyError: 240 | # Endpoint doesn't exist, so we're done. 241 | return False 242 | 243 | 244 | def dispatch(keystone, name, service_type, description, public_url, 245 | internal_url, admin_url, region, ignore_other_regions, state, 246 | check_mode): 247 | 248 | if state == 'present': 249 | (changed, service_id, endpoint_id) = ensure_present( 250 | keystone, 251 | name, 252 | service_type, 253 | description, 254 | public_url, 255 | internal_url, 256 | admin_url, 257 | region, 258 | ignore_other_regions, 259 | check_mode, 260 | ) 261 | return dict(changed=changed, service_id=service_id, endpoint_id=endpoint_id) 262 | elif state == 'absent': 263 | endpoint_changed = ensure_endpoint_absent(keystone, name, check_mode, 264 | region, ignore_other_regions) 265 | service_changed = ensure_service_absent(keystone, name, check_mode) 266 | return dict(changed=service_changed or endpoint_changed) 267 | else: 268 | raise ValueError("Code should never reach here") 269 | 270 | 271 | 272 | def main(): 273 | 274 | module = AnsibleModule( 275 | argument_spec=dict( 276 | name=dict(required=True), 277 | type=dict(required=True), 278 | description=dict(required=False), 279 | public_url=dict(required=True, aliases=['url', 'publicurl']), 280 | internal_url=dict(required=False, aliases=['internalurl']), 281 | admin_url=dict(required=False, aliases=['adminurl']), 282 | region=dict(required=False, default='RegionOne'), 283 | ignore_other_regions=dict(required=False, default=False, type='bool'), 284 | state=dict(default='present', choices=['present', 'absent']), 285 | endpoint=dict(required=False, 286 | default="http://127.0.0.1:35357/v2.0", 287 | aliases=['auth_url']), 288 | token=dict(required=False), 289 | insecure=dict(required=False, default=False, type='bool'), 290 | 291 | login_user=dict(required=False), 292 | login_password=dict(required=False), 293 | tenant_name=dict(required=False, aliases=['tenant']) 294 | ), 295 | supports_check_mode=True, 296 | mutually_exclusive=[['token', 'login_user'], 297 | ['token', 'login_password'], 298 | ['token', 'tenant_name']] 299 | ) 300 | 301 | endpoint = module.params['endpoint'] 302 | token = module.params['token'] 303 | login_user = module.params['login_user'] 304 | login_password = module.params['login_password'] 305 | tenant_name = module.params['tenant_name'] 306 | insecure = module.boolean(module.params['insecure']) 307 | name = module.params['name'] 308 | service_type = module.params['type'] 309 | description = module.params['description'] 310 | public_url = module.params['public_url'] 311 | internal_url = module.params['internal_url'] 312 | if internal_url is None: 313 | internal_url = public_url 314 | admin_url = module.params['admin_url'] 315 | if admin_url is None: 316 | admin_url = public_url 317 | region = module.params['region'] 318 | ignore_other_regions = module.boolean(module.params['ignore_other_regions']) 319 | state = module.params['state'] 320 | 321 | keystone = authenticate(endpoint, token, login_user, login_password, 322 | tenant_name, insecure) 323 | check_mode = module.check_mode 324 | 325 | try: 326 | d = dispatch(keystone, name, service_type, description, 327 | public_url, internal_url, admin_url, region, 328 | ignore_other_regions, state, check_mode) 329 | except Exception: 330 | if check_mode: 331 | # If we have a failure in check mode 332 | module.exit_json(changed=True, 333 | msg="exception: %s" % traceback.format_exc()) 334 | else: 335 | module.fail_json(msg=traceback.format_exc()) 336 | else: 337 | module.exit_json(**d) 338 | 339 | 340 | # this is magic, see lib/ansible/module_common.py 341 | #<> 342 | if __name__ == '__main__': 343 | main() 344 | -------------------------------------------------------------------------------- /neutron_subnet: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | #coding: utf-8 -*- 3 | 4 | # (c) 2013, Benno Joy 5 | # 6 | # This module is free software: you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation, either version 3 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This software is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License 17 | # along with this software. If not, see . 18 | 19 | try: 20 | from neutronclient.neutron import client 21 | from keystoneclient.v2_0 import client as ksclient 22 | except ImportError: 23 | print("failed=True msg='neutron and keystone client are required'") 24 | 25 | DOCUMENTATION = ''' 26 | --- 27 | module: neutron_subnet 28 | version_added: "1.2" 29 | short_description: Add/Remove floating IP from an instance 30 | description: 31 | - Add or Remove a floating IP to an instance 32 | options: 33 | login_username: 34 | description: 35 | - login username to authenticate to keystone 36 | required: true 37 | default: admin 38 | login_password: 39 | description: 40 | - Password of login user 41 | required: true 42 | default: True 43 | login_tenant_name: 44 | description: 45 | - The tenant name of the login user 46 | required: true 47 | default: True 48 | auth_url: 49 | description: 50 | - The keystone URL for authentication 51 | required: false 52 | default: 'http://127.0.0.1:35357/v2.0/' 53 | region_name: 54 | description: 55 | - Name of the region 56 | required: false 57 | default: None 58 | state: 59 | description: 60 | - Indicate desired state of the resource 61 | choices: ['present', 'absent'] 62 | default: present 63 | network_name: 64 | description: 65 | - Name of the network to which the subnet should be attached 66 | required: true 67 | default: None 68 | cidr: 69 | description: 70 | - The CIDR representation of the subnet that should be assigned to the subnet 71 | required: true 72 | default: None 73 | tenant_name: 74 | description: 75 | - The name of the tenant for whom the subnet should be created 76 | required: false 77 | default: None 78 | ip_version: 79 | description: 80 | - The IP version of the subnet 4 or 6 81 | required: false 82 | default: 4 83 | enable_dhcp: 84 | description: 85 | - Whether DHCP should be enabled for this subnet. 86 | required: false 87 | default: true 88 | no_gateway: 89 | description: 90 | - If "true", no gateway will be created for this subnet 91 | required: false 92 | default: false 93 | gateway_ip: 94 | description: 95 | - The ip that would be assigned to the gateway for this subnet 96 | required: false 97 | default: None 98 | dns_nameservers: 99 | description: 100 | - DNS nameservers for this subnet, comma-separated 101 | required: false 102 | default: None 103 | allocation_pool_start: 104 | description: 105 | - From the subnet pool the starting address from which the IP should be allocated 106 | required: false 107 | default: None 108 | allocation_pool_end: 109 | description: 110 | - From the subnet pool the last IP that should be assigned to the virtual machines 111 | required: false 112 | default: None 113 | ipv6-ra-mode: 114 | description: 115 | - IPv6 router advertisement mode: dhcpv6-stateful,dhcpv6-stateless,slaac 116 | required: false 117 | default: none 118 | ipv6-address-mode: 119 | description: 120 | - IPv6 address mode: dhcpv6-stateful,dhcpv6-stateless,slaac 121 | required: false 122 | default: none 123 | host_routes: 124 | description: 125 | - Host routes for this subnet, list of dictionaries, e.g. [{destination: 0.0.0.0/0, nexthop: 123.456.78.9}, {destination: 192.168.0.0/24, nexthop: 192.168.0.1}] 126 | required: false 127 | default: None 128 | requirements: ["neutron", "keystoneclient"] 129 | ''' 130 | 131 | EXAMPLES = ''' 132 | # Create a subnet for a tenant with the specified subnet 133 | - neutron_subnet: state=present login_username=admin login_password=admin 134 | login_tenant_name=admin tenant_name=tenant1 135 | network_name=network1 name=net1subnet cidr=192.168.0.0/24" 136 | ''' 137 | 138 | _os_keystone = None 139 | _os_tenant_id = None 140 | _os_network_id = None 141 | 142 | def _get_ksclient(module, kwargs): 143 | try: 144 | kclient = ksclient.Client( 145 | username=module.params.get('login_username'), 146 | password=module.params.get('login_password'), 147 | tenant_name=module.params.get('login_tenant_name'), 148 | auth_url=module.params.get('auth_url'), 149 | region_name=module.params.get('region_name')) 150 | except Exception as e: 151 | module.fail_json(msg = "Error authenticating to the keystone: %s" %e.message) 152 | global _os_keystone 153 | _os_keystone = kclient 154 | return kclient 155 | 156 | 157 | def _get_endpoint(module, ksclient): 158 | try: 159 | endpoint = ksclient.service_catalog.url_for(service_type='network', endpoint_type='publicURL') 160 | except Exception as e: 161 | module.fail_json(msg = "Error getting endpoint for glance: %s" % e.message) 162 | return endpoint 163 | 164 | def _get_neutron_client(module, kwargs): 165 | _ksclient = _get_ksclient(module, kwargs) 166 | token = _ksclient.auth_token 167 | endpoint = _get_endpoint(module, _ksclient) 168 | kwargs = { 169 | 'token': token, 170 | 'endpoint_url': endpoint 171 | } 172 | try: 173 | neutron = client.Client('2.0', **kwargs) 174 | except Exception as e: 175 | module.fail_json(msg = " Error in connecting to Neutron: %s" % e.message) 176 | return neutron 177 | 178 | def _set_tenant_id(module): 179 | global _os_tenant_id 180 | if module.params['tenant_name']: 181 | # We need admin power in order retrieve the tenant_id of a given 182 | # tenant name and to create/delete networks for a tenant that is not 183 | # the one used to authenticate the user. 184 | tenant_name = module.params['tenant_name'] 185 | for tenant in _os_keystone.tenants.list(): 186 | if tenant.name == tenant_name: 187 | _os_tenant_id = tenant.id 188 | break 189 | else: 190 | _os_tenant_id = _os_keystone.tenant_id 191 | 192 | if not _os_tenant_id: 193 | module.fail_json(msg = "The tenant id cannot be found, please check the paramters") 194 | 195 | def _get_net_id(neutron, module): 196 | kwargs = { 197 | 'tenant_id': _os_tenant_id, 198 | 'name': module.params['network_name'], 199 | } 200 | try: 201 | networks = neutron.list_networks(**kwargs) 202 | except Exception as e: 203 | module.fail_json(msg = "Error in listing Neutron networks: %s" % e.message) 204 | if not networks['networks']: 205 | return None 206 | return networks['networks'][0]['id'] 207 | 208 | 209 | def _get_subnet_id(module, neutron): 210 | global _os_network_id 211 | subnet_id = None 212 | _os_network_id = _get_net_id(neutron, module) 213 | if not _os_network_id: 214 | module.fail_json(msg = "network id of network not found.") 215 | else: 216 | kwargs = { 217 | 'tenant_id': _os_tenant_id, 218 | 'name': module.params['name'], 219 | } 220 | try: 221 | subnets = neutron.list_subnets(**kwargs) 222 | except Exception as e: 223 | module.fail_json( msg = " Error in getting the subnet list:%s " % e.message) 224 | if not subnets['subnets']: 225 | return None 226 | return subnets['subnets'][0]['id'] 227 | 228 | def _create_subnet(module, neutron): 229 | neutron.format = 'json' 230 | subnet = { 231 | 'name': module.params['name'], 232 | 'ip_version': module.params['ip_version'], 233 | 'enable_dhcp': module.params['enable_dhcp'], 234 | 'tenant_id': _os_tenant_id, 235 | 'gateway_ip': module.params['gateway_ip'], 236 | 'dns_nameservers': module.params['dns_nameservers'], 237 | 'network_id': _os_network_id, 238 | 'cidr': module.params['cidr'], 239 | 'host_routes': module.params['host_routes'], 240 | } 241 | if module.params['allocation_pool_start'] and module.params['allocation_pool_end']: 242 | allocation_pools = [ 243 | { 244 | 'start' : module.params['allocation_pool_start'], 245 | 'end' : module.params['allocation_pool_end'] 246 | } 247 | ] 248 | subnet.update({'allocation_pools': allocation_pools}) 249 | # "subnet['gateway_ip'] = None" means: "no gateway" 250 | # no gateway_ip in body means: "automatic gateway" 251 | if module.params['no_gateway']: 252 | subnet['gateway_ip'] = None 253 | elif module.params['gateway_ip'] is not None: 254 | subnet['gateway_ip'] = module.params['gateway_ip'] 255 | if module.params['dns_nameservers']: 256 | subnet['dns_nameservers'] = module.params['dns_nameservers'].split(',') 257 | else: 258 | subnet.pop('dns_nameservers') 259 | if not module.params['host_routes']: 260 | subnet.pop('host_routes') 261 | if module.params['ipv6_ra_mode'] and int(module.params['ip_version']) == 6: 262 | subnet.update({'ipv6_ra_mode': module.params['ipv6_ra_mode']}) 263 | if module.params['ipv6_address_mode'] and int(module.params['ip_version']) == 6: 264 | subnet.update({'ipv6_address_mode': module.params['ipv6_address_mode']}) 265 | try: 266 | new_subnet = neutron.create_subnet(dict(subnet=subnet)) 267 | except Exception, e: 268 | module.fail_json(msg = "Failure in creating subnet: %s" % e.message) 269 | return new_subnet['subnet']['id'] 270 | 271 | 272 | def _delete_subnet(module, neutron, subnet_id): 273 | try: 274 | neutron.delete_subnet(subnet_id) 275 | except Exception as e: 276 | module.fail_json( msg = "Error in deleting subnet: %s" % e.message) 277 | return True 278 | 279 | 280 | def main(): 281 | 282 | ipv6_mode_choices = ['dhcpv6-stateful', 'dhcpv6-stateless', 'slaac'] 283 | module = AnsibleModule( 284 | argument_spec = dict( 285 | login_username = dict(default='admin'), 286 | login_password = dict(required=True), 287 | login_tenant_name = dict(required='True'), 288 | auth_url = dict(default='http://127.0.0.1:35357/v2.0/'), 289 | region_name = dict(default=None), 290 | name = dict(required=True), 291 | network_name = dict(required=True), 292 | cidr = dict(required=True), 293 | tenant_name = dict(default=None), 294 | state = dict(default='present', choices=['absent', 'present']), 295 | ip_version = dict(default='4', choices=['4', '6']), 296 | enable_dhcp = dict(default=True, type='bool'), 297 | no_gateway = dict(default=False, type='bool'), 298 | gateway_ip = dict(default=None), 299 | dns_nameservers = dict(default=None), 300 | allocation_pool_start = dict(default=None), 301 | allocation_pool_end = dict(default=None), 302 | ipv6_ra_mode = dict(default=None, choices=ipv6_mode_choices), 303 | ipv6_address_mode = dict(default=None, choices=ipv6_mode_choices), 304 | host_routes = dict(default=None), 305 | ), 306 | ) 307 | neutron = _get_neutron_client(module, module.params) 308 | _set_tenant_id(module) 309 | if module.params['state'] == 'present': 310 | subnet_id = _get_subnet_id(module, neutron) 311 | if not subnet_id: 312 | subnet_id = _create_subnet(module, neutron) 313 | module.exit_json(changed = True, result = "Created" , id = subnet_id) 314 | else: 315 | module.exit_json(changed = False, result = "success" , id = subnet_id) 316 | else: 317 | subnet_id = _get_subnet_id(module, neutron) 318 | if not subnet_id: 319 | module.exit_json(changed = False, result = "success") 320 | else: 321 | _delete_subnet(module, neutron, subnet_id) 322 | module.exit_json(changed = True, result = "deleted") 323 | 324 | # this is magic, see lib/ansible/module.params['common.py 325 | from ansible.module_utils.basic import * 326 | main() 327 | -------------------------------------------------------------------------------- /tests/test_keystone_service.py: -------------------------------------------------------------------------------- 1 | import keystone_service 2 | import mock 3 | from nose.tools import assert_equal, assert_list_equal, assert_is_none 4 | from nose import SkipTest 5 | 6 | 7 | def setup(): 8 | keystone = mock.MagicMock() 9 | service = mock.Mock(id="b6a7ff03f2574cd9b5c7c61186e0d781", 10 | type="identity", 11 | description="Keystone Identity Service") 12 | # Can't set field in mock in initializer 13 | service.name = "keystone" 14 | keystone.services.list = mock.Mock(return_value=[service]) 15 | endpoint = mock.Mock(id="600759628a214eb7b3acde39b1e85180", 16 | service_id="b6a7ff03f2574cd9b5c7c61186e0d781", 17 | publicurl="http://192.168.206.130:5000/v2.0", 18 | internalurl="http://192.168.206.130:5000/v2.0", 19 | adminurl="http://192.168.206.130:35357/v2.0", 20 | region="RegionOne") 21 | keystone.endpoints.list = mock.Mock(return_value=[endpoint]) 22 | return keystone 23 | 24 | 25 | def setup_multi_region(): 26 | keystone = mock.MagicMock() 27 | 28 | services = [ 29 | mock.Mock(id="b6a7ff03f2574cd9b5c7c61186e0d781", 30 | type="identity", 31 | description="Keystone Identity Service"), 32 | mock.Mock(id="a7ebed35051147d4abbe2ee049eeb346", 33 | type="compute", 34 | description="Compute Service") 35 | ] 36 | 37 | # Can't set field in mock in initializer 38 | services[0].name = "keystone" 39 | services[1].name = "nova" 40 | 41 | keystone.services.list = mock.Mock(return_value=services) 42 | 43 | endpoints = [ 44 | mock.Mock(id="600759628a214eb7b3acde39b1e85180", 45 | service_id="b6a7ff03f2574cd9b5c7c61186e0d781", 46 | publicurl="http://192.168.206.130:5000/v2.0", 47 | internalurl="http://192.168.206.130:5000/v2.0", 48 | adminurl="http://192.168.206.130:35357/v2.0", 49 | region="RegionOne"), 50 | mock.Mock(id="6bdf5ed5e0a54df8b9a049bd263bba0c", 51 | service_id="b6a7ff03f2574cd9b5c7c61186e0d781", 52 | publicurl="http://192.168.206.130:5000/v2.0", 53 | internalurl="http://192.168.206.130:5000/v2.0", 54 | adminurl="http://192.168.206.130:35357/v2.0", 55 | region="RegionTwo"), 56 | mock.Mock(id="cf65cfdc5b5a4fa39bfbe3d7e27f8526", 57 | service_id="a7ebed35051147d4abbe2ee049eeb346", 58 | publicurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 59 | internalurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 60 | adminurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 61 | region="RegionTwo") 62 | ] 63 | 64 | keystone.endpoints.list = mock.Mock(return_value=endpoints) 65 | 66 | return keystone 67 | 68 | 69 | @mock.patch('keystone_service.ensure_endpoint_absent') 70 | @mock.patch('keystone_service.ensure_service_absent') 71 | @mock.patch('keystone_service.ensure_present') 72 | def test_dispatch_service_present(mock_ensure_present, 73 | mock_ensure_service_absent, 74 | mock_ensure_endpoint_absent): 75 | """ Dispatch: service present """ 76 | # Setup 77 | mock_ensure_present.return_value = (True, None, None) 78 | manager = mock.MagicMock() 79 | manager.attach_mock(mock_ensure_present, 'ensure_present') 80 | manager.attach_mock(mock_ensure_service_absent, 'ensure_service_absent') 81 | manager.attach_mock(mock_ensure_endpoint_absent, 82 | 'ensure_endpoint_absent') 83 | 84 | keystone = setup() 85 | name = "keystone" 86 | service_type = "identity" 87 | description = "Keystone Identity Service" 88 | state = "present" 89 | public_url = "http://192.168.206.130:5000/v2.0" 90 | internal_url = "http://192.168.206.130:5000/v2.0" 91 | admin_url = "http://192.168.206.130:35357/v2.0" 92 | region = "RegionOne" 93 | ignore_other_regions = False 94 | check_mode = False 95 | 96 | # Code under test 97 | keystone_service.dispatch(keystone, name, service_type, description, 98 | public_url, internal_url, admin_url, region, 99 | ignore_other_regions, state, check_mode) 100 | 101 | expected_calls = [mock.call.ensure_present(keystone, name, service_type, 102 | description, public_url, 103 | internal_url, admin_url, region, 104 | ignore_other_regions, 105 | check_mode)] 106 | 107 | assert_equal(manager.mock_calls, expected_calls) 108 | 109 | 110 | @mock.patch('keystone_service.ensure_endpoint_absent') 111 | @mock.patch('keystone_service.ensure_service_absent') 112 | @mock.patch('keystone_service.ensure_present') 113 | def test_dispatch_service_absent(mock_ensure_present, 114 | mock_ensure_service_absent, 115 | mock_ensure_endpoint_absent): 116 | """ Dispatch: service absent """ 117 | # Setup 118 | mock_ensure_service_absent.return_value = True 119 | mock_ensure_endpoint_absent.return_value = True 120 | manager = mock.MagicMock() 121 | manager.attach_mock(mock_ensure_present, 'ensure_present') 122 | manager.attach_mock(mock_ensure_service_absent, 'ensure_service_absent') 123 | manager.attach_mock(mock_ensure_endpoint_absent, 124 | 'ensure_endpoint_absent') 125 | 126 | keystone = setup() 127 | name = "keystone" 128 | service_type = "identity" 129 | description = "Keystone Identity Service" 130 | region = "RegionOne" 131 | ignore_other_regions = False 132 | state = "absent" 133 | public_url = "http://192.168.206.130:5000/v2.0" 134 | internal_url = "http://192.168.206.130:5000/v2.0" 135 | admin_url = "http://192.168.206.130:35357/v2.0" 136 | check_mode = False 137 | 138 | # Code under test 139 | keystone_service.dispatch(keystone, name, service_type, description, 140 | public_url, internal_url, admin_url, region, 141 | ignore_other_regions, state, check_mode) 142 | 143 | expected_calls = [ 144 | mock.call.ensure_endpoint_absent(keystone, name, check_mode, region, 145 | ignore_other_regions), 146 | mock.call.ensure_service_absent(keystone, name, check_mode) 147 | ] 148 | 149 | assert_list_equal(manager.mock_calls, expected_calls) 150 | 151 | 152 | def test_ensure_present_when_present(): 153 | """ ensure_present when the service and endpoint are present """ 154 | # Setup 155 | keystone = setup() 156 | name = "keystone" 157 | service_type = "identity" 158 | description = "Keystone Identity Service" 159 | region = "RegionOne" 160 | ignore_other_regions = False 161 | public_url = "http://192.168.206.130:5000/v2.0" 162 | internal_url = "http://192.168.206.130:5000/v2.0" 163 | admin_url = "http://192.168.206.130:35357/v2.0" 164 | check_mode = False 165 | 166 | # Code under test 167 | (changed, service_id, endpoint_id) = keystone_service.ensure_present( 168 | keystone, name, service_type, description, public_url, 169 | internal_url, admin_url, region, ignore_other_regions, check_mode) 170 | 171 | # Assertions 172 | assert not changed 173 | assert_equal(service_id, "b6a7ff03f2574cd9b5c7c61186e0d781") 174 | assert_equal(endpoint_id, "600759628a214eb7b3acde39b1e85180") 175 | 176 | 177 | def test_ensure_present_when_present_multi_region(): 178 | """ ensure_present when the service and endpoint are present in region """ 179 | # Setup 180 | keystone = setup_multi_region() 181 | name = "keystone" 182 | service_type = "identity" 183 | description = "Keystone Identity Service" 184 | region = "RegionOne" 185 | ignore_other_regions = True 186 | public_url = "http://192.168.206.130:5000/v2.0" 187 | internal_url = "http://192.168.206.130:5000/v2.0" 188 | admin_url = "http://192.168.206.130:35357/v2.0" 189 | check_mode = False 190 | 191 | # Code under test 192 | (changed, service_id, endpoint_id) = keystone_service.ensure_present( 193 | keystone, name, service_type, description, public_url, 194 | internal_url, admin_url, region, ignore_other_regions, check_mode) 195 | 196 | # Assertions 197 | assert not changed 198 | assert_equal(service_id, "b6a7ff03f2574cd9b5c7c61186e0d781") 199 | assert_equal(endpoint_id, "600759628a214eb7b3acde39b1e85180") 200 | 201 | 202 | def test_ensure_present_when_present_check(): 203 | """ ensure_present when the service and endpoint are present, check mode""" 204 | # Setup 205 | keystone = setup() 206 | name = "keystone" 207 | service_type = "identity" 208 | description = "Keystone Identity Service" 209 | region = "RegionOne" 210 | ignore_other_regions = False 211 | public_url = "http://192.168.206.130:5000/v2.0" 212 | internal_url = "http://192.168.206.130:5000/v2.0" 213 | admin_url = "http://192.168.206.130:35357/v2.0" 214 | check_mode = True 215 | 216 | # Code under test 217 | (changed, service_id, endpoint_id) = keystone_service.ensure_present( 218 | keystone, name, service_type, description, public_url, 219 | internal_url, admin_url, region, ignore_other_regions, check_mode) 220 | 221 | # Assertions 222 | assert not changed 223 | assert_equal(service_id, None) 224 | assert_equal(endpoint_id, None) 225 | 226 | 227 | def test_ensure_present_when_absent(): 228 | """ ensure_present when the service and endpoint are absent """ 229 | # Setup 230 | keystone = setup() 231 | 232 | # Mock out the service and endpoint creates 233 | endpoint = mock.Mock( 234 | id="622386d836b14fd986d9cec7504d208a", 235 | publicurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 236 | internalurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 237 | adminurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 238 | region="RegionOne") 239 | keystone.endpoints.create = mock.Mock(return_value=endpoint) 240 | service = mock.Mock(id="a7ebed35051147d4abbe2ee049eeb346") 241 | keystone.services.create = mock.Mock(return_value=service) 242 | 243 | name = "nova" 244 | service_type = "compute" 245 | description = "Compute Service" 246 | public_url = "http://192.168.206.130:8774/v2/%(tenant_id)s" 247 | internal_url = "http://192.168.206.130:8774/v2/%(tenant_id)s" 248 | admin_url = "http://192.168.206.130:8774/v2/%(tenant_id)s" 249 | region = "RegionOne" 250 | ignore_other_regions = False 251 | check_mode = False 252 | 253 | # Code under test 254 | (changed, service_id, endpoint_id) = keystone_service.ensure_present( 255 | keystone, name, service_type, description, public_url, 256 | internal_url, admin_url, region, ignore_other_regions, check_mode) 257 | 258 | # Assertions 259 | assert changed 260 | assert_equal(service_id, "a7ebed35051147d4abbe2ee049eeb346") 261 | keystone.services.create.assert_called_with(name=name, 262 | service_type=service_type, 263 | description=description) 264 | assert_equal(endpoint_id, "622386d836b14fd986d9cec7504d208a") 265 | keystone.endpoints.create.assert_called_with( 266 | service_id="a7ebed35051147d4abbe2ee049eeb346", 267 | publicurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 268 | internalurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 269 | adminurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 270 | region="RegionOne") 271 | 272 | 273 | def test_ensure_present_when_absent_multi_region(): 274 | """ ensure_present when the endpoint is absent in this region """ 275 | # Setup 276 | keystone = setup_multi_region() 277 | 278 | # Mock out the service and endpoint creates 279 | endpoint = mock.Mock( 280 | id="622386d836b14fd986d9cec7504d208a", 281 | publicurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 282 | internalurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 283 | adminurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 284 | region="RegionOne") 285 | keystone.endpoints.create = mock.Mock(return_value=endpoint) 286 | service = mock.Mock(id="a7ebed35051147d4abbe2ee049eeb346") 287 | keystone.services.create = mock.Mock(return_value=service) 288 | keystone.endpoints.delete = mock.Mock() 289 | 290 | name = "nova" 291 | service_type = "compute" 292 | description = "Compute Service" 293 | public_url = "http://192.168.206.130:8774/v2/%(tenant_id)s" 294 | internal_url = "http://192.168.206.130:8774/v2/%(tenant_id)s" 295 | admin_url = "http://192.168.206.130:8774/v2/%(tenant_id)s" 296 | region = "RegionOne" 297 | ignore_other_regions = True 298 | check_mode = False 299 | 300 | # Code under test 301 | (changed, service_id, endpoint_id) = keystone_service.ensure_present( 302 | keystone, name, service_type, description, public_url, 303 | internal_url, admin_url, region, ignore_other_regions, check_mode) 304 | 305 | # Assertions 306 | assert changed 307 | assert_equal(service_id, "a7ebed35051147d4abbe2ee049eeb346") 308 | assert not keystone.services.create.called 309 | assert_equal(endpoint_id, "622386d836b14fd986d9cec7504d208a") 310 | keystone.endpoints.create.assert_called_with( 311 | service_id="a7ebed35051147d4abbe2ee049eeb346", 312 | publicurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 313 | internalurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 314 | adminurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 315 | region="RegionOne") 316 | assert not keystone.endpoints.delete.called 317 | 318 | 319 | def test_ensure_present_when_absent_check(): 320 | """ ensure_present when the service and endpoint are absent, check mode """ 321 | # Setup 322 | keystone = setup() 323 | 324 | # Mock out the service and endpoint creates 325 | endpoint = mock.Mock( 326 | id="622386d836b14fd986d9cec7504d208a", 327 | publicurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 328 | internalurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 329 | adminurl="http://192.168.206.130:8774/v2/%(tenant_id)s", 330 | region="RegionOne") 331 | keystone.endpoints.create = mock.Mock(return_value=endpoint) 332 | service = mock.Mock(id="a7ebed35051147d4abbe2ee049eeb346") 333 | keystone.services.create = mock.Mock(return_value=service) 334 | 335 | name = "nova" 336 | service_type = "compute" 337 | description = "Compute Service" 338 | public_url = "http://192.168.206.130:8774/v2/%(tenant_id)s" 339 | internal_url = "http://192.168.206.130:8774/v2/%(tenant_id)s" 340 | admin_url = "http://192.168.206.130:8774/v2/%(tenant_id)s" 341 | region = "RegionOne" 342 | ignore_other_regions = False 343 | check_mode = True 344 | 345 | # Code under test 346 | (changed, service_id, endpoint_id) = keystone_service.ensure_present( 347 | keystone, name, service_type, description, public_url, 348 | internal_url, admin_url, region, ignore_other_regions, check_mode) 349 | 350 | # Assertions 351 | assert changed 352 | assert_equal(service_id, None) 353 | assert not keystone.services.create.called 354 | assert_equal(endpoint_id, None) 355 | assert not keystone.endpoints.create.called 356 | 357 | 358 | def test_get_endpoint_present(): 359 | """ get_endpoint when endpoint is present """ 360 | keystone = setup() 361 | 362 | endpoint = keystone_service.get_endpoint(keystone, "keystone", "RegionOne", 363 | False) 364 | 365 | assert_equal(endpoint.id, "600759628a214eb7b3acde39b1e85180") 366 | -------------------------------------------------------------------------------- /neutron_sec_group: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python 2 | # 3 | # (c) Cisco Systems, 2014 4 | # 5 | # This module is free software: you can redistribute it and/or modify 6 | # it under the terms of the GNU General Public License as published by 7 | # the Free Software Foundation, either version 3 of the License, or 8 | # (at your option) any later version. 9 | # 10 | # This software is distributed in the hope that it will be useful, 11 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | # GNU General Public License for more details. 14 | # 15 | # You should have received a copy of the GNU General Public License 16 | # along with this software. If not, see . 17 | 18 | DOCUMENTATION = ''' 19 | --- 20 | module: neutron_sec_group 21 | short_description: Create, Remove or Update Openstack security groups 22 | description: 23 | - Create, Remove or Update Openstack security groups 24 | options: 25 | login_username: 26 | description: 27 | - login username to authenticate to keystone 28 | - If unspecified, the OS_USERNAME environment variable is used 29 | required: true 30 | login_password: 31 | description: 32 | - Password of login user 33 | - If unspecified, the OS_PASSWORD environment variable is used 34 | required: true 35 | login_tenant_name: 36 | description: 37 | - The tenant name of the login user 38 | - If unspecified, the OS_TENANT_NAME environment variable is used 39 | required: false 40 | login_tenant_id: 41 | description: 42 | - The tenant id of the login user 43 | - If unspecified, the OS_TENANT_ID environment variable is used 44 | required: false 45 | auth_url: 46 | description: 47 | - The keystone url for authentication 48 | - If unspecified, the OS_AUTH_URL environment variable is used 49 | required: false 50 | default: 'http://127.0.0.1:5000/v2.0/' 51 | region_name: 52 | description: 53 | - Name of the region 54 | required: false 55 | default: None 56 | state: 57 | description: 58 | - Indicate desired state of the security group. 'append' will 59 | add rules only, without deleting rules that are not listed. 60 | choices: ['present', 'absent', 'append'] 61 | default: present 62 | name: 63 | description: 64 | - Name to be given to the security group 65 | required: true 66 | default: None 67 | tenant_name: 68 | description: 69 | - Name of the tenant for which the security group has to be created, 70 | if none, the security group would be created for the login tenant. 71 | required: false 72 | default: None 73 | rules: 74 | description: 75 | - "List of security group rules. Available parameters of a rule: 76 | direction, port_range_min, port_range_max, ethertype, protocol, 77 | remote_ip_prefix|remote_group_id|remote_group_name" 78 | required: false 79 | default: none 80 | requirements: ["neutronclient", "keystoneclient"] 81 | ''' 82 | 83 | EXAMPLES = ''' 84 | # Creates a security group with a number of rules 85 | neutron_sec_group: 86 | login_username: "demo" 87 | login_password: "password" 88 | login_tenant_name: "demo" 89 | auth_url: "http://127.0.0.1:5000/v2.0" 90 | name: "sg-test" 91 | description: "Description of the security group" 92 | state: "present" 93 | rules: 94 | - direction: "ingress" 95 | port_range_min: "80" 96 | port_range_max: "80" 97 | ethertype: "IPv4" 98 | protocol: "tcp" 99 | remote_ip_prefix: "10.0.0.1/24" 100 | - direction: "ingress" 101 | port_range_min: "22" 102 | port_range_max: "22" 103 | ethertype: "IPv4" 104 | protocol: "tcp" 105 | remote_ip_prefix: "10.0.0.1/24" 106 | - direction: "ingress" 107 | port_range_min: "22" 108 | port_range_max: "22" 109 | ethertype: "IPv4" 110 | protocol: "tcp" 111 | remote_group_id: UUID_OF_GROUP 112 | - direction: "ingress" 113 | port_range_min: "22" 114 | port_range_max: "22" 115 | ethertype: "IPv4" 116 | protocol: "tcp" 117 | remote_group_name: 'default' 118 | ''' 119 | 120 | try: 121 | import neutronclient.v2_0.client 122 | import keystoneclient.v2_0.client 123 | from neutronclient.common import exceptions 124 | except ImportError: 125 | print "failed=True msg='neutronclient and keystoneclient are required'" 126 | 127 | 128 | def main(): 129 | """ 130 | Main function - entry point. The magic starts here ;-) 131 | """ 132 | module = AnsibleModule( 133 | argument_spec=dict( 134 | auth_url=dict(default=None, required=False), 135 | login_username=dict(default=None, required=False), 136 | login_password=dict(default=None, required=False), 137 | login_tenant_name=dict(default=None, required=False), 138 | login_tenant_id=dict(default=None, required=False), 139 | name=dict(required=True), 140 | description=dict(default=None), 141 | region_name=dict(default=None), 142 | rules=dict(default=None), 143 | tenant_name=dict(required=False), 144 | state=dict(default='present', choices=['present', 'absent', 'append']) 145 | ), 146 | supports_check_mode=True 147 | ) 148 | # Grab configuration from environment or params for openstack 149 | for item in ( 150 | 'auth_url', 151 | 'login_tenant_name', 152 | 'login_username', 153 | 'login_password', 154 | 'login_tenant_id' 155 | ): 156 | if not module.params[item]: 157 | module.params[item] = os.environ.get( 158 | 'OS_{0}'.format(item.upper().replace('LOGIN_', '')) 159 | ) 160 | 161 | network_client = _get_network_client(module.params) 162 | identity_client = _get_identity_client(module.params) 163 | 164 | try: 165 | # Get id of security group (as a result check whether it exists) 166 | tenant_id = _get_tenant_id(module, identity_client) 167 | 168 | params = { 169 | 'name': module.params['name'], 170 | 'tenant_id': tenant_id, 171 | 'fields': 'id', 172 | } 173 | 174 | sec_groups = network_client.list_security_groups(**params)['security_groups'] 175 | if len(sec_groups) > 1: 176 | raise exceptions.NeutronClientNoUniqueMatch(resource='security_group', name=params['name']) 177 | elif len(sec_groups) == 0: 178 | sec_group_exists = False 179 | else: 180 | sec_group = sec_groups[0] 181 | sec_group_exists = True 182 | 183 | # state=present -> create or update depending on whether sg exists. 184 | if module.params['state'] == 'present' or module.params['state'] == 'append': 185 | # UPDATE 186 | if sec_group_exists: 187 | changed, sg = _update_sg(module, network_client, sec_group, tenant_id) 188 | if changed: 189 | module.exit_json(sec_group=sg, updated=True, changed=changed) 190 | else: 191 | module.exit_json(sec_group=sg, changed=changed) 192 | # CREATE 193 | else: 194 | sg = _create_sg(module, network_client, tenant_id) 195 | module.exit_json(sec_group=sg, created=True, changed=True) 196 | # DELETE 197 | elif module.params['state'] == 'absent' and sec_group_exists: 198 | _delete_sg(module, network_client, sec_group) 199 | module.exit_json(changed=True) 200 | 201 | module.exit_json(changed=False) 202 | 203 | except exceptions.Unauthorized as exc: 204 | module.fail_json(msg="Authentication error: %s" % str(exc)) 205 | except Exception as exc: 206 | module.fail_json(msg="Error: %s" % str(exc)) 207 | 208 | 209 | def _delete_sg(module, network_client, sec_group): 210 | """ 211 | Deletes a security group. 212 | :param module: module to get security group params from. 213 | :param network_client: network client to use. 214 | :param sec_group: security group to delete. 215 | """ 216 | if module.check_mode: 217 | return 218 | network_client.delete_security_group(sec_group['id']) 219 | 220 | 221 | def _create_sg(module, network_client, tenant_id): 222 | """ 223 | Creates a security group. 224 | :param module: module to get security group params from. 225 | :param network_client: network client to use. 226 | :param: identity_client: identity_client used if an admin performs the 227 | operation for a different tenant. 228 | :return: newly created security group. 229 | """ 230 | if module.check_mode: 231 | return None 232 | 233 | data = { 234 | 'security_group': { 235 | 'name': module.params['name'], 236 | 'description': module.params['description'], 237 | 'tenant_id': tenant_id 238 | } 239 | } 240 | 241 | sg = network_client.create_security_group(data) 242 | sg = sg['security_group'] 243 | 244 | changed, sg = _update_sg(module, network_client, sg, tenant_id) 245 | return sg 246 | 247 | 248 | def _update_sg(module, network_client, sg, tenant_id): 249 | """ 250 | Updates a security group. 251 | :param module: module to get updated security group param from. 252 | :param network_client: network client to use. 253 | :param sg: security group that needs to be updated. 254 | :return: True/False, the updated security group. 255 | """ 256 | changed = False 257 | sg = network_client.show_security_group(sg['id']) 258 | sg = sg['security_group'] 259 | 260 | # We only allow description updating, no name updating 261 | if module.params['description'] \ 262 | and not module.params['description'] == sg['description'] \ 263 | and module.check_mode: 264 | 265 | changed = True 266 | elif module.params['description'] \ 267 | and not module.params['description'] == sg['description'] \ 268 | and not module.check_mode: 269 | body = { 270 | 'security_group': { 271 | 'description': module.params['description'] 272 | } 273 | } 274 | sg = network_client.update_security_group(sg['id'], body) 275 | sg = sg['security_group'] 276 | changed = True 277 | 278 | if module.params['rules'] is not None: 279 | rules_changed = _update_sg_rules(module, network_client, sg, 280 | module.params['rules'], tenant_id) 281 | changed |= rules_changed 282 | 283 | return changed, sg 284 | 285 | 286 | def _update_sg_rules(module, network_client, sg, wanted_rules, tenant_id): 287 | """ 288 | Updates rules of a security group. 289 | """ 290 | 291 | changed = False 292 | existing_rules = sg['security_group_rules'] 293 | 294 | #check ok 295 | ok_rules = [] 296 | for new_rule in wanted_rules: 297 | # Ugly: define tenant also here so that matches 298 | new_rule['tenant_id'] = sg['tenant_id'] 299 | # protocol is in lowercase 300 | if 'protocol' in new_rule: 301 | new_rule['protocol'] = new_rule['protocol'].lower() 302 | 303 | matched_id = None 304 | for old_rule in existing_rules: 305 | clean_new_rule = new_rule.copy() 306 | clean_old_rule = old_rule.copy() 307 | old_id = clean_old_rule.pop('id') 308 | clean_old_rule.pop('security_group_id') 309 | for key in clean_old_rule.keys(): 310 | if key not in clean_new_rule: 311 | clean_new_rule[key] = None 312 | continue 313 | value = clean_new_rule[key] 314 | if isinstance(value, (str, unicode)) and value.isdigit() and \ 315 | key != 'tenant_id': 316 | clean_new_rule[key] = int(value) 317 | if cmp(clean_old_rule, clean_new_rule) == 0: 318 | matched_id = old_id 319 | break 320 | 321 | if matched_id: 322 | new_rule['done'] = True 323 | ok_rules.append(matched_id) 324 | 325 | #apply new first 326 | new_rules = [rule for rule in wanted_rules if 'done' not in rule] 327 | if len(new_rules): 328 | if not module.check_mode: 329 | sg = _create_sg_rules(network_client, sg, new_rules, tenant_id) 330 | changed = True 331 | 332 | #then delete not ok if not append 333 | if module.params['state'] != 'append': 334 | for rule in existing_rules: 335 | if rule['id'] in ok_rules: 336 | continue 337 | if not module.check_mode: 338 | sg = network_client.delete_security_group_rule(rule['id']) 339 | changed = True 340 | 341 | return changed 342 | 343 | 344 | def _create_sg_rules(network_client, sg, rules, tenant_id): 345 | """ 346 | Creates a set of security group rules in a given security group. 347 | :param network_client: network client to use to create rules. 348 | :param sg: security group to create rules in. 349 | :param rules: rules to create. 350 | :return: the updated security group. 351 | """ 352 | if rules: 353 | for rule in rules: 354 | if 'remote_group_name' in rule: 355 | rule['remote_group_id'] = _get_security_group_id(network_client, 356 | rule['remote_group_name'], 357 | tenant_id) 358 | rule.pop('remote_group_name', None) 359 | rule['tenant_id'] = sg['tenant_id'] 360 | rule['security_group_id'] = sg['id'] 361 | data = { 362 | 'security_group_rule': rule 363 | } 364 | network_client.create_security_group_rule(data) 365 | 366 | # fetch security group again to show end result 367 | return network_client.show_security_group(sg['id'])['security_group'] 368 | return sg 369 | 370 | 371 | def _get_security_group_id(network_client, group_name, tenant_id): 372 | """ 373 | Lookup the UUID for a named security group. This provides the ability to 374 | specify a SourceGroup via remote_group_id. 375 | 376 | http://docs.openstack.org/openstack-ops/content/security_groups.html 377 | 378 | This will return the first match to a group name. 379 | :param network_client: network client ot use to lookup group_id 380 | :param group_name: The name of the security group to lookup 381 | """ 382 | 383 | params = { 384 | 'name': group_name, 385 | 'tenant_id': tenant_id, 386 | 'fields': 'id' 387 | } 388 | 389 | return network_client.list_security_groups(**params)['security_groups'][0]['id'] 390 | 391 | 392 | def _get_tenant_id(module, identity_client): 393 | """ 394 | Returns the tenant_id, given tenant_name. 395 | if tenant_name is not specified in the module params uses login_tenant_name 396 | if tenant_name is not specified and login_tenant_id is defined, it uses that. 397 | :param identity_client: identity_client used to get the tenant_id from its 398 | name. 399 | :param module_params: module parameters. 400 | """ 401 | if not module.params['tenant_name']: 402 | if module.params['login_tenant_id']: 403 | return module.params['login_tenant_id'] 404 | 405 | # Use token to get ID to avoid using "admin"/internal call 406 | return identity_client.tenant_id 407 | else: 408 | return _get_tenant(identity_client, module.params['tenant_name']).id 409 | 410 | 411 | def _get_tenant(identity_client, tenant_name): 412 | """ 413 | Returns the tenant, given the tenant_name. 414 | :param identity_client: identity client to use to do the required requests. 415 | :param tenant_name: name of the tenant. 416 | :return: tenant for which the name was given. 417 | """ 418 | tenants = identity_client.tenants.list() 419 | tenant = next((t for t in tenants if t.name == tenant_name), None) 420 | if not tenant: 421 | raise Exception("Tenant with name '%s' not found." % tenant_name) 422 | 423 | return tenant 424 | 425 | 426 | def _get_network_client(module_params): 427 | """ 428 | :param module_params: module params containing the openstack credentials 429 | used to authenticate. 430 | :return: a neutron client. 431 | """ 432 | client = neutronclient.v2_0.client.Client( 433 | username=module_params.get('login_username'), 434 | password=module_params.get('login_password'), 435 | tenant_name=module_params.get('login_tenant_name'), 436 | auth_url=module_params.get('auth_url'), 437 | region_name=module_params.get('region_name')) 438 | 439 | return client 440 | 441 | 442 | def _get_identity_client(module_params): 443 | """ 444 | :param module_params: module params containing the openstack credentials 445 | used to authenticate. 446 | :return: a keystone client. 447 | """ 448 | client = keystoneclient.v2_0.client.Client( 449 | username=module_params.get('login_username'), 450 | password=module_params.get('login_password'), 451 | tenant_name=module_params.get('login_tenant_name'), 452 | auth_url=module_params.get('auth_url'), 453 | region_name=module_params.get('region_name')) 454 | 455 | return client 456 | 457 | 458 | # Let's get the party started! 459 | from ansible.module_utils.basic import * 460 | 461 | main() 462 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------