我的两个测试机:
系统:
ubuntu 16.04.2
ansible-master:
192.168.0.107
ansible-slave:
192.168.0.108
ansible版本:
root@ansible-master:/etc/ansible# ansible --version
ansible 2.0.0.2
config file = /etc/ansible/ansible.cfg
configured module search path = /usr/share/my_modules/
安装方法:
默认apt安装
安装命令:
apt install ansible -y
默认安装路径:
/etc/ansible
目录结构:

root@ansible-master:/etc/ansible# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg
└── hosts
0 directories, 2 files

/etc/ansible
├── ansible.cfg
├── hosts
├── hosts.yml
└── roles
└── booster
├── files
│ └── booster
├── handlers
│ └── main.yml
├── tasks
│ └── main.yml
└── templates
└── config.json.j2
一 实现master-->slave无密码登录
1.1 生成ssh秘钥文件
ssh-keygen -t rsa #生成密钥
1.2 将公钥分别发送到slave机器上
ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.0.108
1.3 ssh远程slave端
root@ansible-master:~# ssh root@192.168.0.108
Welcome to Ubuntu 16.04.2 LTS (GNU/Linux 4.4.0-62-generic x86_64)
* Documentation: https://help.ubuntu.com
* Management: https://landscape.canonical.com
* Support: https://ubuntu.com/advantage
94 packages can be updated.
44 updates are security updates.
Last login: Tue Jun 6 05:52:56 2017 from 192.168.0.107
root@ansible-slave:~#
######################################
无需输入密码,则ok
1.4 添加主机ip到hosts文件中
默认文件: /etc/ansible/hosts
root@ansible-master:/etc/ansible# cat hosts
[test] #可以设置组名,用[]括上
192.168.0.108 #slave 端ip

# config file for ansible -- http://ansible.com/
# ==============================================
# nearly all parameters can be overridden in ansible-playbook
# or with command line flags. ansible will read ANSIBLE_CONFIG,
# ansible.cfg in the current working directory, .ansible.cfg in
# the home directory or /etc/ansible/ansible.cfg, whichever it
# finds first
[defaults]
# some basic default values...
inventory = /etc/ansible/hosts
library = /usr/share/my_modules/
remote_tmp = $HOME/.ansible/tmp
forks = 5
poll_interval = 15
sudo_user = root
#ask_sudo_pass = True
#ask_pass = True
transport = smart
remote_port = 22
module_lang = C
# plays will gather facts by default, which contain information about
# the remote system.
#
# smart - gather by default, but don't regather if already gathered
# implicit - gather by default, turn off with gather_facts: False
# explicit - do not gather by default, must say gather_facts: True
gathering = implicit
# additional paths to search for roles in, colon separated
roles_path = /etc/ansible/roles
# uncomment this to disable SSH key host checking
#host_key_checking = False
# change the default callback
#stdout_callback = skippy
# enable additional callbacks
#callback_whitelist = timer, mail
# change this for alternative sudo implementations
sudo_exe = sudo
# What flags to pass to sudo
# WARNING: leaving out the defaults might create unexpected behaviours
#sudo_flags = -H -S -n
# SSH timeout
timeout = 10
# default user to use for playbooks if user is not specified
# (/usr/bin/ansible will use current user as default)
#remote_user = root
# logging is off by default unless this path is defined
# if so defined, consider logrotate
#log_path = /var/log/ansible.log
# default module name for /usr/bin/ansible
#module_name = command
# use this shell for commands executed under sudo
# you may need to change this to bin/bash in rare instances
# if sudo is constrained
#executable = /bin/sh
# if inventory variables overlap, does the higher precedence one win
# or are hash values merged together? The default is 'replace' but
# this can also be set to 'merge'.
#hash_behaviour = replace
# by default, variables from roles will be visible in the global variable
# scope. To prevent this, the following option can be enabled, and only
# tasks and handlers within the role will see the variables there
#private_role_vars = yes
# list any Jinja2 extensions to enable here:
#jinja2_extensions = jinja2.ext.do,jinja2.ext.i18n
# if set, always use this private key file for authentication, same as
# if passing --private-key to ansible or ansible-playbook
#private_key_file = /path/to/file
# format of string {{ ansible_managed }} available within Jinja2
# templates indicates to users editing templates files will be replaced.
# replacing {file}, {host} and {uid} and strftime codes with proper values.
ansible_managed = Ansible managed: {file} modified on %Y-%m-%d %H:%M:%S by {uid} on {host}
# This short version is better used in templates as it won't flag the file as changed every run.
#ansible_managed = Ansible managed: {file} on {host}
# by default, ansible-playbook will display "Skipping [host]" if it determines a task
# should not be run on a host. Set this to "False" if you don't want to see these "Skipping"
# messages. NOTE: the task header will still be shown regardless of whether or not the
# task is skipped.
#display_skipped_hosts = True
# by default (as of 1.3), Ansible will raise errors when attempting to dereference
# Jinja2 variables that are not set in templates or action lines. Uncomment this line
# to revert the behavior to pre-1.3.
#error_on_undefined_vars = False
# by default (as of 1.6), Ansible may display warnings based on the configuration of the
# system running ansible itself. This may include warnings about 3rd party packages or
# other conditions that should be resolved if possible.
# to disable these warnings, set the following value to False:
#system_warnings = True
# by default (as of 1.4), Ansible may display deprecation warnings for language
# features that should no longer be used and will be removed in future versions.
# to disable these warnings, set the following value to False:
#deprecation_warnings = True
# (as of 1.8), Ansible can optionally warn when usage of the shell and
# command module appear to be simplified by using a default Ansible module
# instead. These warnings can be silenced by adjusting the following
# setting or adding warn=yes or warn=no to the end of the command line
# parameter string. This will for example suggest using the git module
# instead of shelling out to the git command.
# command_warnings = False
# set plugin path directories here, separate with colons
action_plugins = /usr/share/ansible/plugins/action
callback_plugins = /usr/share/ansible/plugins/callback
connection_plugins = /usr/share/ansible/plugins/connection
lookup_plugins = /usr/share/ansible/plugins/lookup
vars_plugins = /usr/share/ansible/plugins/vars
filter_plugins = /usr/share/ansible/plugins/filter
test_plugins = /usr/share/ansible/plugins/test
# by default callbacks are not loaded for /bin/ansible, enable this if you
# want, for example, a notification or logging callback to also apply to
# /bin/ansible runs
#bin_ansible_callbacks = False
# don't like cows? that's unfortunate.
# set to 1 if you don't want cowsay support or export ANSIBLE_NOCOWS=1
#nocows = 1
# set which cowsay stencil you'd like to use by default. When set to 'random',
# a random stencil will be selected for each task. The selection will be filtered
# against the `cow_whitelist` option below.
#cow_selection = default
#cow_selection = random
# when using the 'random' option for cowsay, stencils will be restricted to this list.
# it should be formatted as a comma-separated list with no spaces between names.
# NOTE: line continuations here are for formatting purposes only, as the INI parser
# in python does not support them.
#cow_whitelist=bud-frogs,bunny,cheese,daemon,default,dragon,elephant-in-snake,elephant,eyes,
# hellokitty,kitty,luke-koala,meow,milk,moofasa,moose,ren,sheep,small,stegosaurus,
# stimpy,supermilker,three-eyes,turkey,turtle,tux,udder,vader-koala,vader,www
# don't like colors either?
# set to 1 if you don't want colors, or export ANSIBLE_NOCOLOR=1
#nocolor = 1
# if set to a persistent type (not 'memory', for example 'redis') fact values
# from previous runs in Ansible will be stored. This may be useful when
# wanting to use, for example, IP information from one group of servers
# without having to talk to them in the same playbook run to get their
# current IP information.
fact_caching = memory
# retry files
# When a playbook fails by default a .retry file will be created in ~/
# You can disable this feature by setting retry_files_enabled to False
# and you can change the location of the files by setting retry_files_save_path
#retry_files_enabled = False
#retry_files_save_path = ~/.ansible-retry
# prevents logging of task data, off by default
#no_log = False
# prevents logging of tasks, but only on the targets, data is still logged on the master/controller
#no_target_syslog = False
# controls the compression level of variables sent to
# worker processes. At the default of 0, no compression
# is used. This value must be an integer from 0 to 9.
#var_compression_level = 9
[privilege_escalation]
#become=True
#become_method=sudo
#become_user=root
#become_ask_pass=False
[paramiko_connection]
# uncomment this line to cause the paramiko connection plugin to not record new host
# keys encountered. Increases performance on new host additions. Setting works independently of the
# host key checking setting above.
#record_host_keys=False
# by default, Ansible requests a pseudo-terminal for commands executed under sudo. Uncomment this
# line to disable this behaviour.
#pty=False
[ssh_connection]
# ssh arguments to use
# Leaving off ControlPersist will result in poor performance, so use
# paramiko on older platforms rather than removing it
#ssh_args = -o ControlMaster=auto -o ControlPersist=60s
# The path to use for the ControlPath sockets. This defaults to
# "%(directory)s/ansible-ssh-%%h-%%p-%%r", however on some systems with
# very long hostnames or very long path names (caused by long user names or
# deeply nested home directories) this can exceed the character limit on
# file socket names (108 characters for most platforms). In that case, you
# may wish to shorten the string below.
#
# Example:
# control_path = %(directory)s/%%h-%%r
#control_path = %(directory)s/ansible-ssh-%%h-%%p-%%r
# Enabling pipelining reduces the number of SSH operations required to
# execute a module on the remote server. This can result in a significant
# performance improvement when enabled, however when using "sudo:" you must
# first disable 'requiretty' in /etc/sudoers
#
# By default, this option is disabled to preserve compatibility with
# sudoers configurations that have requiretty (the default on many distros).
#
#pipelining = False
# if True, make ansible use scp if the connection type is ssh
# (default is sftp)
#scp_if_ssh = True
# if False, sftp will not use batch mode to transfer files. This may cause some
# types of file transfer failures impossible to catch however, and should
# only be disabled if your sftp version has problems with batch mode
#sftp_batch_mode = False
[accelerate]
accelerate_port = 5099
accelerate_timeout = 30
accelerate_connect_timeout = 5.0
# The daemon timeout is measured in minutes. This time is measured
# from the last activity to the accelerate daemon.
accelerate_daemon_timeout = 30
# If set to yes, accelerate_multi_key will allow multiple
# private keys to be uploaded to it, though each user must
# have access to the system via SSH to add a new key. The default
# is "no".
#accelerate_multi_key = yes
[selinux]
# file systems that require special treatment when dealing with security context
# the default behaviour that copies the existing context or uses the user default
# needs to be changed to use the file system dependent context.
#special_context_filesystems=nfs,vboxsf,fuse,ramfs
二 开始你的表演
2.1 ansible的第一条命令
ansible test -m ping
root@ansible-master:/etc/ansible# ansible test -m ping
组名或者ip 使用模块的参数 模块命令
192.168.0.108 | SUCCESS => {
"changed": false,
"ping": "pong"
}
界面显示返回值颜色为绿色则证明ping通。
2.2 可能遇到的报错
2.2.1 问题一
root@ansible-master:/etc/ansible# ansible test -m ping
192.168.0.108 | FAILED! => {
"changed": false,
"failed": true,
"module_stderr": "",
"module_stdout": "bash: /usr/bin/python: No such file or directory
",
"msg": "MODULE FAILURE",
"parsed": false
}
上面的报错是有提示的
"bash: /usr/bin/python: No such file or directory
"
所以在slave端装上pytho就ok了
2.2.2 问题二
如果slave节点上开启了SElinux,你需要安装libselinux-python,这样才可使用Ansible中与copy/file/template相关的函数.你可以通过Ansible的yum模块在需要的托管节点上安装libselinux-python
在返回值中也会有相对应的提示
2.2.3 问题三
/bin/sh: 1: /usr/bin/python: not found
这个问题出现在ubuntu16.04上,因为ubuntu16.04默认的是python3,而ansible需要的是python2
解决办法:
在客户端 apt安装 python-simplejson
大多数问题都会在返回值中提示,so 认真一点,耐心一点,都不是问题
三 ansible的命令参数
[root@ansiblemaster ansible]# ansible --help Usage: ansible <host-pattern> [options] Options: -a MODULE_ARGS, --args=MODULE_ARGS #(指定模块参数) module arguments --ask-vault-pass ask for vault password -B SECONDS, --background=SECONDS #(在后台运行命令,在制定NUM秒后kill该任务) run asynchronously, failing after X seconds (default=N/A) -C, --check don't make any changes; instead, try to predict some of the changes that may occur #(只是测试一下会改变什么内容,不会真正去执行) -D, --diff when changing (small) files and templates, show the differences in those files; works great with --check -e EXTRA_VARS, --extra-vars=EXTRA_VARS set additional variables as key=value or YAML/JSON -f FORKS, --forks=FORKS specify number of parallel processes to use (default=5) -h, --help show this help message and exit #(帮助信息) -i INVENTORY, --inventory-file=INVENTORY #(指定hosts文件路径,默认default=/etc/ansible/hosts) specify inventory host path (default=/etc/ansible/hosts) or comma separated host list. -l SUBSET, --limit=SUBSET further limit selected hosts to an additional pattern --list-hosts outputs a list of matching hosts; does not execute anything else -m MODULE_NAME, --module-name=MODULE_NAME #(指定模块) module name to execute (default=command) -M MODULE_PATH, --module-path=MODULE_PATH #(要执行的模块路径,默认为/usr/share/ansible) specify path(s) to module library (default=None) --new-vault-password-file=NEW_VAULT_PASSWORD_FILE new vault password file for rekey -o, --one-line condense output #(一个主机的执行结果在一行显示) --output=OUTPUT_FILE output file name for encrypt or decrypt; use - for stdout -P POLL_INTERVAL, --poll=POLL_INTERVAL set the poll interval if using -B (default=15) --syntax-check perform a syntax check on the playbook, but do not execute it -t TREE, --tree=TREE log output to this directory #(日志输出到该目录,日志文件名以主机名命名) --vault-password-file=VAULT_PASSWORD_FILE vault password file -v, --verbose verbose mode (-vvv for more, -vvvv to enable connection debugging) --version show program's version number and exit Connection Options: control as whom and how to connect to hosts -k, --ask-pass ask for connection password #(输入ssh密码,而不是使用秘钥) --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE use this file to authenticate the connection -u REMOTE_USER, --user=REMOTE_USER #(指定远程机器的用户) connect as this user (default=None) -c CONNECTION, --connection=CONNECTION #(指定建立连接的类型,一般有ssh,localhost FILES) connection type to use (default=smart) -T TIMEOUT, --timeout=TIMEOUT #(超时时间) override the connection timeout in seconds (default=10) --ssh-common-args=SSH_COMMON_ARGS specify common arguments to pass to sftp/scp/ssh (e.g. ProxyCommand) --sftp-extra-args=SFTP_EXTRA_ARGS specify extra arguments to pass to sftp only (e.g. -f, -l) --scp-extra-args=SCP_EXTRA_ARGS specify extra arguments to pass to scp only (e.g. -l) --ssh-extra-args=SSH_EXTRA_ARGS specify extra arguments to pass to ssh only (e.g. -R) Privilege Escalation Options: control how and which user you become as on target hosts -s, --sudo run operations with sudo (nopasswd) (deprecated, use become) -U SUDO_USER, --sudo-user=SUDO_USER desired sudo user (default=root) (deprecated, use become) -S, --su run operations with su (deprecated, use become) -R SU_USER, --su-user=SU_USER run operations with su as this user (default=root) (deprecated, use become) -b, --become run operations with become (does not imply password prompting) --become-method=BECOME_METHOD privilege escalation method to use (default=sudo), valid choices: [ sudo | su | pbrun | pfexec | runas | doas | dzdo ] --become-user=BECOME_USER run operations as this user (default=root) --ask-sudo-pass ask for sudo password (deprecated, use become) --ask-su-pass ask for su password (deprecated, use become) -K, --ask-become-pass #(提示输入sudo密码,与sudo一起使用) ask for privilege escalation password