Ansible

Материал из Tech_support
Перейти к навигации Перейти к поиску

Установка Ansible на Debian 9

Ansible это система управления конфигурациями, которая используется для управления большим количеством однотипных (выполняющих одни и те же функции) хостов. В отличие от большинства конкурентов, таких как Puppet, Chef не требует установки собственного программного обеспечения - достаточно иметь доступ к компьютеру, например по SSH. Для управления конфигурациями Ansible использует Playbooks - специальным образом описанные на языке YAML сценарии.

Для установки Ansible на системах, использующих пакетный менеджер apt достаточно выполнить apt-get install.

apt-get instal ansible

Проверить, что ansible установился корректно можно командой:

ansible --version

Все настройки ansible находятся в папке /etc/ansible.

  • пример рабочего /etc/ansible/ansible.conf:

  1  # config file for ansible -- http://ansible.com/
  2  # ==============================================
  3  
  4  # nearly all parameters can be overridden in ansible-playbook
  5  # or with command line flags. ansible will read ANSIBLE_CONFIG,
  6  # ansible.cfg in the current working directory, .ansible.cfg in
  7  # the home directory or /etc/ansible/ansible.cfg, whichever it
  8  # finds first
  9  
 10  [defaults]
 11  
 12  # some basic default values...
 13  
 14  '''inventory      = /etc/ansible/hosts'''
 15  ##- создайте папку /etc/ansible/playbooks/ - для своих '''playbooks.yaml'''
 16  '''library        = /etc/ansible/playbooks/'''
 17  '''remote_tmp     = ~/.ansible/tmp'''
 18  '''local_tmp      = ~/.ansible/tmp'''
 19  #forks          = 5
 20  #poll_interval  = 15
 21  '''sudo_user      = remotemyuser'''
 22  '''ask_sudo_pass = False'''
 23  '''ask_pass      = False'''
 24  '''transport      = smart'''
 25  '''remote_port    = 22'''
 26  #module_lang    = C
 27  #module_set_locale = False
 28  
 29  # plays will gather facts by default, which contain information about
 30  # the remote system.
 31  #
 32  # smart - gather by default, but don't regather if already gathered
 33  # implicit - gather by default, turn off with gather_facts: False
 34  # explicit - do not gather by default, must say gather_facts: True
 35  #gathering = implicit
 36  
 37  # by default retrieve all facts subsets
 38  # all - gather all subsets
 39  # network - gather min and network facts
 40  # hardware - gather hardware facts (longest facts to retrieve)
 41  # virtual - gather min and virtual facts
 42  # facter - import facts from facter
 43  # ohai - import facts from ohai
 44  # You can combine them using comma (ex: network,virtual)
 45  # You can negate them using ! (ex: !hardware,!facter,!ohai)
 46  # A minimal set of facts is always gathered.
 47  #gather_subset = all
 48  
 49  # some hardware related facts are collected
 50  # with a maximum timeout of 10 seconds. This
 51  # option lets you increase or decrease that
 52  # timeout to something more suitable for the
 53  # environment. 
 54  # gather_timeout = 10
 55  
 56  # additional paths to search for roles in, colon separated
 57  #roles_path    = /etc/ansible/roles
 58  
 59  # uncomment this to disable SSH key host checking
 60  #host_key_checking = False
 61  
 62  # change the default callback
 63  #stdout_callback = skippy
 64  # enable additional callbacks
 65  #callback_whitelist = timer, mail
 66  
 67  # Determine whether includes in tasks and handlers are "static" by
 68  # default. As of 2.0, includes are dynamic by default. Setting these
 69  # values to True will make includes behave more like they did in the
 70  # 1.x versions.
 71  #task_includes_static = True
 72  #handler_includes_static = True
 73  
 74  # Controls if a missing handler for a notification event is an error or a warning
 75  #error_on_missing_handler = True
 76  
 77  # change this for alternative sudo implementations
 78  #sudo_exe = sudo
 79  
 80  # What flags to pass to sudo
 81  # WARNING: leaving out the defaults might create unexpected behaviours
 82  #sudo_flags = -H -S -n
 83  
 84  # SSH timeout
 85  #timeout = 10
 86  
 87  # default user to use for playbooks if user is not specified
 88  # (/usr/bin/ansible will use current user as default)
 89  '''remote_user = remotemyuser'''
 90  
 91  # logging is off by default unless this path is defined
 92  # if so defined, consider logrotate
 93  #log_path = /var/log/ansible.log
 94  
 95  # default module name for /usr/bin/ansible
 96  #module_name = command
 97  
 98  # use this shell for commands executed under sudo
 99  # you may need to change this to bin/bash in rare instances
100  # if sudo is constrained
101  #executable = /bin/sh
102  
103  # if inventory variables overlap, does the higher precedence one win
104  # or are hash values merged together?  The default is 'replace' but
105  # this can also be set to 'merge'.
106  #hash_behaviour = replace
107  
108  # by default, variables from roles will be visible in the global variable
109  # scope. To prevent this, the following option can be enabled, and only
110  # tasks and handlers within the role will see the variables there
111  #private_role_vars = yes
112  
113  # list any Jinja2 extensions to enable here:
114  #jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n
115  
116  # if set, always use this private key file for authentication, same as
117  # if passing --private-key to ansible or ansible-playbook
118  #private_key_file = /path/to/file
119  
120  # If set, configures the path to the Vault password file as an alternative to
121  # specifying --vault-password-file on the command line.
122  #vault_password_file = /path/to/vault_password_file
123  
124  # format of string {{ ansible_managed }} available within Jinja2
125  # templates indicates to users editing templates files will be replaced.
126  # replacing {file}, {host} and {uid} and strftime codes with proper values.
127  #ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}
128  # {file}, {host}, {uid}, and the timestamp can all interfere with idempotence
129  # in some situations so the default is a static string:
130  #ansible_managed = Ansible managed
131  
132  # by default, ansible-playbook will display "Skipping [host]" if it determines a task
133  # should not be run on a host.  Set this to "False" if you don't want to see these "Skipping"
134  # messages. NOTE: the task header will still be shown regardless of whether or not the
135  # task is skipped.
136  #display_skipped_hosts = True
137  
138  # by default, if a task in a playbook does not include a name: field then
139  # ansible-playbook will construct a header that includes the task's action but
140  # not the task's args.  This is a security feature because ansible cannot know
141  # if the *module* considers an argument to be no_log at the time that the
142  # header is printed.  If your environment doesn't have a problem securing
143  # stdout from ansible-playbook (or you have manually specified no_log in your
144  # playbook on all of the tasks where you have secret information) then you can
145  # safely set this to True to get more informative messages.
146  #display_args_to_stdout = False
147  
148  # by default (as of 1.3), Ansible will raise errors when attempting to dereference
149  # Jinja2 variables that are not set in templates or action lines. Uncomment this line
150  # to revert the behavior to pre-1.3.
151  #error_on_undefined_vars = False
152  
153  # by default (as of 1.6), Ansible may display warnings based on the configuration of the
154  # system running ansible itself. This may include warnings about 3rd party packages or
155  # other conditions that should be resolved if possible.
156  # to disable these warnings, set the following value to False:
157  #system_warnings = True
158  
159  # by default (as of 1.4), Ansible may display deprecation warnings for language
160  # features that should no longer be used and will be removed in future versions.
161  # to disable these warnings, set the following value to False:
162  #deprecation_warnings = True
163  
164  # (as of 1.8), Ansible can optionally warn when usage of the shell and
165  # command module appear to be simplified by using a default Ansible module
166  # instead.  These warnings can be silenced by adjusting the following
167  # setting or adding warn=yes or warn=no to the end of the command line
168  # parameter string.  This will for example suggest using the git module
169  # instead of shelling out to the git command.
170  # command_warnings = False
171  
172  
173  # set plugin path directories here, separate with colons
174  #action_plugins     = /usr/share/ansible/plugins/action
175  #cache_plugins      = /usr/share/ansible/plugins/cache
176  #callback_plugins   = /usr/share/ansible/plugins/callback
177  #connection_plugins = /usr/share/ansible/plugins/connection
178  #lookup_plugins     = /usr/share/ansible/plugins/lookup
179  #inventory_plugins  = /usr/share/ansible/plugins/inventory
180  #vars_plugins       = /usr/share/ansible/plugins/vars
181  #filter_plugins     = /usr/share/ansible/plugins/filter
182  #test_plugins       = /usr/share/ansible/plugins/test
183  #strategy_plugins   = /usr/share/ansible/plugins/strategy
184  
185  # by default callbacks are not loaded for /bin/ansible, enable this if you
186  # want, for example, a notification or logging callback to also apply to
187  # /bin/ansible runs
188  #bin_ansible_callbacks = False
189  
190  
191  # don't like cows?  that's unfortunate.
192  # set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1
193  #nocows = 1
194  
195  # set which cowsay stencil you'd like to use by default. When set to 'random',
196  # a random stencil will be selected for each task. The selection will be filtered
197  # against the `cow_whitelist` option below.
198  #cow_selection = default
199  #cow_selection = random
200  
201  # when using the 'random' option for cowsay, stencils will be restricted to this list.
202  # it should be formatted as a comma-separated list with no spaces between names.
203  # NOTE: line continuations here are for formatting purposes only, as the INI parser
204  #       in python does not support them.
205  #cow_whitelist=bud-frogs,bunny,cheese,daemon,default,dragon,elephant-in-snake,elephant,eyes,\
206  #              hellokitty,kitty,luke-koala,meow,milk,moofasa,moose,ren,sheep,small,stegosaurus,\
207  #              stimpy,supermilker,three-eyes,turkey,turtle,tux,udder,vader-koala,vader,www
208  
209  # don't like colors either?
210  # set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1
211  #nocolor = 1
212  
213  # if set to a persistent type (not 'memory', for example 'redis') fact values
214  # from previous runs in Ansible will be stored.  This may be useful when
215  # wanting to use, for example, IP information from one group of servers
216  # without having to talk to them in the same playbook run to get their
217  # current IP information.
218  #fact_caching = memory
219  
220  
221  # retry files
222  # When a playbook fails by default a .retry file will be created in ~/
223  # You can disable this feature by setting retry_files_enabled to False
224  # and you can change the location of the files by setting retry_files_save_path
225  
226  #retry_files_enabled = False
227  #retry_files_save_path = ~/.ansible-retry
228  
229  # squash actions
230  # Ansible can optimise actions that call modules with list parameters
231  # when looping. Instead of calling the module once per with_ item, the
232  # module is called once with all items at once. Currently this only works
233  # under limited circumstances, and only with parameters named 'name'.
234  #squash_actions = apk,apt,dnf,homebrew,package,pacman,pkgng,yum,zypper
235  
236  # prevents logging of task data, off by default
237  #no_log = False
238  
239  # prevents logging of tasks, but only on the targets, data is still logged on the master/controller
240  #no_target_syslog = False
241  
242  # controls whether Ansible will raise an error or warning if a task has no
243  # choice but to create world readable temporary files to execute a module on
244  # the remote machine.  This option is False by default for security.  Users may
245  # turn this on to have behaviour more like Ansible prior to 2.1.x.  See
246  # https://docs.ansible.com/ansible/become.html#becoming-an-unprivileged-user
247  # for more secure ways to fix this than enabling this option.
248  #allow_world_readable_tmpfiles = False
249  
250  # controls the compression level of variables sent to
251  # worker processes. At the default of 0, no compression
252  # is used. This value must be an integer from 0 to 9.
253  #var_compression_level = 9
254  
255  # controls what compression method is used for new-style ansible modules when
256  # they are sent to the remote system.  The compression types depend on having
257  # support compiled into both the controller's python and the client's python.
258  # The names should match with the python Zipfile compression types:
259  # * ZIP_STORED (no compression. available everywhere)
260  # * ZIP_DEFLATED (uses zlib, the default)
261  # These values may be set per host via the ansible_module_compression inventory
262  # variable
263  #module_compression = 'ZIP_DEFLATED'
264  
265  # This controls the cutoff point (in bytes) on --diff for files
266  # set to 0 for unlimited (RAM may suffer!).
267  #max_diff_size = 1048576
268  
269  [privilege_escalation]
270  '''become=True'''
271  '''become_method=sudo'''
272  '''become_user=root'''
273  '''become_ask_pass=False'''
274  
275  [paramiko_connection]
276  
277  # uncomment this line to cause the paramiko connection plugin to not record new host
278  # keys encountered.  Increases performance on new host additions.  Setting works independently of the
279  # host key checking setting above.
280  #record_host_keys=False
281  
282  # by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this
283  # line to disable this behaviour.
284  #pty=False
285  
286  [ssh_connection]
287  
288  # ssh arguments to use
289  # Leaving off ControlPersist will result in poor performance, so use
290  # paramiko on older platforms rather than removing it, -C controls compression use
291  #ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s
292  
293  # The path to use for the ControlPath sockets. This defaults to
294  # "%(directory)s/ansible-ssh-%%h-%%p-%%r", however on some systems with
295  # very long hostnames or very long path names (caused by long user names or
296  # deeply nested home directories) this can exceed the character limit on
297  # file socket names (108 characters for most platforms). In that case, you
298  # may wish to shorten the string below.
299  #
300  # Example:
301  # control_path = %(directory)s/%%h-%%r
302  #control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r
303  
304  # Enabling pipelining reduces the number of SSH operations required to
305  # execute a module on the remote server. This can result in a significant
306  # performance improvement when enabled, however when using "sudo:" you must
307  # first disable 'requiretty' in /etc/sudoers
308  #
309  # By default, this option is disabled to preserve compatibility with
310  # sudoers configurations that have requiretty (the default on many distros).
311  #
312  #pipelining = False
313  
314  # Control the mechanism for transfering files
315  #   * smart = try sftp and then try scp [default]
316  #   * True = use scp only
317  #   * False = use sftp only
318  #scp_if_ssh = smart
319  
320  # if False, sftp will not use batch mode to transfer files. This may cause some
321  # types of file transfer failures impossible to catch however, and should
322  # only be disabled if your sftp version has problems with batch mode
323  #sftp_batch_mode = False
324  
325  [accelerate]
326  #accelerate_port = 5099
327  #accelerate_timeout = 30
328  #accelerate_connect_timeout = 5.0
329  
330  # The daemon timeout is measured in minutes. This time is measured
331  # from the last activity to the accelerate daemon.
332  #accelerate_daemon_timeout = 30
333  
334  # If set to yes, accelerate_multi_key will allow multiple
335  # private keys to be uploaded to it, though each user must
336  # have access to the system via SSH to add a new key. The default
337  # is "no".
338  #accelerate_multi_key = yes
339  
340  [selinux]
341  # file systems that require special treatment when dealing with security context
342  # the default behaviour that copies the existing context or uses the user default
343  # needs to be changed to use the file system dependent context.
344  #special_context_filesystems=nfs,vboxsf,fuse,ramfs
345  
346  # Set this to yes to allow libvirt_lxc connections to work without SELinux.
347  #libvirt_lxc_noseclabel = yes
348  
349  [colors]
350  #highlight = white
351  #verbose = blue
352  #warn = bright purple
353  #error = red
354  #debug = dark gray
355  #deprecate = purple
356  #skip = cyan
357  #unreachable = red
358  #ok = green
359  #changed = yellow
360  #diff_add = green
361  #diff_remove = red
362  #diff_lines = cyan

Для того, чтобы ansible могу управлять каким-либо хостом, необходимо сгенерировать ему файл ключа ssh с помощью ssh-keygen. На первый вопрос о том, в какой файл сгенерировать ключ нажать enter, на второй можно ввести парольную фразу с подтверждением, но тогда ее придется вводить всякий раз когда будет запрашиваться доступ к серверу, поэтому ее также оставляем пустой.

root@debian9:~# ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:AJZ2E5a+V+dNUvMbGdAwaj8xLiCJ9EkV7TaeSA5pr4I root@debian9
The key's randomart image is:
+---[RSA 2048]----+
|	ooo+.oo  ++  |
|   .+oB o  .. +o |
|   . +.*...o + oo|
|  	.=..++= +o.|
|  	..S.++oB  o|
|  	. .+ oo o. |
|	.  ..    	|
|   E . .     	|
|  	.      	|
+----[SHA256]-----+

Обменяться открытыми ключами с управляемым сервером с помощью команды ssh-copy-id <имя или ip сервера>. После этого при попытке соединиться с данным сервером автоматически прочтется ключ доступа и произойдет вход на целевой сервер без дополнительных запросов.

ssh-copy-id 10.0.0.2
ssh 10.0.0.2

ssh-copy-id root@10.0.0.2
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@10.0.0.2's password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh 'root@10.0.0.2'"
and check to make sure that only the key(s) you wanted were added.

root@debian9:~# ssh 10.0.0.2
Last login: Thu Jul 26 15:49:46 2018 from 185.11.35.28

  • Для Debian на каждом управляемом хосте внести еще 2 изменения:
1. внести своего удаленного пользователя в группу sudo
2. дописать в /etc/sudoers:
1     ... 
2     #includedir /etc/sudoers.d
3      '''%sudo ALL=NOPASSWD: ALL'''

Теперь можно добавить этот хост в файл:

/etc/ansible/hosts

Хост можно добавить отдельно или в любую группу, если хостов несколько, например в webservers

1  [webservers]
2  #alpha.example.org
3  #beta.example.org
4  #192.168.1.100
5  10.0.0.2
  • Проверим доступность хостов для Ansible:

ansible -m ping webservers 

$ ansible dnsservers -m ping
10.0.0.2 | success >> {
    "changed": false,
    "ping": "pong"
}

Теперь создадим какой-нибудь плейбук - например установим nginx на сервер с ОС Centos. ОС на управляющем и управляемом могут не совпадать.

nano /etc/ansible/nginst.yml
1  ---
2  - hosts: 10.0.0.2
3    tasks:
4     - name: Install Nginx
5   	yum: pkg=nginx state=latest

Здесь используются следующие команды:

   hosts: задает имя или ip хоста к которому применять данное действие. Можно вписать имя группы - тогда применится ко всем членам данной группы
   tasks: описание задачи
   name: Install Nginx - наименование задачи
   yum: pkg=nginx state=latest -действие. В данном случае это установить пакет nginx через yum, ключ state определяет что делать с пакетом
   latest означает установить или обновить до последней версии, если пакет есть
   present - просто установить
   absent - удалить пакет

Теперь запустим наш плейбук командой:

ansible-playbook /etc/ansible/nginst.yml

Если все сделано правильно, то вывод должен быть такой:

root@debian9:~# ansible-playbook /etc/ansible/nginst.yml

PLAY [10.0.0.2] ****************************************************************

TASK [setup] *******************************************************************
ok: [10.0.0.2]

TASK [Install Nginx] ***********************************************************
changed: [10.0.0.2]

PLAY RECAP *********************************************************************
10.0.0.2               	: ok=2	changed=1	unreachable=0	failed=0

После этого надо запустить nginx на целевом сервере.

Для системы Debian пример для обновления нескольких хостов:

# apt-update for servers
- hosts: mediaservers
  tasks:
    - name: Update dvr
      apt: upgrade=yes update_cache=yes cache_valid_time=86400
# update all web
- hosts: webservers
  tasks:
    - name: Update www
      apt: upgrade=yes update_cache=yes cache_valid_time=86400
# update mail
- hosts: mailservers
  tasks:
    - name: Update mail
      apt: upgrade=yes update_cache=yes cache_valid_time=86400

ПОЛЕЗНОЕ: