def setup_i2c(): if cuisine.file_exists('/etc/modprobe.d/raspi-blacklist.conf'): sudo('sed -i -e \'s/^blacklist i2c-bcm2708/# blacklist i2c-bcm2708/g\' ' + '/etc/modprobe.d/raspi-blacklist.conf') else: # RASPBIAN Release 2015-01-31 or later boot_conf = cuisine.text_ensure_line( cuisine.file_read('/boot/config.txt'), 'dtparam=i2c_arm=on' ) cuisine.file_write( location = '/boot/config.txt', content = boot_conf, mode='755', sudo=True ) modules_conf = cuisine.text_ensure_line( cuisine.file_read('/etc/modules'), 'i2c-dev' ) cuisine.file_write( location = '/etc/modules', content = modules_conf, mode='644', sudo=True ) # Repeated Start Condition cuisine.file_write( location = '/etc/modprobe.d/i2c.conf', content = 'options i2c_bcm2708 combined=1\n', mode='644', sudo=True )
def get_devpanel_config(): print env.host with hide('output','running','warnings'): with show(): print green('[%s] Retrieving db-daemons.conf' % env.host, bold=True) for line in iter(cuisine.file_read('/opt/webenabled/compat/dbmgr/config/db-daemons.conf').splitlines()): if line.startswith('#'): continue db_daemons_conf[env.host] = line.split(':') with show(): print green('[%s] Retrieving db-shadow.conf' % env.host, bold=True) for line in iter(cuisine.file_read('/opt/webenabled/compat/dbmgr/config/db-shadow.conf').splitlines()): if line.startswith('#'): continue db_shadow_conf[env.host] = line.split(':') # Test MySQL access # args -N removes colum name and -B for batch (no design) test_mysql_access = run('mysql -NB -uroot -p1P@ssw0rd9 -e \'SELECT "OK" FROM DUAL\' ; true').endswith('OK')
def ssh_pam_config(): puts(green('Setup PAM for SSHD')) # setting PAM pam_ssh = '/etc/pam.d/sshd' if not 'pam_access.so' in cuisine.file_read(pam_ssh): cuisine.file_append(pam_ssh, 'account required pam_access.so') # check SSHD config if not 'UsePAM yes' in cuisine.file_read('/etc/ssh/sshd_config'): puts(yellow('\'UserPAM no\' in sshd_config ')) # Upload download_and_upload('ssh/%s-access.conf', '/etc/security/access.conf') puts(green('Success'))
def append_line_to_file(self, tag, add_line, filepath): ''' Append a line to a file on the remote filesystem if it's not there already. Look for the tag to see if the line is there already, in case the existing line has different spacing or tabbing than the new line. :type tag: string :param tag: tag to look for in existing lines :type add_line: string :param add_line: line to append to file :type filepath: string :param filepath: fully-qualified path to remote file ''' old_contents = cuisine.file_read(filepath) eol = cuisine.text_detect_eol(old_contents) old_contents = old_contents.rstrip(eol) old_contents = old_contents.split(eol) has_line = False for line in old_contents: print line if line.find(tag) != -1: has_line = True continue if not has_line: old_contents.append(add_line) cuisine.file_write(filepath, eol.join(old_contents) + eol)
def cloudstack_init(fqdn=None): puts(green('CloudStack Initialize')) if fqdn is None: abort('Please set FQDN\n\tex) $ fab .... rolename:"fqdn"') # 石川さんごめんなさい sudo('sed -i -e "s/SELINUX=enforcing/SELINUX=permissive/g" /etc/selinux/config') sudo('setenforce permissive') # Repository for CloudStack repository = '[cloudstack]\nname=cloudstack\n' repository += 'baseurl=http://cloudstack.apt-get.eu/rhel/4.2/\n' repository += 'enabled=1\n' repository += 'gpgcheck=0\n' cuisine.file_write('/etc/yum.repos.d/CloudStack.repo', repository) # Setting FQDN if not fqdn in cuisine.file_read('/etc/hosts'): sudo('sed -i -e "s/localhost/' + fqdn + ' localhost/" /etc/hosts') # NTP install_package('ntp') cuisine.upstart_ensure('ntpd') sudo('chkconfig ntpd on') download_and_upload('ntp/%s-ntp.conf', '/etc/ntp.conf', abort_flg=False) puts(green('Success')) #--------------------------------------# # NFS # #--------------------------------------# def nfs(directory): puts(green('Setup NFS')) if fqdn is None: abort('Please set Directory\n\tex) $ fab .... nfsrolename:"/etc/hogehoge"') # Install install_package('nfs-utils') # Start for name in [ 'rpcbind', 'nfs' ]: cuisine.upstart_ensure(name) sudo('chkconfig %s on' % name) # Create Directory cuisine.dir_ensure(directory, recursive=True) # Setting /etc/exports download_and_upload('nfs/%s-exports', '/etc/exports') sudo('exportfs -a') # Setting /etc/sysconfig/nfs download_and_upload('nfs/%s-nfs', '/etc/sysconfig/nfs') puts(green('Success'))
def config_puppet(): ''' Ensure the server directive is in puppet.conf ''' print(green("Writing puppet config file")) config_file = '/etc/puppet/puppet.conf' line1 = "[agent]" line2 = "server = %s" % env.puppet_server config_content = file_read(config_file) updated_config = text_ensure_line(config_content, line1, line2) file_write(config_file, updated_config)
def file_update(location, updater=lambda x: x, use_sudo=False): """ Updates the content of the given by passing the existing content of the remote file at the given location to the 'updater' function. Return true if file content was changed. """ assert file_exists(location), "File does not exists: " + location old_content = file_read(location) new_content = updater(old_content) if (old_content == new_content): return False runner = run_as_root if env.use_sudo or use_sudo else run runner('echo "%s" | openssl base64 -A -d -out %s' % (base64.b64encode(new_content), shell_safe(location))) return True
def uuid(self, vm=None): ''' Determine the underlying VM's UUID, which is useful for purposes like performing low-level control tasks via VBoxManage. ''' if not self._uuid.get(vm): runfile = os.path.join(self.directory, '.vagrant') with hide('running', 'stdout'): if not file_exists(runfile): self.up(vm=vm) # newer versions of vagrant use folders instead of a single JSON file if os.path.isdir(runfile): idfile = os.path.join(runfile, 'machines', vm or 'default', 'virtualbox', 'id') # when boxes are destroyed the folders persist, so we can't assume the box exists yet if not file_exists(idfile): self.up(vm=vm) self._uuid[vm] = file_read(idfile) else: runinfo = json.loads(file_read(runfile)) self._uuid[vm] = runinfo['active'].get(vm or 'default') return self._uuid.get(vm)
def setup_wlan(): if not cuisine.file_exists('/sys/class/net/wlan0'): return puts(fabric.colors.green('[Setting Wireless LAN]', True)) wifi_config = None try: (file, pathname, description) = imp.find_module('wifi_config', ['.']) wifi_config = imp.load_module("wifi_config", file, pathname, description) except ImportError: puts(fabric.colors.red('SKIP WiFi Configuration. (FAILED to load wifi_config.py)', True)) return cuisine.file_write( location = '/etc/wpa_supplicant/wpa_supplicant.conf', content = 'ctrl_interface=DIR=/var/run/wpa_supplicant GROUP=netdev\n' + 'update_config=1\n' + 'network={\n' + (' ssid=\"%s\"\n' % (wifi_config.WIFI_SSID)) + (' psk=%s\n' % (wifi_config.WIFI_PSK)) + ' key_mgmt=WPA-PSK\n' + ' proto=WPA2\n' + ' pairwise=CCMP\n' + ' group=CCMP\n' + '}\n', mode='600', sudo=True ) sudo('sed -i -e \'s/^wpa-roam \/etc\/wpa_supplicant\/wpa_supplicant.conf/' + 'wpa-conf \/etc\/wpa_supplicant\/wpa_supplicant.conf/\' /etc/network/interfaces') sudo('sed -i -e \'s/^iface wlan0 inet manual/iface wlan0 inet dhcp/\' /etc/network/interfaces') # NOTE: Wifi の場合は「ホスト名-wifi」でアクセスできるようにする dhclient_conf = cuisine.text_ensure_line( cuisine.file_read('/etc/dhcp/dhclient.conf'), 'interface "wlan0" { send host-name = concat (gethostname(), "-wifi"); }' ) cuisine.file_write( location = '/etc/dhcp/dhclient.conf', content = dhclient_conf, mode='644', sudo=True )
def download_and_upload(local, remote, abort_flg=True): host = env.hosts[0] origin = local if '%s' in origin: local = origin % host local = './config/' + local # Download if cuisine.file_exists(remote): data = cuisine.file_read(remote) tmp = ('-%s.bak.ignore' % host) f = open(local + tmp, 'w') f.write(data) puts(yellow('Download: %s ==> %s' % (remote, local + tmp))) f.close() # Upload def upload(local, remote, post=''): def _upload(local, remote): if not os.path.isfile(local): return False cuisine.file_upload(remote, local) puts(yellow('Upload: %s ==> %s' % (local, remote))) return True if _upload(local + post, remote): return True if '%s' in origin and _upload('./config/' + origin % 'default' + post, remote): return True return False if upload(local, remote, '.ignore'): # Debug return if upload(local, remote): # Main return # Abort str = 'Not Found %s' % local if not abort_flg: puts(yellow(str)) else: abort(str)
def find_replace_in_file(self, old_text, new_text, filepath): ''' Find and replace text in a file on the remote filesystem. :type old_text: string :param tag: text to replace :type new_text: string :param add_line: text to replace with :type filepath: string :param filepath: fully-qualified path to remote file ''' old_contents = cuisine.file_read(filepath) eol = cuisine.text_detect_eol(old_contents) old_contents = old_contents.split(eol) new_contents = [] for line in old_contents: print line new_line = line.replace(old_text, new_text) new_contents.append(new_line) cuisine.file_write(filepath, eol.join(new_contents))
def upgrade_agent(): puts(green('Upgrade Agent')) # Prepare upgrade_common() # Upgrade proxy(sudo, 'yum upgrade cloudstack-agent -y') # Verify path = '/etc/cloudstack/agent/environment.properties' str = 'paths.script=/usr/share/cloudstack-common' if not str in cuisine.file_read(path): cuisine.file_append(path, '\n%s\n' % str) # Restart cuisine.upstart_stop('cloudstack-agent') sudo('killall jsvc', warn_only=True) cuisine.upstart_ensure('cloudstack-agent') puts(green('Success'))
def sentry(): cuisine.run('virtualenv /var/opt/sentry/') cuisine.run('source /var/opt/sentry/bin/activate') cuisine.run('easy_install -UZ sentry') cuisine.run('sentry init /etc/sentry.conf.py') configuration = cuisine.file_read('/etc/sentry.conf.py') dictionnary = { "django.db.backends.sqlite3":"django.db.backends.mysql", "'NAME': os.path.join(CONF_ROOT, 'sentry.db')":"'NAME': 'sentry'", "'USER': '******'":"'USER': '******'", "'PASSWORD': ''":"'PASSWORD': '******'" } for old, new in dictionnary.iteritems(): configuration = configuration.replace(old, new) cuisine.file_write('/etc/sentry.conf.py', configuration) if not database_exists('sentry'): fabtools.mysql.create_database('sentry') cuisine.run('sentry --config=/etc/sentry.conf.py upgrade') fabtools.require.supervisor.process('sentry', command='sentry --config=/etc/sentry.conf.py start http', directory='/var/opt/sentry/', autorestart='true' )
def testRead(self): cuisine.file_read("/etc/passwd")
def testB( self ): print cuisine.file_read("/etc/passwd")
def get_config(key, default=None): filename = "/etc/installconfig/%s.pk" % key if cuisine.file_exists(filename): return pickle.loads(cuisine.file_read(filename)) else: return default
def read_vagrantfile(self, vm=None): return file_read(os.path.join(self.directory, 'Vagrantfile'))
def testRead( self ): cuisine.file_read("/etc/passwd")
def management(): puts(green('Setup Management Server')) # Install install_package('cloudstack-management') # Load File config = ConfigParser.SafeConfigParser() config.read(config_read_path('./config/management/db.ini')) user = config.get('cloud', 'user') password = config.get('cloud', 'password') deploy_user = config.get('deploy', 'user') deploy_password = config.get('deploy', 'password') server = config.get('deploy', 'server') if None in [ user, password, deploy_user, deploy_password, server ]: abort('Check config/agent/db.ini') # Initialize run('cloudstack-setup-databases "%s:%s@%s" "--deploy-as=%s:%s"' % (user, password, server, deploy_user, deploy_password)) tmp = 'Defaults:cloud !requiretty' if not '\n' + tmp in cuisine.file_read('/etc/sudoers'): cuisine.file_append('/etc/sudoers', '\nDefaults:cloud !requiretty\n') run('cloudstack-setup-management') sudo('chkconfig cloudstack-management on') sudo('chown cloud:cloud /var/log/cloudstack/management/catalina.out') # NFS Client for service in [ 'rpcbind', 'nfs' ]: cuisine.upstart_ensure(service) sudo('chkconfig %s on' % service) # Setting Storage cuisine.dir_ensure('/mnt/primary', recursive=True) cuisine.dir_ensure('/mnt/secondary', recursive=True) config.read(config_read_path('./config/management/nfs.ini')) nfs_primary_path = config.get('primary', 'path') nfs_primary_ip = config.get('primary', 'ipaddr') nfs_secondary_path = config.get('secondary', 'path') nfs_secondary_ip = config.get('secondary', 'ipaddr') if None in [ nfs_primary_path, nfs_primary_ip, nfs_secondary_path, nfs_secondary_ip ]: abort('Check config/agent/nfs.ini') sudo('mount -t nfs %s:%s /mnt/primary' % (nfs_primary_ip, nfs_primary_path)) sleep(5) sudo('mount -t nfs %s:%s /mnt/secondary' % (nfs_secondary_ip, nfs_secondary_path)) sleep(5) sudo('rm -rf /mnt/primary/*') sudo('rm -rf /mnt/secondary/*') proxy(sudo, '/usr/share/cloudstack-common/scripts/storage/secondary/cloud-install-sys-tmplt -m /mnt/secondary -u http://d21ifhcun6b1t2.cloudfront.net/templates/4.2/systemvmtemplate-2013-06-12-master-kvm.qcow2.bz2 -h kvm -F') sudo('sync') for dir in [ '/mnt/primary', '/mnt/secondary' ]: sudo('umount %s' % dir) sudo('rmdir %s' % dir) puts(green('Success'))