Systems Administration

https://d33wubrfki0l68.cloudfront.net/d5eeffae7269c828f8bf55bb7cf566d4788eec83/c0d28/_images/34435690580_3afec7d4cd_k_d.jpg

Fabric

Fabric is a library for simplifying systemadministration tasks. While Chef and Puppet tend to focus on managing serversand system libraries, Fabric is more focused on application level tasks suchas deployment.

Install Fabric:

  1. $ pip install fabric

The following code will create two tasks that we can use: memory_usage anddeploy. The former will output the memory usage on each machine. Thelatter will SSH into each server, cd to our project directory, activate thevirtual environment, pull the newest codebase, and restart the applicationserver.

  1. from fabric.api import cd, env, prefix, run, task
  2.  
  3. env.hosts = ['my_server1', 'my_server2']
  4.  
  5. @task
  6. def memory_usage():
  7. run('free -m')
  8.  
  9. @task
  10. def deploy():
  11. with cd('/var/www/project-env/project'):
  12. with prefix('. ../bin/activate'):
  13. run('git pull')
  14. run('touch app.wsgi')

With the previous code saved in a file named fabfile.py, we can checkmemory usage with:

  1. $ fab memory_usage
  2. [my_server1] Executing task 'memory'
  3. [my_server1] run: free -m
  4. [my_server1] out: total used free shared buffers cached
  5. [my_server1] out: Mem: 6964 1897 5067 0 166 222
  6. [my_server1] out: -/+ buffers/cache: 1509 5455
  7. [my_server1] out: Swap: 0 0 0
  8.  
  9. [my_server2] Executing task 'memory'
  10. [my_server2] run: free -m
  11. [my_server2] out: total used free shared buffers cached
  12. [my_server2] out: Mem: 1666 902 764 0 180 572
  13. [my_server2] out: -/+ buffers/cache: 148 1517
  14. [my_server2] out: Swap: 895 1 894

and we can deploy with:

  1. $ fab deploy

Additional features include parallel execution, interaction with remoteprograms, and host grouping.

Fabric Documentation

Salt

Salt is an open source infrastructure managementtool. It supports remote command execution from a central point (master host)to multiple hosts (minions). It also supports system states which can be usedto configure multiple servers using simple template files.

Salt supports Python versions 2.6 and 2.7 and can be installed via pip:

  1. $ pip install salt

After configuring a master server and any number of minion hosts, we can runarbitrary shell commands or use pre-built modules of complex commands on ourminions.

The following command lists all available minion hosts, using the ping module.

  1. $ salt '*' test.ping

The host filtering is accomplished by matching the minion idor using the grains system. Thegrainssystem uses static host information like the operating system version or theCPU architecture to provide a host taxonomy for the Salt modules.

The following command lists all available minions running CentOS using thegrains system:

  1. $ salt -G 'os:CentOS' test.ping

Salt also provides a state system. States can be used to configure the minionhosts.

For example, when a minion host is ordered to read the following state file,it will install and start the Apache server:

  1. apache:
  2. pkg:
  3. - installed
  4. service:
  5. - running
  6. - enable: True
  7. - require:
  8. - pkg: apache

State files can be written using YAML, the Jinja2 template system, or pure Python.

Salt Documentation

Psutil

Psutil is an interface to differentsystem information (e.g. CPU, memory, disks, network, users, and processes).

Here is an example to be aware of some server overload. If any of thetests (net, CPU) fail, it will send an email.

  1. # Functions to get system values:
  2. from psutil import cpu_percent, net_io_counters
  3. # Functions to take a break:
  4. from time import sleep
  5. # Package for email services:
  6. import smtplib
  7. import string
  8. MAX_NET_USAGE = 400000
  9. MAX_ATTACKS = 4
  10. attack = 0
  11. counter = 0
  12. while attack <= MAX_ATTACKS:
  13. sleep(4)
  14. counter = counter + 1
  15. # Check the cpu usage
  16. if cpu_percent(interval = 1) > 70:
  17. attack = attack + 1
  18. # Check the net usage
  19. neti1 = net_io_counters()[1]
  20. neto1 = net_io_counters()[0]
  21. sleep(1)
  22. neti2 = net_io_counters()[1]
  23. neto2 = net_io_counters()[0]
  24. # Calculate the bytes per second
  25. net = ((neti2+neto2) - (neti1+neto1))/2
  26. if net > MAX_NET_USAGE:
  27. attack = attack + 1
  28. if counter > 25:
  29. attack = 0
  30. counter = 0
  31. # Write a very important email if attack is higher than 4
  32. TO = "you@your_email.com"
  33. FROM = "webmaster@your_domain.com"
  34. SUBJECT = "Your domain is out of system resources!"
  35. text = "Go and fix your server!"
  36. BODY = string.join(("From: %s" %FROM,"To: %s" %TO,"Subject: %s" %SUBJECT, "",text), "\r\n")
  37. server = smtplib.SMTP('127.0.0.1')
  38. server.sendmail(FROM, [TO], BODY)
  39. server.quit()

A full terminal application like a widely extended top which is based onpsutil and with the ability of a client-server monitoring isglance.

Ansible

Ansible is an open source system automation tool.The biggest advantage over Puppet or Chef is it does not require an agent onthe client machine. Playbooks are Ansible’s configuration, deployment, andorchestration language and are written in YAML with Jinja2 for templating.

Ansible supports Python versions 2.6 and 2.7 and can be installed via pip:

  1. $ pip install ansible

Ansible requires an inventory file that describes the hosts to which it hasaccess. Below is an example of a host and playbook that will ping all thehosts in the inventory file.

Here is an example inventory file:hosts.yml

  1. [server_name]
  2. 127.0.0.1

Here is an example playbook:ping.yml

  1. ---
  2. - hosts: all
  3.  
  4. tasks:
  5. - name: ping
  6. action: ping

To run the playbook:

  1. $ ansible-playbook ping.yml -i hosts.yml --ask-pass

The Ansible playbook will ping all of the servers in the hosts.yml file.You can also select groups of servers using Ansible. For more informationabout Ansible, read the Ansible Docs.

An Ansible tutorial is also agreat and detailed introduction to getting started with Ansible.

Chef

Chef is a systems and cloud infrastructure automationframework that makes it easy to deploy servers and applications to any physical,virtual, or cloud location. In case this is your choice for configuration management,you will primarily use Ruby to write your infrastructure code.

Chef clients run on every server that is part of your infrastructure and these regularlycheck with your Chef server to ensure your system is always aligned and represents thedesired state. Since each individual server has its own distinct Chef client, each serverconfigures itself and this distributed approach makes Chef a scalable automation platform.

Chef works by using custom recipes (configuration elements), implemented in cookbooks. Cookbooks, which are basicallypackages for infrastructure choices, are usually stored in your Chef server.Read the DigitalOcean tutorial serieson Chef to learn how to create a simple Chef Server.

To create a simple cookbook the knife command is used:

  1. knife cookbook create cookbook_name

Getting started with Chefis a good starting point for Chef Beginners and many community maintained cookbooks that canserve as a good reference or tweaked to serve your infrastructure configuration needs can befound on the Chef Supermarket.

Puppet

Puppet is IT Automation and configuration managementsoftware from Puppet Labs that allows System Administrators to define the stateof their IT Infrastructure, thereby providing an elegant way to manage theirfleet of physical and virtual machines.

Puppet is available both as an Open Source and an Enterprise variant. Modulesare small, shareable units of code written to automate or define the state of asystem. Puppet Forge is a repository formodules written by the community for Open Source and Enterprise Puppet.

Puppet Agents are installed on nodes whose state needs to be monitored orchanged. A designated server known as the Puppet Master is responsible fororchestrating the agent nodes.

Agent nodes send basic facts about the system such as the operating system,kernel, architecture, IP address, hostname, etc. to the Puppet Master.The Puppet Master then compiles a catalog with information provided by theagents on how each node should be configured and sends it to the agent. Theagent enforces the change as prescribed in the catalog and sends a report backto the Puppet Master.

Facter is an interesting tool that ships with Puppet that pulls basic factsabout the system. These facts can be referenced as a variable while writingyour Puppet modules.

  1. $ facter kernel
  2. Linux
  1. $ facter operatingsystem
  2. Ubuntu

Writing Modules in Puppet is pretty straight forward. Puppet Manifests togetherform Puppet Modules. Puppet manifests end with an extension of .pp.Here is an example of ‘Hello World’ in Puppet.

  1. notify { 'This message is getting logged into the agent node':
  2.  
  3. #As nothing is specified in the body the resource title
  4. #the notification message by default.
  5. }

Here is another example with system based logic. Note how the operating systemfact is being used as a variable prepended with the $ sign. Similarly, thisholds true for other facts such as hostname which can be referenced by$hostname.

  1. notify{ 'Mac Warning':
  2. message => $operatingsystem ? {
  3. 'Darwin' => 'This seems to be a Mac.',
  4. default => 'I am a PC.',
  5. },
  6. }

There are several resource types for Puppet but the package-file-serviceparadigm is all you need for undertaking the majority of the configurationmanagement. The following Puppet code makes sure that the OpenSSH-Serverpackage is installed in a system and the sshd service is notified to restartevery time the sshd configuration file is changed.

  1. package { 'openssh-server':
  2. ensure => installed,
  3. }
  4.  
  5. file { '/etc/ssh/sshd_config':
  6. source => 'puppet:///modules/sshd/sshd_config',
  7. owner => 'root',
  8. group => 'root',
  9. mode => '640',
  10. notify => Service['sshd'], # sshd will restart
  11. # whenever you edit this
  12. # file
  13. require => Package['openssh-server'],
  14.  
  15. }
  16.  
  17. service { 'sshd':
  18. ensure => running,
  19. enable => true,
  20. hasstatus => true,
  21. hasrestart=> true,
  22. }

For more information, refer to the Puppet Labs Documentation

Blueprint

Todo

Write about Blueprint

Buildout

Buildout is an open source software build tool.Buildout is created using the Python programming language. It implements aprinciple of separation of configuration from the scripts that do the settingup. Buildout is primarily used to download and set up dependencies in Pythoneggsformat of the software being developed or deployed. Recipes for build tasks inany environment can be created, and many are already available.

Shinken

Shinken is a modern, Nagios compatiblemonitoring framework written in Python. Its main goal is to give users a flexiblearchitecture for their monitoring system that is designed to scale to largeenvironments.

Shinken is backwards-compatible with the Nagios configuration standard andplugins. It works on any operating system and architecture that supports Python,which includes Windows, Linux, and FreeBSD.

原文: https://docs.python-guide.org/scenarios/admin/