ansible
openpyxl ansible saltstack
批量在主机上执行命名
与salt一样 用 Python2.7写的。
ansible 只需要在 主控制的机器上按上 通过ssh连接(密码,秘钥) 如果客户端开启了selinux(可以安装 libselinux-python跳过检查)
saltstack 需要在 主控机安装 stlt-master
管控机安装 salt-minion
安装
sudo apt-get install ansible yum install ansible
命令格式
ace@ace-i1102:~$ ansible --help
Usage: ansible <host-pattern> [options]
Define and run a single task 'playbook' against a set of hosts
Options:
-a MODULE_ARGS, --args=MODULE_ARGS 模块参数
module arguments
--ask-vault-pass ask for vault password
-B SECONDS, --background=SECONDS
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, if
filename prepend with @
-f FORKS, --forks=FORKS 用来做并发的
specify number of parallel processes to use
(default=5)
-h, --help show this help message and exit
-i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY
specify inventory host path or comma separated host
list. --inventory-file is deprecated
-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
prepend colon-separated path(s) to module library
(default=[u'/home/ace/.ansible/plugins/modules',
u'/usr/share/ansible/plugins/modules'])
-o, --one-line condense output
--playbook-dir=BASEDIR
Since this tool does not use playbooks, use this as a
subsitute playbook directory.This sets the relative
path for many features including roles/ group_vars/
etc.
-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-id=VAULT_IDS the vault identity to use
--vault-password-file=VAULT_PASSWORD_FILES
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
--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
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=None)
(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 | doas |
dzdo | ksu | runas | pmrun | enable ]
--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
ask for privilege escalation password
Some modules do not make sense in Ad-Hoc (include, meta, etc)

该命令会将 本地~/.ssh/id_rsa.pub(公钥) 拷贝到 远程机器的家目录下的 .ssh下 会有一个 名字为authorized_keys的文件
本地.ssh 会多一个known_hosts的文件
在远程主机有authorized_keys文件的前提下 以后本地登录远程主机,不再需要密码
如果删除了本地的known_host文件,再登录会提示再次生成该文件
ssh 公钥
1- 拿到远程主机的公钥 ,加密本地的公钥以及登录信息
2- 远程主机,用私钥对该信息进行解密,通过,允许登录
ace@ace-i1102:~/.ssh$ ansible ***.***.*****.150 -m ping [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all' [WARNING]: Could not match supplied host pattern, ignoring: **.*****.***.150
ace@ace-i1102:/etc/ansible$ sudo vim hosts [port] ***.×××。×××。150 [port:vars] ansible_ssh_user="root" ansible_ssh_port= # ping走的是ICMP协议
# ansible所有命令都是走的ssh ace@ace-i1102:/etc/ansible$ ansible ××××××××.150 -m ping ××××××××××× | SUCCESS => { "changed": false, "ping": "pong" }
# ansible all -m ping
# ansibel ip,ip,ip -m ping
[port1]
192.168.1.[80:88] # host文件配置 : 代表到
# ansible port1 -m ping
# ansible port1 --list-hosts # web,port ‘web:db’ 交集 ’web:!db‘ web独有的 web:&db 交集
# 秘要分发脚本
#!/bin/bash
rm /root/.ssh/id_dsa
ssh-keygen -t dsa -f /root/.ssh/id_dsa -N ""
for ip in 31 41 7
do
sshpass -p123456 ssh-copy-id -i /root/.ssh/id_dsa.pub "-o StrictHostKeyChecking=no 172.16.1.$ip" #ssh参数
done
如果运行失败,去掉命令后面的“”“”
sshpass -p123456 ssh-copy-id -i /root/.ssh/id_dsa.pub "-o StrictHostKeyChecking=no 172.16.1.$ip -p52113"
# 秘钥检查脚本
#!/bin/bash if [ $# -ne 1 ]
then
echo "pls input one args"
exit 1
fi for ip in 31 41 7 do
echo ===========info 172.16.1.$ip==============
ssh 172.16.1.$ip $1 done
# 当秘钥失效,可以使用这个方式;不写密码;看上边的-k参数

安装产生的文件
ace@ace-i1102:~/.ssh$ sudo find /etc/ |grep ansible | more /etc/ansible /etc/ansible/hosts /etc/ansible/ansible.cfg # 配置文件
ansible-doc 查看模块帮助信息
ansible-doc [-l|-F|-s] [options] [-t <plugin type> ] [plugin] -j 以json格式显示所有模块信息 -l 列出所有的模块 -s 显示模块的摘要信息 # 直接显示模块的所有帮助信息
远端执行命令
command
# ace@ace-i1102:~$ ansible port -a 'ls'
ace@ace-i1102:~$ ansible port -m command -a 'ls'
xxx.xxx.xxx.150 | SUCCESS | rc=0 >> 2003378_www.shuoiliu.com.key 2003378_www.shuoiliu.com.pem online.sh
ace@ace-i1102:~$ ansible-doc -s command
- name: Executes a command on a remote node
command:
chdir: # Change into this directory before running the command.
creates: # A filename or (since 2.0) glob pattern, when it already exists, this step will *not* be run.
free_form: # (required) The command module takes a free form command to run. There is no parameter actually
named 'free form'. See the examples!
removes: # A filename or (since 2.0) glob pattern, when it does not exist, this step will *not* be run.
stdin: # Set the stdin of the command directly to the specified value.
warn: # If command_warnings are on in ansible.cfg, do not warn about this particular line if set to `no'.
ansible port -a 'chdir=/tmp pwd' # 先切换目录,在pwd ansible port -a 'creates=/tmp pwd' # 创建成功,pwd;失败,跳过 ansible port -a 'removes=/tmp pwd' # 如果removes的文件夹存在,继续执行后续命令
shell
ansible port -m shell -a 'echo "pas" | password --stdin alex'
> SHELL (/usr/lib/python2.7/dist-packages/ansible/modules/commands/shell.py) The `shell' module takes the command name followed by a list of space-delimited arguments. It is almost exactly like the [command] module but runs the command through a shell (`/bin/sh') on the remote node. For Windows targets, use the [win_shell] module instead. * note: This module has a corresponding action plugin. OPTIONS (= is mandatory): - chdir cd into this directory before running the command [Default: None] version_added: 0.6 - creates a filename, when it already exists, this step will *not* be run. [Default: None] - executable change the shell used to execute the command. Should be an absolute path to the executable. [Default: None] version_added: 0.9 = free_form The shell module takes a free form command to run, as a string. There's not an actual option named "free form". See the examples! [Default: None]
script
ansible db -m script -a '/root/m.sh' # 执行管控机上的文件 ansible web -m script -a 'creates=/root/a.sh /root/m.sh' # 查看的是被管控机上的文件是否存在; 存在就跳过
参数和shell一样
copy
ace@ace-i1102:~$ ansible-doc -s copy
- name: Copies files to remote locations
copy:
attributes: # Attributes the file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should contain the attributes in the
same order as the one displayed by `lsattr'.
backup: # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly.
checksum: # SHA1 checksum of the file being transferred. Used to valdiate that the copy of the file was successful. If this is not provided, ansible will use the local calculated checksum
of the src file.
content: # When used instead of `src', sets the contents of a file directly to the specified value. For anything advanced or with formatting also look at the template module.
decrypt: # This option controls the autodecryption of source files using vault.
dest: # (required) Remote absolute path where the file should be copied to. If `src' is a directory, this must be a directory too. If `dest' is a nonexistent path and if either `dest'
ends with "/" or `src' is a directory, `dest' is created. If `src' and `dest' are files, the parent directory of `dest' isn't created: the task
fails if it doesn't already exist.
directory_mode: # When doing a recursive copy set the mode for the directories. If this is not set we will use the system defaults. The mode is only set on directories which are newly created,
and will not affect those that already existed.
follow: # This flag indicates that filesystem links in the destination, if they exist, should be followed.
force: # the default is `yes', which will replace the remote file when contents are different than the source. If `no', the file will only be transferred if the destination does not
exist.
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
local_follow: # This flag indicates that filesystem links in the source tree, if they exist, should be followed.
mode: # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like `0644' or `01777'). Leaving off the leading zero
will likely have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx' or `u=rw,g=r,o=r').
owner: # Name of the user that should own the file/directory, as would be fed to `chown'.
remote_src: # If `no', it will search for `src' at originating/master machine. If `yes' it will go to the remote/target machine for the `src'. Default is `no'. Currently `remote_src' does
not support recursive copying.
selevel: # Level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
serole: # Role part of SELinux file context, `_default' feature works as for `seuser'.
setype: # Type part of SELinux file context, `_default' feature works as for `seuser'.
seuser: # User part of SELinux file context. Will default to system policy, if applicable. If set to `_default', it will use the `user' portion of the policy if available.
src: # Local path to a file to copy to the remote server; can be absolute or relative. If path is a directory, it is copied recursively. In this case, if path ends with "/", only
inside contents of that directory are copied to destination. Otherwise, if it does not end with "/", the directory itself with all contents is
copied. This behavior is similar to Rsync.
unsafe_writes: # Normally this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, sometimes systems are configured or just broken in ways that
prevent this. One example are docker mounted files, they cannot be updated atomically and can only be done in an unsafe manner. This boolean
option allows ansible to fall back to unsafe methods of updating files for those cases in which you do not have any other choice. Be aware that
this is subject to race conditions and can lead to data corruption.
validate: # The validation command to run before copying into place. The path to the file to validate is passed in via '%s' which must be present as in the example below. The command is
passed securely so shell features like expansion and pipes won't work.
ansible port -m copy -a 'src=~/123.txt dest=/root'
ansible 特性:幂等性: 相同命令,不管执行几次,结构都一样 # 根据da39a3ee5e6b4b0d3255bfef95601890afd80709值
file
在管控机上创建文件、文件夹、软链接、硬链接
ace@ace-i1102:~$ ansible-doc -s file
- name: Sets attributes of files
file:
attributes: # Attributes the file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should contain the attributes in the
same order as the one displayed by `lsattr'.
follow: # This flag indicates that filesystem links, if they exist, should be followed. Previous to Ansible 2.5, this was `no' by default.
force: # force the creation of the symlinks in two cases: the source file does not exist (but will appear later); the destination exists and is a file (so, we need to unlink the "path"
file and create symlink to the "src" file in place of it).
group: # Name of the group that should own the file/directory, as would be fed to `chown'.
mode: # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers (like `0644' or `01777'). Leaving off the leading zero
will likely have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx' or `u=rw,g=r,o=r').
owner: # Name of the user that should own the file/directory, as would be fed to `chown'.
path: # (required) path to the file being managed. Aliases: `dest', `name'
recurse: # recursively set the specified file attributes (applies only to state=directory)
selevel: # Level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
serole: # Role part of SELinux file context, `_default' feature works as for `seuser'.
setype: # Type part of SELinux file context, `_default' feature works as for `seuser'.
seuser: # User part of SELinux file context. Will default to system policy, if applicable. If set to `_default', it will use the `user' portion of the policy if available.
src: # path of the file to link to (applies only to `state=link' and `state=hard'). Will accept absolute, relative and nonexisting paths. Relative paths are not expanded.
state: # If `directory', all immediate subdirectories will be created if they do not exist, since 1.7 they will be created with the supplied permissions. If `file', the file will NOT be
created if it does not exist, see the [copy] or [template] module if you want that behavior. If `link', the symbolic link will be created or
changed. Use `hard' for hardlinks. If `absent', directories will be recursively deleted, and files or symlinks will be unlinked. Note that
`absent' will not cause `file' to fail if the `path' does not exist as the state did not change. If `touch' (new in 1.4), an empty file will be
created if the `path' does not exist, while an existing file or directory will receive updated file access and modification times (similar to the
way `touch` works from the command line).
unsafe_writes: # Normally this module uses atomic operations to prevent data corruption or inconsistent reads from the target files, sometimes systems are configured or just broken in ways that
prevent this. One example are docker mounted files, they cannot be updated atomically and can only be done in an unsafe manner. This boolean
option allows ansible to fall back to unsafe methods of updating files for those cases in which you do not have any other choice. Be aware that
this is subject to race conditions and can lead to data corruption.
ansible port -m file -a "path=/tmp/wupeiqi state=directory" 创建一个目录 ansible port -m file -a "path=/tmp/wupeiqi.txt state=touch" 创建一个文件 ansible port -m file -a "path=/tmp/t state=link src=/etc/init.d" 创建软连接 path是目标文件 src是源文件 hand ansible port -m file -a "path=/tmp/t state=absent " 删除文件
user
[root@liushuo ~]# ansible-doc user
- append
If `yes', add the user to the groups specified in `groups'.
If `no', user will only be added to the groups specified in `groups', removing them from all other
groups.
[Default: no]
type: bool
- comment
Optionally sets the description (aka `GECOS') of user account.
[Default: (null)]
- create_home
Unless set to `no', a home directory will be made for the user when the account is created or if the home
directory does not exist.
Changed from `createhome' to `create_home' in version 2.5.
(Aliases: createhome)[Default: yes]
type: bool
- expires
An expiry time for the user in epoch, it will be ignored on platforms that do not support this. Currently
supported on GNU/Linux, FreeBSD, and DragonFlyBSD.
Since version 2.6 you can remove the expiry time specify a negative value. Currently supported on
GNU/Linux and FreeBSD.
[Default: (null)]
version_added: 1.9
- force
This only affects `state=absent', it forces removal of the user and associated directories on supported
platforms. The behavior is the same as `userdel --force', check the man page for `userdel' on your system
for details and support.
[Default: no]
type: bool
- generate_ssh_key
Whether to generate a SSH key for the user in question. This will *not* overwrite an existing SSH key.
[Default: no]
type: bool
version_added: 0.9
- group
Optionally sets the user's primary group (takes a group name).
[Default: (null)]
- groups
List of groups user will be added to. When set to an empty string `''', `null', or `~', the user is
removed from all groups except the primary group. (`~' means `null' in YAML)
Before version 2.3, the only input format allowed was a comma separated string. Now this parameter
accepts a list as well as a comma separated string.
[Default: (null)]
- hidden
macOS only, optionally hide the user from the login window and system preferences.
The default will be 'True' if the `system' option is used.
[Default: (null)]
type: bool
version_added: 2.6
- home
Optionally set the user's home directory.
[Default: (null)]
- local
Forces the use of "local" command alternatives on platforms that implement it. This is useful in
environments that use centralized authentification when you want to manipulate the local users. I.E. it
uses `luseradd` instead of `useradd`.
This requires that these commands exist on the targeted host, otherwise it will be a fatal error.
[Default: no]
type: bool
version_added: 2.4
- login_class
Optionally sets the user's login class, a feature of most BSD OSs.
[Default: (null)]
- move_home
If set to `yes' when used with `home=', attempt to move the user's old home directory to the specified
directory if it isn't there already and the old home exists.
[Default: no]
type: bool
= name
Name of the user to create, remove or modify.
(Aliases: user)
- non_unique
Optionally when used with the -u option, this option allows to change the user ID to a non-unique value.
[Default: no]
type: bool
version_added: 1.1
- password
Optionally set the user's password to this crypted value.
On macOS systems, this value has to be cleartext. Beware of security issues.
To create a disabled account or Linux systems, set this to `'!'' or `'*''.
See https://docs.ansible.com/ansible/faq.html#how-do-i-generate-crypted-passwords-for-the-user-module for
details on various ways to generate these password values.
[Default: (null)]
- password_lock
Lock the password (usermod -L, pw lock, usermod -C). BUT implementation differs on different platforms,
this option does not always mean the user cannot login via other methods. This option does not disable
the user, only lock the password. Do not change the password in the same task. Currently supported on
Linux, FreeBSD, DragonFlyBSD, NetBSD, OpenBSD.
[Default: (null)]
type: bool
version_added: 2.6
- remove
This only affects `state=absent', it attempts to remove directories associated with the user. The
behavior is the same as `userdel --remove', check the man page for details and support.
[Default: no]
type: bool
- seuser
Optionally sets the seuser type (user_u) on selinux enabled systems.
[Default: (null)]
version_added: 2.1
- shell
Optionally set the user's shell.
On macOS, before version 2.5, the default shell for non-system users was /usr/bin/false. Since 2.5, the
default shell for non-system users on macOS is /bin/bash.
On other operating systems, the default shell is determined by the underlying tool being used. See Notes
for details.
[Default: (null)]
- skeleton
Optionally set a home skeleton directory. Requires create_home option!
[Default: (null)]
version_added: 2.0
- ssh_key_bits
Optionally specify number of bits in SSH key to create.
[Default: default set by ssh-keygen]
version_added: 0.9
- ssh_key_comment
Optionally define the comment for the SSH key.
[Default: ansible-generated on $HOSTNAME]
version_added: 0.9
- ssh_key_file
Optionally specify the SSH key filename. If this is a relative filename then it will be relative to the
user's home directory.
[Default: .ssh/id_rsa]
version_added: 0.9
- ssh_key_passphrase
Set a passphrase for the SSH key. If no passphrase is provided, the SSH key will default to having no
passphrase.
[Default: (null)]
version_added: 0.9
- ssh_key_type
Optionally specify the type of SSH key to generate. Available SSH key types will depend on implementation
present on target host.
[Default: rsa]
version_added: 0.9
- state
Whether the account should exist or not, taking action if the state is different from what is stated.
(Choices: absent 删除该用户, present)[Default: present]
- system
When creating an account `state=present', setting this to `yes' makes the user a system account. This
setting cannot be changed on existing users.
[Default: no]
type: bool
- uid
Optionally sets the `UID' of the user.
[Default: (null)]
- update_password
`always' will update passwords if they differ. `on_create' will only set the password for newly created
users.
(Choices: always, on_create)[Default: always]
version_added: 1.3
ansible port -m user -a 'name=mysql home=/tmp/mysql groups=root uid=2000'
ansible port -m user -a 'name=mysql stat=absent remove=yes' # 删除用户,并删除家目录
group
[root@liushuo ~]# ansible-doc -s group
- name: Add or remove groups
group:
gid: # Optional `GID' to set for the group.
local: # Forces the use of "local" command alternatives on platforms that implement it. This is useful in environments
that use centralized authentification when you want to manipulate the local
groups. I.E. it uses `lgroupadd` instead of `useradd`. This requires that these
commands exist on the targeted host, otherwise it will be a fatal error.
name: # (required) Name of the group to manage.
state: # Whether the group should be present or not on the remote host.
system: # If `yes', indicates that the group created is a system group.
ubuntu工具包
[root@liushuo ~]# ansible-doc -s apt
- name: Manages apt-packages
apt:
allow_unauthenticated: # Ignore if packages cannot be authenticated. This is useful for bootstrapping environments that manage their own apt-key setup. `allow_unauthenticated' is only supported with state: `install'/`present'
autoclean: # If `yes', cleans the local repository of retrieved package files that can no longer be downloaded.
autoremove: # If `yes', remove unused dependency packages for all module states except `build-dep'. It can also be used as the only option. Previous to version 2.4, autoclean was also an alias for autoremove, now it is its own separate command. See
documentation for further information.
cache_valid_time: # Update the apt cache if its older than the `cache_valid_time'. This option is set in seconds. As of Ansible 2.4, this sets `update_cache=yes'.
deb: # Path to a .deb package on the remote machine. If :// in the path, ansible will attempt to download deb before installing. (Version added 2.1)
default_release: # Corresponds to the `-t' option for `apt' and sets pin priorities
dpkg_options: # Add dpkg options to apt command. Defaults to '-o "Dpkg::Options::=--force-confdef" -o "Dpkg::Options::=--force-confold"' Options should be supplied as comma separated list
force: # Corresponds to the `--force-yes' to `apt-get' and implies `allow_unauthenticated: yes' This option will disable checking both the packages' signatures and the certificates of the web servers they are downloaded from. This option *is not*
the equivalent of passing the `-f' flag to `apt-get' on the command line **This is a destructive operation with the potential to destroy your system, and it should almost never be used.** Please also see
`man apt-get' for more information.
force_apt_get: # Force usage of apt-get instead of aptitude
install_recommends: # Corresponds to the `--no-install-recommends' option for `apt'. `yes' installs recommended packages. `no' does not install recommended packages. By default, Ansible will use the same defaults as the operating system. Suggested packages
are never installed.
name: # A list of package names, like `foo', or package specifier with version, like `foo=1.0'. Name wildcards (fnmatch) like `apt*' and version wildcards like `foo=1.0*' are also supported.
only_upgrade: # Only upgrade a package if it is already installed.
purge: # Will force purging of configuration files if the module state is set to `absent'.
state: # Indicates the desired package state. `latest' ensures that the latest version is installed. `build-dep' ensures the package build dependencies are installed.
update_cache: # Run the equivalent of `apt-get update' before the operation. Can be run as part of the package installation or as a separate step.
upgrade: # If yes or safe, performs an aptitude safe-upgrade. If full, performs an aptitude full-upgrade. If dist, performs an apt-get dist-upgrade. Note: This does not upgrade a specific package, use state=latest for that. Note: Since 2.4, apt-get
is used as a fall-back if aptitude is not present.
centos工具包 (并行)
[root@liushuo ~]# ansible-doc -s yum - name: Manages packages with the `yum' package manager yum: allow_downgrade: # Specify if the named package and version is allowed to downgrade a maybe already installed higher version of that package. Note that setting allow_downgrade=True can make this module behave in a non-idempotent way. The task could end up with a set of packages that does not match the complete list of specified packages to install (because dependencies between the downgraded package and others can cause changes to the packages which were in the earlier transaction). autoremove: # If `yes', removes all "leaf" packages from the system that were originally installed as dependencies of user-installed packages but which are no longer required by any such package. Should be used alone or when state is `absent' NOTE: This feature requires yum >= 3.4.3 (RHEL/CentOS 7+) bugfix: # If set to `yes', and `state=latest' then only installs updates that have been marked bugfix related. conf_file: # The remote yum configuration file to use for the transaction. disable_excludes: # Disable the excludes defined in YUM config files. If set to `all', disables all excludes. If set to `main', disable excludes defined in [main] in yum.conf. If set to `repoid', disable excludes defined for given repo id. disable_gpg_check: # Whether to disable the GPG checking of signatures of packages being installed. Has an effect only if state is `present' or `latest'. disable_plugin: # `Plugin' name to disable for the install/update operation. The disabled plugins will not persist beyond the transaction. disablerepo: # `Repoid' of repositories to disable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a `","'. As of Ansible 2.7, this can alternatively be a list instead of `","' separated string download_only: # Only download the packages, do not install them. enable_plugin: # `Plugin' name to enable for the install/update operation. The enabled plugin will not persist beyond the transaction. enablerepo: # `Repoid' of repositories to enable for the install/update operation. These repos will not persist beyond the transaction. When specifying multiple repos, separate them with a `","'. As of Ansible 2.7, this can alternatively be a list instead of `","' separated string exclude: # Package name(s) to exclude when state=present, or latest installroot: # Specifies an alternative installroot, relative to which all packages will be installed. list: # Package name to run the equivalent of yum list <package> against. In addition to listing packages, use can also list the following: `installed', `updates', `available' and `repos'. name: # A package name or package specifier with version, like `name-1.0'. If a previous version is specified, the task also needs to turn `allow_downgrade' on. See the `allow_downgrade' documentation for caveats with downgrading packages. When using state=latest, this can be `'*'' which means run `yum -y update'. You can also pass a url or a local path to a rpm file (using state=present). To operate on several packages this can accept a comma separated string of packages or (as of 2.0) a list of packages. releasever: # Specifies an alternative release from which all packages will be installed. security: # If set to `yes', and `state=latest' then only installs updates that have been marked security related. skip_broken: # Skip packages with broken dependencies(devsolve) and are causing problems. state: # Whether to install (`present' or `installed', `latest'), or remove (`absent' or `removed') a package. `present' and `installed' will simply ensure that a desired package is installed. `latest' will update the specified package if it's not of the latest available version. `absent' and `removed' will remove the specified package. Default is `None', however in effect the default action is `present' unless the `autoremove' option is¬ enabled for this module, then `absent' is inferred. update_cache: # Force yum to check if cache is out of date and redownload if needed. Has an effect only if state is `present' or `latest'. update_only: # When using latest, only update installed packages. Do not install packages. Has an effect only if state is `latest' use_backend: # This module supports `yum' (as it always has), this is known as `yum3'/`YUM3'/`yum-deprecated' by upstream yum developers. As of Ansible 2.7+, this module also supports `YUM4', which is the "new yum" and it has an `dnf' backend. By default, this module will select the backend based on the `ansible_pkg_mgr' fact. validate_certs: # This only applies if using a https url as the source of the rpm. e.g. for localinstall. If set to `no', the SSL certificates will not be validated. This should only set to `no' used on personally controlled sites using self-signed certificates as it avoids verifying the source site. Prior to 2.1 the code worked as if this was set to `yes'.
yum grouplist 查询包组 yum groupinstall -y 'Development Tools' 安装包组 rpm -qa |grep python2-pip 查看软件包是否安装成功 ansible web -m yum -a 'name=python2-pip' 安装python2-pip包 ansible web -m yum -a 'name=@Development Tools' 安装python2-pip包 yum web -m yum -a "list=iftop" 查看是否安装、仓库是否有该软件
service
service nginx start|stop|restart # centos6 chkconfig add nginx chkconfig nginx on 设置开机自启动 chkconfig --list systemctl start nginx # centos7 systemctl enable nginx # 设置开机自启动 ss -tnlp ansible web -m service -a 'name=nginx state=started' #启动服务 ansible web -m service -a 'name=nginx state=stopped' #停止服务 # state : restarted reloaded # enabled: yes
cron 定时任务
[root@liushuo ~]# ansible-doc -s cron
- name: Manage cron.d and crontab entries
cron:
backup: # If set, create a backup of the crontab before it is modified. The location of the backup is returned in the `backup_file' variable by this module.
cron_file: # If specified, uses this file instead of an individual user's crontab. If this is a relative path, it is interpreted with respect to /etc/cron.d. (If it is absolute, it will typically be /etc/crontab). Many linux distros expect (and some
require) the filename portion to consist solely of upper- and lower-case letters, digits, underscores, and hyphens. To use the `cron_file' parameter you must specify the `user' as well.
day: # Day of the month the job should run ( 1-31, *, */2, etc )
disabled: # If the job should be disabled (commented out) in the crontab. Only has effect if `state=present'.
env: # If set, manages a crontab's environment variable. New variables are added on top of crontab. "name" and "value" parameters are the name and the value of environment variable.
hour: # Hour when the job should run ( 0-23, *, */2, etc )
insertafter: # Used with `state=present' and `env'. If specified, the environment variable will be inserted after the declaration of specified environment variable.
insertbefore: # Used with `state=present' and `env'. If specified, the environment variable will be inserted before the declaration of specified environment variable.
job: # The command to execute or, if env is set, the value of environment variable. The command should not contain line breaks. Required if state=present.
minute: # Minute when the job should run ( 0-59, *, */2, etc )
month: # Month of the year the job should run ( 1-12, *, */2, etc )
name: # Description of a crontab entry or, if env is set, the name of environment variable. Required if state=absent. Note that if name is not set and state=present, then a new crontab entry will always be created, regardless of existing ones.
reboot: # If the job should be run at reboot. This option is deprecated. Users should use special_time.
special_time: # Special time specification nickname.
state: # Whether to ensure the job or environment variable is present or absent.
user: # The specific user whose crontab should be modified.
weekday: # Day of the week that the job should run ( 0-6 for Sunday-Saturday, *, etc )
python包管理 pip
[root@liushuo ~]# ansible-doc -s pip
- name: Manages Python library dependencies
pip:
chdir: # cd into this directory before running the command
editable: # Pass the editable flag.
executable: # The explicit executable or a pathname to the executable to be used to run pip for a specific version of Python
installed in the system. For example `pip-3.3', if there are both Python 2.7
and 3.3 installations in the system and you want to run pip for the Python 3.3
installation. It cannot be specified together with the 'virtualenv' parameter
(added in 2.1). By default, it will take the appropriate version for the python
interpreter use by ansible, e.g. pip3 on python 3, and pip2 or pip on python 2.
extra_args: # Extra arguments passed to pip.
name: # The name of a Python library to install or the url(bzr+,hg+,git+,svn+) of the remote package. This can be a
list (since 2.2) and contain version specifiers (since 2.7).
requirements: # The path to a pip requirements file, which should be local to the remote system. File can be specified as a
relative path if using the chdir option.
state: # The state of module The 'forcereinstall' option is only available in Ansible 2.1 and above.
umask: # The system umask to apply before installing the pip package. This is useful, for example, when installing on
systems that have a very restrictive umask by default (e.g., "0077") and you
want to pip install packages which are to be used by all users. Note that this
requires you to specify desired umask mode as an octal string, (e.g., "0022").
version: # The version number to install of the Python library specified in the `name' parameter.
virtualenv: # An optional path to a `virtualenv' directory to install into. It cannot be specified together with the
'executable' parameter (added in 2.1). If the virtualenv does not exist, it
will be created before installing packages. The optional
virtualenv_site_packages, virtualenv_command, and virtualenv_python options
affect the creation of the virtualenv.
virtualenv_command: # The command or a pathname to the command to create the virtual environment with. For example `pyvenv',
`virtualenv', `virtualenv2', `~/bin/virtualenv', `/usr/local/bin/virtualenv'.
virtualenv_python: # The Python executable used for creating the virtual environment. For example `python3.5', `python2.7'. When
not specified, the Python version used to run the ansible module is used. This
parameter should not be used when `virtualenv_command' is using `pyvenv' or the
`-m venv' module.
virtualenv_site_packages: # Whether the virtual environment will inherit packages from the global site-packages directory. Note that
this setting is changed on an already existing virtual environment it will not
have any effect, the environment must be deleted and newly created.
fetch
用来拉取 被控机上的文件,每个被控机都会创建一个文件夹,并且保留原来的目录格式
ansible web -m fetch -a 'dest=/tmp src=/var/log/cron'
playbook 剧本
- 创建一个用户alex ansible web -m user -a 'name=alex' - 创建一个用户组wusir ansible web -m group -a 'name=wusir' - 复制/etc/fstab文件到/tmp目录下面 ansible web -m copy -a 'dest=/tmp/fstab src=/etc/fstab' - 安装nginx ansible web -m yum -a 'name=nginx' - 安装redis ansible web -m yum -a 'name=redis' - 并新建crontab每天的晚上12点重启 nginx ansible web -m cron -a 'minute=0 hour=0 job=重启'
[root@liushuo ~]# ansible-playbook -h Usage: ansible-playbook [options] playbook.yml [playbook2 ...] Runs Ansible playbooks, executing the defined tasks on the targeted hosts. Options: --ask-vault-pass ask for vault password -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, if filename prepend with @ --flush-cache clear the fact cache for every host in inventory --force-handlers run handlers even if a task fails -f FORKS, --forks=FORKS specify number of parallel processes to use (default=5) -h, --help show this help message and exit -i INVENTORY, --inventory=INVENTORY, --inventory-file=INVENTORY specify inventory host path or comma separated host list. --inventory-file is deprecated -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 --list-tags list all available tags --list-tasks list all tasks that would be executed -M MODULE_PATH, --module-path=MODULE_PATH prepend colon-separated path(s) to module library (default=['/root/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']) --skip-tags=SKIP_TAGS only run plays and tasks whose tags do not match these values --start-at-task=START_AT_TASK start the playbook at the task matching this name --step one-step-at-a-time: confirm each task before running --syntax-check perform a syntax check on the playbook, but do not execute it -t TAGS, --tags=TAGS only run plays and tasks tagged with these values --vault-id=VAULT_IDS the vault identity to use --vault-password-file=VAULT_PASSWORD_FILES 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 --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 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=None) (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 | doas | dzdo | ksu | runas | pmrun | enable | machinectl ] --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 ask for privilege escalation password
# play.book.yml 以列表的格式写
- hosts: port # 之前写的
remote_user: root
tasks:
- name: createuser
user: name=wengang
- name: creategroup
group: name=gebixiaoguniang
ansible-playbook 123.yml
多台机器执行过程,所有机器都执行完第一个任务,在去执行第二个任务
收集的信息
# ansible port -m setup
ansible_all_ipv4_addresses 所有的ipv4地址
ansible_all_ipv6_addresses 所有的ipv6地址
ansible_architecture 系统的架构
ansible_date_time 系统时间
ansible_default_ipv4 系统的默认ipv4地址
ansible_distribution 系统名称
ansible_distribution_file_variety 系统的家族
ansible_distribution_major_version 系统的版本
ansible_domain 系统所在的域
ansible_fqdn 系统的主机名
ansible_hostname 系统的主机名,简写
ansible_os_family 系统的家族
ansible_processor_cores cpu的核数
ansible_processor_count cpu的颗数
ansible_processor_vcpus cpu的个数
ansible_facts里面的值 可以直接使用
ip | SUCCESS => { "ansible_facts": { "ansible_all_ipv4_addresses": [ "172.16.0.15" ], "ansible_all_ipv6_addresses": [], "ansible_apparmor": { "status": "disabled" }, "ansible_architecture": "x86_64", "ansible_bios_date": "01/01/2011", "ansible_bios_version": "Bochs", "ansible_cmdline": { "BOOT_IMAGE": "/boot/vmlinuz-3.10.0-514.26.2.el7.x86_64", "LANG": "C", "biosdevname": "0", "console": "tty0", "crashkernel": "auto", "net.ifnames": "0", "panic": "5", "ro": true, "root": "/dev/vda1" }, "ansible_date_time": { "date": "2019-04-03", "day": "03", "epoch": "1554297647", "hour": "21", "iso8601": "2019-04-03T13:20:47Z", "iso8601_basic": "20190403T212047815242", "iso8601_basic_short": "20190403T212047", "iso8601_micro": "2019-04-03T13:20:47.815324Z", "minute": "20", "month": "04", "second": "47", "time": "21:20:47", "tz": "CST", "tz_offset": "+0800", "weekday": "ζζδΈ", "weekday_number": "3", "weeknumber": "13", "year": "2019" }, "ansible_default_ipv4": { "address": "172.16.0.15", "alias": "eth0", "broadcast": "172.16.15.255", "gateway": "172.16.0.1", "interface": "eth0", "macaddress": "52:54:00:53:bc:82", "mtu": 1500, "netmask": "255.255.240.0", "network": "172.16.0.0", "type": "ether" }, "ansible_default_ipv6": {}, "ansible_device_links": { "ids": { "sr0": [ "ata-QEMU_DVD-ROM_QM00002" ] }, "labels": { "sr0": [ "config-2" ] }, "masters": {}, "uuids": { "sr0": [ "2019-01-22-18-05-35-00" ], "vda1": [ "49f819fd-e56d-48a4-86d3-7ebe0a68ec88" ] } }, "ansible_devices": { "sr0": { "holders": [], "host": "IDE interface: Intel Corporation 82371SB PIIX3 IDE [Natoma/Triton II]", "links": { "ids": [ "ata-QEMU_DVD-ROM_QM00002" ], "labels": [ "config-2" ], "masters": [], "uuids": [ "2019-01-22-18-05-35-00" ] }, "model": "QEMU DVD-ROM", "partitions": {}, "removable": "1", "rotational": "1", "sas_address": null, "sas_device_handle": null, "scheduler_mode": "cfq", "sectors": "75776", "sectorsize": "2048", "size": "37.00 MB", "support_discard": "0", "vendor": "QEMU", "virtual": 1 }, "vda": { "holders": [], "host": "SCSI storage controller: Red Hat, Inc Virtio block device", "links": { "ids": [], "labels": [], "masters": [], "uuids": [] }, "model": null, "partitions": { "vda1": { "holders": [], "links": { "ids": [], "labels": [], "masters": [], "uuids": [ "49f819fd-e56d-48a4-86d3-7ebe0a68ec88" ] }, "sectors": "104855552", "sectorsize": 512, "size": "50.00 GB", "start": "2048", "uuid": "49f819fd-e56d-48a4-86d3-7ebe0a68ec88" } }, "removable": "0", "rotational": "1", "sas_address": null, "sas_device_handle": null, "scheduler_mode": "", "sectors": "104857600", "sectorsize": "512", "size": "50.00 GB", "support_discard": "0", "vendor": "0x1af4", "virtual": 1 } }, "ansible_distribution": "CentOS", "ansible_distribution_file_parsed": true, "ansible_distribution_file_path": "/etc/redhat-release", "ansible_distribution_file_variety": "RedHat", "ansible_distribution_major_version": "7", "ansible_distribution_release": "Core", "ansible_distribution_version": "7.2.1511", "ansible_dns": { "nameservers": [ "183.60.83.19", "183.60.82.98" ], "options": { "rotate": true, "timeout": "1" } }, "ansible_domain": "", "ansible_effective_group_id": 0, "ansible_effective_user_id": 0, "ansible_env": { "HISTSIZE": "3000", "HISTTIMEFORMAT": "%F %T ", "HOME": "/root", "LANG": "zh_CN.UTF-8", "LESSOPEN": "||/usr/bin/lesspipe.sh %s", "LOGNAME": "root", "MAIL": "/var/mail/root", "PATH": "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin", "PROMPT_COMMAND": "history -a; ", "PWD": "/root", "SHELL": "/bin/bash", "SHLVL": "2", "SSH_CLIENT": "121.28.69.79 33900 9856", "SSH_CONNECTION": "121.28.69.79 33900 172.16.0.15 9856", "SSH_TTY": "/dev/pts/0", "TERM": "xterm-256color", "USER": "root", "XDG_RUNTIME_DIR": "/run/user/0", "XDG_SESSION_ID": "110321", "_": "/usr/bin/python" }, "ansible_eth0": { "active": true, "device": "eth0", "features": { "busy_poll": "off [fixed]", "fcoe_mtu": "off [fixed]", "generic_receive_offload": "on", "generic_segmentation_offload": "on", "highdma": "on [fixed]", "hw_tc_offload": "off [fixed]", "l2_fwd_offload": "off [fixed]", "large_receive_offload": "off [fixed]", "loopback": "off [fixed]", "netns_local": "off [fixed]", "ntuple_filters": "off [fixed]", "receive_hashing": "off [fixed]", "rx_all": "off [fixed]", "rx_checksumming": "on [fixed]", "rx_fcs": "off [fixed]", "rx_vlan_filter": "on [fixed]", "rx_vlan_offload": "off [fixed]", "rx_vlan_stag_filter": "off [fixed]", "rx_vlan_stag_hw_parse": "off [fixed]", "scatter_gather": "on", "tcp_segmentation_offload": "on", "tx_checksum_fcoe_crc": "off [fixed]", "tx_checksum_ip_generic": "on", "tx_checksum_ipv4": "off [fixed]", "tx_checksum_ipv6": "off [fixed]", "tx_checksum_sctp": "off [fixed]", "tx_checksumming": "on", "tx_fcoe_segmentation": "off [fixed]", "tx_gre_segmentation": "off [fixed]", "tx_gso_robust": "off [fixed]", "tx_ipip_segmentation": "off [fixed]", "tx_lockless": "off [fixed]", "tx_mpls_segmentation": "off [fixed]", "tx_nocache_copy": "off", "tx_scatter_gather": "on", "tx_scatter_gather_fraglist": "off [fixed]", "tx_sctp_segmentation": "off [fixed]", "tx_sit_segmentation": "off [fixed]", "tx_tcp6_segmentation": "on", "tx_tcp_ecn_segmentation": "on", "tx_tcp_segmentation": "on", "tx_udp_tnl_segmentation": "off [fixed]", "tx_vlan_offload": "off [fixed]", "tx_vlan_stag_hw_insert": "off [fixed]", "udp_fragmentation_offload": "on", "vlan_challenged": "off [fixed]" }, "hw_timestamp_filters": [], "ipv4": { "address": "172.16.0.15", "broadcast": "172.16.15.255", "netmask": "255.255.240.0", "network": "172.16.0.0" }, "macaddress": "52:54:00:53:bc:82", "module": "virtio_net", "mtu": 1500, "pciid": "virtio0", "promisc": false, "timestamping": [ "rx_software", "software" ], "type": "ether" }, "ansible_fips": false, "ansible_form_factor": "Other", "ansible_fqdn": "liushuo", "ansible_hostname": "liushuo", "ansible_interfaces": [ "lo", "eth0" ], "ansible_is_chroot": false, "ansible_kernel": "3.10.0-514.26.2.el7.x86_64", "ansible_lo": { "active": true, "device": "lo", "features": { "busy_poll": "off [fixed]", "fcoe_mtu": "off [fixed]", "generic_receive_offload": "on", "generic_segmentation_offload": "on", "highdma": "on [fixed]", "hw_tc_offload": "off [fixed]", "l2_fwd_offload": "off [fixed]", "large_receive_offload": "off [fixed]", "loopback": "on [fixed]", "netns_local": "on [fixed]", "ntuple_filters": "off [fixed]", "receive_hashing": "off [fixed]", "rx_all": "off [fixed]", "rx_checksumming": "on [fixed]", "rx_fcs": "off [fixed]", "rx_vlan_filter": "off [fixed]", "rx_vlan_offload": "off [fixed]", "rx_vlan_stag_filter": "off [fixed]", "rx_vlan_stag_hw_parse": "off [fixed]", "scatter_gather": "on", "tcp_segmentation_offload": "on", "tx_checksum_fcoe_crc": "off [fixed]", "tx_checksum_ip_generic": "on [fixed]", "tx_checksum_ipv4": "off [fixed]", "tx_checksum_ipv6": "off [fixed]", "tx_checksum_sctp": "on [fixed]", "tx_checksumming": "on", "tx_fcoe_segmentation": "off [fixed]", "tx_gre_segmentation": "off [fixed]", "tx_gso_robust": "off [fixed]", "tx_ipip_segmentation": "off [fixed]", "tx_lockless": "on [fixed]", "tx_mpls_segmentation": "off [fixed]", "tx_nocache_copy": "off [fixed]", "tx_scatter_gather": "on [fixed]", "tx_scatter_gather_fraglist": "on [fixed]", "tx_sctp_segmentation": "on", "tx_sit_segmentation": "off [fixed]", "tx_tcp6_segmentation": "on", "tx_tcp_ecn_segmentation": "on", "tx_tcp_segmentation": "on", "tx_udp_tnl_segmentation": "off [fixed]", "tx_vlan_offload": "off [fixed]", "tx_vlan_stag_hw_insert": "off [fixed]", "udp_fragmentation_offload": "on", "vlan_challenged": "on [fixed]" }, "hw_timestamp_filters": [], "ipv4": { "address": "127.0.0.1", "broadcast": "host", "netmask": "255.0.0.0", "network": "127.0.0.0" }, "mtu": 65536, "promisc": false, "timestamping": [ "rx_software", "software" ], "type": "loopback" }, "ansible_local": {}, "ansible_lsb": {}, "ansible_lvm": { "lvs": {}, "pvs": {}, "vgs": {} }, "ansible_machine": "x86_64", "ansible_machine_id": "f9d400c5e1e8c3a8209e990d887d4ac1", "ansible_memfree_mb": 64, "ansible_memory_mb": { "nocache": { "free": 1261, "used": 578 }, "real": { "free": 64, "total": 1839, "used": 1775 }, "swap": { "cached": 1, "free": 3982, "total": 3999, "used": 17 } }, "ansible_memtotal_mb": 1839, "ansible_mounts": [ { "block_available": 8898335, "block_size": 4096, "block_total": 12868511, "block_used": 3970176, "device": "/dev/vda1", "fstype": "ext3", "inode_available": 3098027, "inode_total": 3276800, "inode_used": 178773, "mount": "/", "options": "rw,noatime,data=ordered", "size_available": 36447580160, "size_total": 52709421056, "uuid": "49f819fd-e56d-48a4-86d3-7ebe0a68ec88" } ], "ansible_nodename": "liushuo", "ansible_os_family": "RedHat", "ansible_pkg_mgr": "yum", "ansible_processor": [ "0", "GenuineIntel", "Intel(R) Xeon(R) CPU E5-26xx v4" ], "ansible_processor_cores": 1, "ansible_processor_count": 1, "ansible_processor_threads_per_core": 1, "ansible_processor_vcpus": 1, "ansible_product_name": "Bochs", "ansible_product_serial": "7c60b665-7950-41cb-ae5a-e6c83fe81f5a", "ansible_product_uuid": "7C60B665-7950-41CB-AE5A-E6C83FE81F5A", "ansible_product_version": "NA", "ansible_python": { "executable": "/usr/bin/python", "has_sslcontext": true, "type": "CPython", "version": { "major": 2, "micro": 5, "minor": 7, "releaselevel": "final", "serial": 0 }, "version_info": [ 2, 7, 5, "final", 0 ] }, "ansible_python_version": "2.7.5", "ansible_real_group_id": 0, "ansible_real_user_id": 0, "ansible_selinux": { "status": "disabled" }, "ansible_selinux_python_present": true, "ansible_service_mgr": "systemd", "ansible_ssh_host_key_dsa_public": "AAAAB3NzaC1kc3MAAACBAPTl1aNHzs5lqZeB0Xvgq9+K//DmRruIRP2O3q0U5WLgJ+iQEb50yFMaIkezpRjWrkrjl7GzD8yoB/3TQVqY875EPlUpMm0ekygwqxrLg/SZ4r8wTNHkc2nnFLKrz3t1+10dnr7SREz12jPOT/hab/dVzRrcKNr9bUXgu93JOJz1AAAAFQCWM/6a3Qnw0sgzgSQn0FLyg3X1bQAAAIEA8EX2KQVDFytLrvWObQI4zlgM8xqoqFxAnOHFp3gef+pDHW8jmnqHj74bKYNojshTeUBM1dfKM9CDi4w7G3lPiEqDMseiak6Bz+PM3z93JpjC1pmVPBbhCIR8RERFtZWpYXeCVFOIpXxcOzXOd7YwUwz3VV5RtsBU9Hk+ZzyklDwAAACBAKUHU0nHLPUuoAmjRrtBIYc5XZYDae6NtUKRm6JTj4nU29ehTjph5ibchfPfY9Pqq2Gy+hq63IyWxavl/MG+TYxALEvkYWF4sJ8cBpyc9AGc4BGilsJsC+RuCVDzh9PzmWVEmb2G6gzxOhoyJNG709KwzB/UR4/WNlbCTPgHQIar", "ansible_ssh_host_key_ecdsa_public": "AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBGlcQEYM733GDZGeBGP8wGnKZtNvFBQvWc/8rgqhoN+3crZcSgZAzeQ+MYfTiJzlc1YLUNWxLdtP0vkvUQclTQQ=", "ansible_ssh_host_key_ed25519_public": "AAAAC3NzaC1lZDI1NTE5AAAAIAeskEU7sUHvEV4sL4oP5mlU+6TYKYkdQWNFOv9koYDz", "ansible_ssh_host_key_rsa_public": "AAAAB3NzaC1yc2EAAAADAQABAAABAQDkYYaw80pPVkuwxVJ27YNaz06erTW4W6LmEWfKV2Zy7PQWnuGCu0CYY5we9zS5nwAIbF5YvEt39Go/zntwLMavaANn4IcxS/FP1DOPMiXlDFCMRtQfSRaV6+5dNDbU5QzeF4SVCrMvzGkCWT0io1D/UGUbn3hZBRzj5ZSbH6RVlle4qePsOkAnBH2XDHGg2W48iqu5JIj53FdmsSolYXy57Dt/TFmVZ8tmH8yLXyVakvvoFCROMjz8Kqbcv5YsZ67IaWCZJblOl4XHhZ73ZhZrEexKBDRdtbrZYO0L7QhvqW5R4ZOng++E2HCUYlUNfh24C4PwGL52AthuA23TfcVD", "ansible_swapfree_mb": 3982, "ansible_swaptotal_mb": 3999, "ansible_system": "Linux", "ansible_system_capabilities": [ "cap_chown", "cap_dac_override", "cap_dac_read_search", "cap_fowner", "cap_fsetid", "cap_kill", "cap_setgid", "cap_setuid", "cap_setpcap", "cap_linux_immutable", "cap_net_bind_service", "cap_net_broadcast", "cap_net_admin", "cap_net_raw", "cap_ipc_lock", "cap_ipc_owner", "cap_sys_module", "cap_sys_rawio", "cap_sys_chroot", "cap_sys_ptrace", "cap_sys_pacct", "cap_sys_admin", "cap_sys_boot", "cap_sys_nice", "cap_sys_resource", "cap_sys_time", "cap_sys_tty_config", "cap_mknod", "cap_lease", "cap_audit_write", "cap_audit_control", "cap_setfcap", "cap_mac_override", "cap_mac_admin", "cap_syslog", "35", "36+ep" ], "ansible_system_capabilities_enforced": "True", "ansible_system_vendor": "Bochs", "ansible_uptime_seconds": 6146103, "ansible_user_dir": "/root", "ansible_user_gecos": "root", "ansible_user_gid": 0, "ansible_user_id": "root", "ansible_user_shell": "/bin/bash", "ansible_user_uid": 0, "ansible_userspace_architecture": "x86_64", "ansible_userspace_bits": "64", "ansible_virtualization_role": "guest", "ansible_virtualization_type": "kvm", "gather_subset": [ "all" ], "module_setup": true }, "changed": false }
setup
[root@liushuo ~]# ansible-doc -s setup - name: Gathers facts about remote hosts setup: fact_path: # path used for local ansible facts (`*.fact') - files in this dir will be run (if executable) and their results be added to `ansible_local' facts if a file is not executable it is read. Check notes for Windows options. (from 2.1 on) File/results format can be json or ini-format filter: # if supplied, only return facts that match this shell-style (fnmatch) wildcard. gather_subset: # if supplied, restrict the additional facts collected to the given subset. Possible values: `all', `min', `hardware', `network', `virtual', `ohai', and `facter'. Can specify a list of values to specify a larger subset. Values can also be used with an initial `!' to specify that that specific subset should not be collected. For instance: `!hardware,!network,!virtual,!ohai,!facter'. If `!all' is specified then only the min subset is collected. To avoid collecting even the min subset, specify `!all,!min'. To collect only specific facts, use `!all,!min', and specify the particular fact subsets. Use the filter parameter if you do not want to display some collected facts. gather_timeout: # Set the default timeout in seconds for individual fact gathering
参数
- hosts: web remote_user: root tasks: - name: create{{ user }} user: name={{ user }}
# 第一种
ansible-playbook -e name=xxxxx 123.yml
# 第二种 在/etc/ansible/host中配置
【web】
127.0.0.1 user=xxxx
#第三种 在/etc/ansible/host中配置
【web】
127.0.0.1
【web:vars】
user=xxxx
# 第四种
- hosts: web remote_user: root vars: - user: xxxxxxx tasks: - name: createuser user: name={{ user }}
# 第五种: 上一条命令的结果,作为下一条命令的参数
通过register注册,使用的时候要使用参数的.stdout值 - hosts: web remote_user: root tasks: - name: sum # 随便写 shell: echo 2+4|bc register: user_ - name: create{{ user_ }} # user_为上一个命令的结果是一个字典 user: name=alexsb{{ user_.stdout }} # user_ 中的stdout输出
# 模块 参数以及值
优先级
-e > playbooks > hosts
playbook 条件判断
- hosts: web
tasks:
- name: file
copy: content="凿壁偷光" dest=/tmp/wg.txt
when: num=="2"
- name: file
copy: content="刷流氓" dest=/tmp/wg.txt
when: num=="4"
单独执行playbook中的一个命令:标签
- hosts: web
tasks:
- name: file
copy: content="凿壁偷光" dest=/tmp/wg.txt
tag: file
ansible-playbook -t file p10.yml
# command play-book - hosts: 172.16.1.41 tasks: - name: step01:install rsync yum: name=rsync state=installed - name: step02:edit rsync conf file copy: src=/etc/ansible/conf/rsync_conf/rsyncd.conf dest=/etc/ - name: step03:create rsync user user: name=rsync state=present createhome=no shell=/sbin/nologin - name: step04:create auth file copy: src=/etc/ansible/conf/rsync_conf/rsync.password dest=/etc/ mode=600 - name: step05:create backup dir file: dest=/backup state=directory owner=rsync group=rsync - name: step06:boot rsync server shell: rsync --daemon creates=/var/run/rsyncd.pid - hosts: 172.16.1.31 tasks: - name: step01:create auth file copy: src=/etc/ansible/conf/rsync_conf/rsync_client.password dest=/etc/rsync.password mode=600
ansible-playbook /etc/ansible/ansible-playbook/test.yaml
ansible-playbook -C /etc/ansible/ansible-playbook/test.yaml
模板
[root@liushuo ~]# ansible-doc -s template - name: Templates a file out to a remote server template: attributes: # Attributes the file or directory should have. To get supported flags look at the man page for `chattr' on the target system. This string should contain the attributes in the same order as the one displayed by `lsattr'. `=' operator is assumed as default, otherwise `+' or `-' operators need to be included in the string. backup: # Create a backup file including the timestamp information so you can get the original file back if you somehow clobbered it incorrectly. block_end_string: # The string marking the end of a block. block_start_string: # The string marking the beginning of a block. dest: # (required) Location to render the template to on the remote machine. follow: # This flag indicates that filesystem links in the destination, if they exist, should be followed. Previous to Ansible 2.4, this was hardcoded as `yes'. force: # the default is `yes', which will replace the remote file when contents are different than the source. If `no', the file will only be transferred if the destination does not exist. group: # Name of the group that should own the file/directory, as would be fed to `chown'. lstrip_blocks: # If this is set to True leading spaces and tabs are stripped from the start of a line to a block. Setting this option to True requires Jinja2 version >=2.7. mode: # Mode the file or directory should be. For those used to `/usr/bin/chmod' remember that modes are actually octal numbers. You must either add a leading zero so that Ansible's YAML parser knows it is an octal number (like `0644' or `01777') or quote it (like `'644'' or `'1777'') so Ansible receives a string and can do its own conversion from string into number. Giving Ansible a number without following one of these rules will end up with a decimal number which will have unexpected results. As of version 1.8, the mode may be specified as a symbolic mode (for example, `u+rwx' or `u=rw,g=r,o=r'). As of version 2.6, the mode may also be the special string `preserve'. `preserve' means that the file will be given the same permissions as the source file. newline_sequence: # Specify the newline sequence to use for templating files. output_encoding: # Overrides the encoding used to write the template file defined by `dest'. It defaults to `'utf-8'', but any encoding supported by python can be used. The source template file must always be encoded using `'utf-8'', for homogeneity. owner: # Name of the user that should own the file/directory, as would be fed to `chown'. selevel: # Level part of the SELinux file context. This is the MLS/MCS attribute, sometimes known as the `range'. `_default' feature works as for `seuser'.
- hosts: cache
remote_user: root
tasks:
- name: copyfile
template: dest=/etc/redis.conf src=redis.conf.j2 # 可以使用相对路径,在当前目录的templates目录里面
tags: copyfile
bind:{{ ansible_default_ipv4.address}}
再将其对应的文件名后 + .j2
循环 with_item
- hosts: port
remote_user: root
tasks:
- name: echo——
shell: echo "xxx"
with_items:
- tast1
- task2
- task3
两种一样
- hosts: port
remote_user: root
tasks:
- name: tast1
shell: echo "xxx"
- name: tast2
shell: echo "xxx"
- name: tast3
shell: echo "xxx"
- hosts: db
tasks:
- name: group
group: name={{item}}
with_items:
- alex20
- wusir20
- taibai20
- name: creatuser
user: name={{ item.name }} group={{item.group}}
with_items:
- {name: alex30,group: alex20} # 整体作为item 参数传入
- {name: wusir30,group: wusir20}
- {name: taibai30,group: taibai20}
handler
- hosts: cache remote_user: root tasks: - name: install yum: name=redis tags: install - name: copyfile template: dest=/etc/redis.conf src=redis.conf.j2 tags: copyfile notify: restart redis # 这个执行完了 触发对应的handler - name: startredis service: name=redis state=started tags: start handlers: - name: restart redis service: name=redis state=restarted

浙公网安备 33010602011771号