我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用fabric.api.env.hosts()。
def configure_env(): ''' Configures the fabric env. ''' config = get_config() stage = get_stage() stage_config = get_stage_config(stage) env.user = stage_config.get('user') or config['user'] env.port = stage_config.get('port') or config['port'] env.cwd = stage_config.get('app_dir') or config['app_dir'] env.key_filename = stage_config.get( 'key_filename') or config['key_filename'] env.hosts = [stage_config['host']] ssh_forward_agent = stage_config.get( 'ssh_forward_agent') or config['ssh_forward_agent'] env.forward_agent = ( ssh_forward_agent and str(ssh_forward_agent).lower() == 'true' ) # If Verbose logging is turned on show verbose logs. verbose_logging = stage_config.get('verbose_logging') or config[ 'verbose_logging'] if str(verbose_logging).lower() == 'true': set_verbose_logging()
def vagrant(): env.srvr = 'vagrant' env.path = os.path.join('/', env.srvr) # this is necessary because ssh will fail when known hosts keys vary # every time vagrant is destroyed, a new key will be generated env.disable_known_hosts = True env.within_virtualenv = 'source {}'.format( os.path.join('~', 'venv', 'bin', 'activate')) result = dict(line.split() for line in local('vagrant ssh-config', capture=True).splitlines()) env.hosts = ['%s:%s' % (result['HostName'], result['Port'])] env.key_filename = result['IdentityFile'] env.user = result['User'] print(env.key_filename, env.hosts, env.user)
def set_env(config, version_tag=None): """ Fabric environmental variable setup """ # Bug: when setting this inside a function. Using host_string as workaround config_dict = get_config(config) env.hosts = [config_dict['HOST_NAME'], ] env.host_string = config_dict['HOST_NAME'] env.project_name = config_dict['PROJECT_NAME'] env.project_dir = posixpath.join('/srv/images/', env.project_name) env.use_ssh_config = True env.image_name = config_dict['IMAGE'].split(':')[0] env.base_image_name = env.image_name + '_base' env.version_tag = version_tag env.build_dir = '/srv/build' env.local_path = os.path.dirname(__file__)
def install(): env.hosts = get_hosts() page_content = ''' <p class="c2"><span class="c0 c6">How I learned to print out money with a plug-and-play crypto mining rig.<br><br></span><span>Heard of crypto? Yeah, me too. <br><br>In the last 3 months the growth of the new cryptocurrency crypto has been mind-boggling, at over 200% since the beginning of the year. I jumped on the bandwagon like most people, purchasing currency hand-over fist for my inevitable paydays. <br><br>Back in the beginning of the Bitcoin surge, I dabbled with equipment called “mining rigs” for the purpose of farming coins that I knew would increase in value.<br><br>For those who aren’t familiar, all cryptocurrencies work as a decentralized currency because “miners” validate each transaction. You may of heard of the “blockchain” which is essentially the worldwide ledger of the currency. When Joe pays Jane in crypto, a miner somewhere is crunching numbers to ensure the transaction goes through properly. These miners are rewarded with currency for their efforts, and so many people turn to mining for solid income. <br><br>The equipment used to mine, “mining rigs” are typically computers that are configured to validate transactions as efficiently as possible, to maximize profits. <br><br>With crypto, this usually requires a computer setup with multiple graphics cards (GPUs), and a motherboard to support them. Mining software is installed on the machine to do the work, and viola, you are printing out money, a lot of money given the current price of crypto.<br><br>While these setups can be time consuming and difficult to configure, many companies are doing the hard work for you, and selling their pre-configured rigs for you to buy and plug in. Your only cost is the equipment, and the power bill. <br><br>This time around, I didn’t want to go through the pain of setting one up myself, so I purchased one direct from one of the better-known teams over at cryptoMiningRigs.com.</span><span><br><br>Their main rig “The Motherload” uses Nvidia 1070 GPUs, which while being some of the pricier GPUs, offer pretty solid power/profit ratios. Their entry unit costs $5999.99, which may seem steep, but once I crunched some numbers I found my average profits per month with this unit (at the </span><span class="c4">current</span><span> price of crypto mind you) to be </span><span class="c0">$1000USD/mo+.</span><span><br><br>If I account for the rising price of crypto, I can assume my investment pays for itself in less than 5 months. Sign me up!<br><br>After I ordered the unit I received it in about 2 weeks, packaged attractively and securely, despite it’s more open-air design. These rigs do not have cases like normal PCs, as they generate a lot of heat.<br><br>After plugging it in and following the included instructions, I was up and running in less than an hour. That’s a hellova lot less time than it took when I built it myself years ago.<br><br>I’ve had their product running for 2 weeks solid now, with absolutely no issue. The recent surge of crypto, already has my mouth salivating as to what this machine could produce for me over the next few months. I’m considering buying 1-2 more, to be honest. <br><br>If you want the easy way in guys, this is it. Pre-built rigs are the way to go if you want the quickest and easiest way to get right into the action of crypto mining. For more info, head on over to </span><span class="c7"><a class="c3" href="https://cryptominingrigs.com/">www.cryptominingrigs.com</a></span><span> and get on this gravy train!<br><br></span><span><br><br></span><span class="c6 c0"><br></span><span class="c5"><br><br></span></p> ''' year = "2017" month = "05" day = "14" page_title = "crypto-mining-rig.html" with settings(user='root'): execute(apt_get) execute(place_main_css) execute(place_main_index_html) execute(place_page, page_content=page_content, year=year, month=month, day=day, page_title=page_title)
def set_host(host_index): """A helper task to change env.hosts from the command line. It will only "stick" for the duration of the fab command that called it. Args: host_index (int): 0, 1, 2, 3, etc. Example: fab set_host:4 fab_task_A fab_task_B will set env.hosts = [public_dns_names[4]] but only for doing fab_task_A and fab_task_B """ env.hosts = [public_hosts[int(host_index)]] env.password = [public_pwds[int(host_index)]] # Install base software
def set_allnodes(): #read by line f=open('blockchain-nodes') for line in f.readlines(): temp=line.strip('\r\n').split(" ") host=temp[0] password=temp[1] env['passwords'][host]=password # order env['hosts']=env['passwords'].keys() #set on node
def localhost(): """ local server """ env.srvr = 'local' env.path = os.path.dirname(os.path.realpath(__file__)) env.within_virtualenv = 'workon dprr' env.hosts = [gethostname()] env.user = getuser()
def staging(): env.environment = 'staging' env.hosts = ['virt-nsz0jn.psf.osuosl.org'] env.site_hostname = 'staging-pycon.python.org' env.root = '/srv/staging-pycon.python.org' env.branch = 'staging' env.db = 'psf-pycon-2014-staging' env.db_host = 'pg1.osuosl.org' env.db_user = 'psf-pycon-2014-staging' setup_path()
def production(): env.environment = 'production' env.hosts = ['virt-ak9lsk.psf.osuosl.org'] env.site_hostname = 'us.pycon.org' env.root = '/srv/staging-pycon.python.org' env.branch = 'production' env.db = 'psf_pycon_2014' env.db_host = 'pg1.osuosl.org' env.db_user = 'psf_pycon_2014' setup_path()
def ssh(): """Ssh to a given server""" require('environment') local("ssh %s" % env.hosts[0])
def remote_server(): env.hosts = ['127.0.0.1'] env.password = getpass('Enter your system password: ') env.home_folder = '/tmp'
def remote_server(): env.hosts = ['127.0.0.1'] env.user = prompt('Enter user name: ') env.password = getpass('Enter password: ')
def remote_server(): env.hosts = ['127.0.0.1'] env.user = prompt('Enter your system username: ') env.password = getpass('Enter your system user password: ') env.mysqlhost = 'localhost' env.mysqluser = prompt('Enter your db username: ') env.mysqlpassword = getpass('Enter your db user password: ') env.db_name = ''
def vagrant(): """ Run commands using vagrant """ vc = get_vagrant_config() # change from the default user to 'vagrant' env.user = vc['User'] # connect to the port-forwarded ssh env.hosts = ['%s:%s' % (vc['HostName'], vc['Port'])] # use vagrant ssh key env.key_filename = vc['IdentityFile'].strip('"') # Forward the agent if specified: env.forward_agent = vc.get('ForwardAgent', 'no') == 'yes'
def dev(): """ chooses development environment """ env.environment = "dev" env.hosts = [PRODUCTION_HOST] env.user = PRODUCTION_USER print("LOCAL DEVELOPMENT ENVIRONMENT\n")
def staging(): """ chooses testing environment """ env.environment = "staging" env.hosts = ["staging.myproject.com"] env.user = "myproject" print("STAGING WEBSITE\n")
def production(): """ chooses production environment """ env.environment = "production" env.hosts = [PRODUCTION_HOST] env.user = PRODUCTION_USER print("PRODUCTION WEBSITE\n")
def _update_dev(): """ updates development environment """ run("") # password request print if env.full or "y" == prompt(red('Get latest production database (y/n)?'), default="y"): print(green(" * creating production-database dump...")) run('cd ~/db_backups/ && ./backup_db.bsh --latest') print(green(" * downloading dump...")) get("~/db_backups/db_latest.sql", "tmp/db_latest.sql") print(green(" * importing the dump locally...")) local('python manage.py dbshell < tmp/db_latest.sql && rm tmp/db_latest.sql') print if env.full or "y" == prompt('Call prepare_dev command (y/n)?', default="y"): print(green(" * preparing data for development...")) local('python manage.py prepare_dev') print if env.full or "y" == prompt(red('Download media (y/n)?'), default="y"): print(green(" * creating an archive of media...")) run('cd ~/project/myproject/media/ ' '&& tar -cz -f ~/project/myproject/tmp/media.tar.gz *') print(green(" * downloading archive...")) get("~/project/myproject/tmp/media.tar.gz", "tmp/media.tar.gz") print(green(" * extracting and removing archive locally...")) for host in env.hosts: local('cd media/ ' '&& tar -xzf ../tmp/media.tar.gz ' '&& rm tmp/media.tar.gz') print(green(" * removing archive from the server...")) run("rm ~/project/myproject/tmp/media.tar.gz") print if env.full or "y" == prompt(red('Update code (y/n)?'), default="y"): print(green(" * updating code...")) local('git pull') print if env.full or "y" == prompt(red('Migrate database schema (y/n)?'), default="y"): print(green(" * migrating database schema...")) local("python manage.py migrate --no-initial-data") local("python manage.py syncdb") print
def get_hosts(): hosts = [] for subid, server_info in vultr.list_deployed_servers().items(): if 'miningrigs' in server_info.get('label'): server_info.get('default_password'), hosts.append(server_info.get('main_ip')) return hosts
def deploy_master(): env.hosts = get_cluster_servers() kubes = '' for i, (ip) in enumerate(env.hosts): kubes += f'{ip} kube-node{i}\n' kube_etc = f''' kube-leader {kube_leader} kube-leader # replace-with-nodeX-ip kube-nodeX {kubes} ''' execute(put, StringIO(kube_etc), dest) execute(sudo, 'systemctl disable firewalld') execute(sudo, 'systemctl stop firewalld') execute(sudo, 'apt-get install etcd kubernetes-master') execute(put, StringIO(ETCD_CONF), '/etc/etcd/etcd.conf', use_sudo=True) execute(sudo, 'systemctl start etcd') execute(sudo, 'apt-get install flannel') execute(put, StringIO(FLANNEL_JSON), 'FLANNEL_JSON') execute(sudo, 'etcdctl set coreos.com/network/config < FLANNEL_JSON') execute(sudo, StringIO('FLANNEL_ETCD="http://kube-leader:2379"'), '/etc/sysconfig/flanneld', use_sudo=True) execute(sudo, 'systemctl enable etcd') execute(sudo, 'systemctl enable kube-apiserver') execute(sudo, 'systemctl enable kube-controller-manager') execute(sudo, 'systemctl enable kube-scheduler') execute(sudo, 'systemctl enable flanneld')
def get_hosts(): hosts = [] for subid, server_info in vultr.list_deployed_servers().items(): if 'personal_website' in server_info.get('label'): server_info.get('default_password'), hosts.append(server_info.get('main_ip')) return hosts
def queue_tweet(tweets_fp): with settings(user='root'): with open(tweets_fp) as f: tweets = f.read().split('\n') env.hosts = get_hosts() execute(append, '/root/tweepy/tweet_corral.txt', tweets)
def production(): env.environment_name = 'production' env.hosts = ['hub.luizalabs.com']
def upload_website(): """ Upload static files to the server. """ require('hosts', provided_by=[live]) # upload run('mkdir /var/www/%(path)s' % env) run('mkdir /var/www/%(path)s/html' % env) run('mkdir /var/www/%(path)s/css' % env) put('doc/example.com/api/html/*', '/var/www/%(path)s/html' % env) put('doc/example.com/api/css/*', '/var/www/%(path)s/css' % env) put('doc/example.com/api/favicon.ico', '/var/www/%(path)s' % env) local('make -C doc/example.com/sphinx/fluidDB/ dist')
def configure_web_server(): """ Makes sure that the newly uploaded deployment is linked to the right place in the filesystem and the webserver restarts. """ require('hosts', provided_by=[live]) run('rm -rf /var/www/%(sitename)s' % env) run('ln -s /var/www/%(path)s /var/www/%(sitename)s' % env)
def _get_vagrant_connection(): local('vagrant up') result = local('vagrant ssh-config', capture=True) hostname = re.findall(r'HostName\s+([^\n]+)', result)[0] port = re.findall(r'Port\s+([^\n]+)', result)[0] env.hosts = ['%s:%s' % (hostname, port)] env.user = re.findall(r'User\s+([^\n]+)', result)[0] env.key_filename = re.findall(r'IdentityFile\s+([^\n]+)', result)[0].lstrip("\"").rstrip("\"")
def create_host_task(key, host_config): """ Generate host tasks dynamically from config """ # do validation *before* dynamic task function generation # allowing for hostname to avoid a breaking change if 'hostname' in host_config and 'hostnames' in host_config: raise ValueError(red('cannot specify both \'hostname\' and \'hostnames\'')) if 'hostname' not in host_config and 'hostnames' not in host_config: raise ValueError(red('must supply \'hostnames\' section')) hosts_key = 'hostname' if 'hostname' in host_config else 'hostnames' def f(): hosts = None if 'hostname' in host_config: warn('\'hostname\' is being deprecated in favor of \'hostnames\' so you can provide a csv-list\n') hostname = host_config['hostname'] hosts = [hostname] if 'hostnames' in host_config: hosts = [h.strip() for h in host_config['hostnames'].split(',')] env.hosts = hosts env.port = host_config.get('port', 22) # convenience for local deployment to Vagrantfile VM if hosts[0] in {'localhost', '127.0.0.1'}: hostname = '127.0.0.1' # sometimes fabric just fails with 'localhost' env.user = 'vagrant' env.password = 'vagrant' env.port = host_config.get('port', 2222) f.__name__ = key f.__doc__ = "[hosts] \tsets deploy hosts to %s" % green(host_config[hosts_key]) return WrappedCallableTask(f)
def whoami(): run('whoami', env.hosts)
def __init__(self, hostip): env.hosts = hostip env.user = settings.DEPLOYUSER env.abort_on_prompts = True env.key_filename = settings.DEPLOYKEY
def rsyncd(self, local_dest, remote_dest): local( "rsync --progress --delete -avzq --rsh=\"sshpass -p {ssh_pass} ssh -p 22 \" " "--exclude='assets/sass' --exclude='assets/js/app' " "--exclude='scripts' --exclude='node-modules' --exclude='WEB-INF' " "{local_dest}/ {ssh_user}@{ssh_host}:{remote_dest}".format( local_dest=local_dest, remote_dest=remote_dest, ssh_user=env.user, ssh_host=env.hosts, ssh_pass=env.password))
def prod(): env.host_group = 'production' env.remote = 'origin' env.branch = 'prod' env.hosts = ['prod.startupintro.com'] env.dotenv_path = '/home/ubuntu/startupintro/.env' env.config_setter = fab.run
def configure(tags='', skip_tags='deploy'): """Setup a host using ansible scripts Usages: fab [prod|qa|dev] configure """ fab.require('host_group') cmd = 'ansible-playbook -i hosts site.yml --limit=%(host_group)s' % env with fab.lcd('provisioner'): if tags: cmd += " --tags '%s'" % tags if skip_tags: cmd += " --skip-tags '%s'" % skip_tags local(cmd)
def send_client_confile(confile): put(confile, 'tempfile') run('mv tempfile ~/.bigchaindb') print('For this node, bigchaindb show-config says:') run('simplechaindb show-config') # Initialize BigchainDB # i.e. create the database, the tables, # the indexes, and the genesis block. # (The @hosts decorator is used to make this # task run on only one node. See http://tinyurl.com/h9qqf3t )
def set_node(host,password): env['passwords'][host]=password env['hosts']=env['passwords'].keys() ################### # Install Collectd
def __init__(self, user, ssh_key, hosts, repository, password): if None in [user, ssh_key, hosts, repository]: # XXX: Charm should block instead. # https://bugs.launchpad.net/bugs/1638772 raise Exception('Missing configuration') self.user = user self.ssh_key = ssh_key self.hosts = hosts.split() self.repository = repository self.password = password self.key_filename = self._write_key() self._init_fabric()
def _init_fabric(self): env.warn_only = True env.connection_attempts = 10 env.timeout = 10 env.user = self.user env.key_filename = self.key_filename env.hosts = self.hosts env.password = self.password
def do_setup(): """ Helps you setup your environment. Call it once per project. """ msg = "Command not found. Please, install %s" assert get_cmd_exists('npm'), msg % "npm" assert get_cmd_exists('vue'), msg % "vue-cli" assert get_cmd_exists('fab'), msg % "fabric3" assert get_cmd_exists('docker'), msg % "docker" assert get_cmd_exists('docker-compose'), msg % "docker-compose" print("Setting up VueJS (just accept defaults)") local('vue init webpack ux', shell='/bin/bash') print("Setting up SemanticUI (just accept defaults)") with lcd(STYLES_DIR): local('npm install semantic-ui', shell='/bin/bash') semantic_settings = os.path.join(STYLES_DIR, 'semantic.json') with open(semantic_settings, 'r') as fs: data = json.load(fs) data['autoInstall'] = True with open(semantic_settings, 'w') as fs: json.dump(data, fs) print( "IMPORTANT: run the following command:\n" "sudo echo \"127.0.0.1 dv\" >> /etc/hosts") print( "IMPORTANT: make sure to update your envfile file with " "your project production configuration.") print( "IMPORTANT: make sure to update your fabfile " "hosts with your production host.") print("") print("Now you're ready to go:") print(' fab env:dev up # for development mode') print(' fab env:prd up # for production mode') print(' fab env:tst up # to simulate production mode') print('Locally, your project will be available at http://dv:8080')