简介:
自动化运维工具,基于python开发,集合了众多运维工具(puppet、saltstack、chef、func、Fabric)的优点,实现了批量系统配合,批量程序部署,批量运行命令等功能。ansible是基于模块化工作的,本身没有批量 部署能力,真正具有部署能力的是它的模块,ansilble只是提供一种框架。
核心组件:
- Ansible:核心程序
- Modules:包含Ansible的自带的核心模块以及自定义模块
- Plugins:完成模块功能的补充,包括连接插件,邮箱插件等
- Playbooks:剧本:定理ansible多任务配置文件,由ansible自动执行
- host
- role
- 剧情
- Inventory:定义ansible管理的机器清单
Connection Plugins:负载和被监控端实现通信
特性:
1.它不需要被管控主机安装任何客户端
- 2.无服务端,使用时直接使用命令运行即可
- 3.基于模块工作,可以使用任何语言开发新模块
- 4.使用yaml语言来定制剧本playbook
- 5.基于ssh工作
- 6.可实现多级指挥
-
安装
yum provides ansible
- yum install ansible-2.8.2-1.el7.noarch
- /usr/lib/ansible #
命令说明
[root@localhost ~]# ansible -hUsage: ansible <host-pattern> [options]Define and run a single task 'playbook' against a set of hostsOptions:-a MODULE_ARGS, --args=MODULE_ARGS #指定模块参数module arguments--ask-vault-pass ask for vault password-B SECONDS, --background=SECONDSrun asynchronously, failing after X seconds(default=N/A)-C, --check don't make any changes; instead, try to predict someof the changes that may occur #检查临时命令操作-D, --diff when changing (small) files and templates, show thedifferences in those files; works great with --check-e EXTRA_VARS, --extra-vars=EXTRA_VARS #设置变量set additional variables as key=value or YAML/JSON, iffilename prepend with @-f FORKS, --forks=FORKSspecify 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 hostlist. --inventory-file is deprecated-l SUBSET, --limit=SUBSETfurther limit selected hosts to an additional pattern--list-hosts outputs a list of matching hosts; does not executeanything else-m MODULE_NAME, --module-name=MODULE_NAME #指定模块名module name to execute (default=command)-M MODULE_PATH, --module-path=MODULE_PATHprepend colon-separated path(s) to module library (default=~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules) #指定模块路径-o, --one-line condense output--playbook-dir=BASEDIRSince this tool does not use playbooks, use this as asubstitute playbook directory.This sets the relativepath for many features including roles/ group_vars/etc.-P POLL_INTERVAL, --poll=POLL_INTERVALset the poll interval if using -B (default=15)--syntax-check perform a syntax check on the playbook, but do notexecute it-t TREE, --tree=TREE log output to this directory--vault-id=VAULT_IDS the vault identity to use--vault-password-file=VAULT_PASSWORD_FILESvault password file-v, --verbose verbose mode (-vvv for more, -vvvv to enableconnection debugging)--version show program's version number, config file location,configured module search path, module location,executable location and exitPrivilege Escalation Options:control how and which user you become as on target hosts-b, --become run operations with become (does not imply passwordprompting)--become-method=BECOME_METHODprivilege escalation method to use (default=sudo), use`ansible-doc -t become -l` to list valid choices.--become-user=BECOME_USERrun operations as this user (default=root)-K, --ask-become-passask for privilege escalation passwordConnection 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_FILEuse this file to authenticate the connection-u REMOTE_USER, --user=REMOTE_USERconnect as this user (default=None) #指明连接远程主机的用户-c CONNECTION, --connection=CONNECTIONconnection type to use (default=smart)-T TIMEOUT, --timeout=TIMEOUToverride the connection timeout in seconds(default=10)--ssh-common-args=SSH_COMMON_ARGSspecify common arguments to pass to sftp/scp/ssh (e.g.ProxyCommand)--sftp-extra-args=SFTP_EXTRA_ARGSspecify extra arguments to pass to sftp only (e.g. -f,-l)--scp-extra-args=SCP_EXTRA_ARGSspecify extra arguments to pass to scp only (e.g. -l)--ssh-extra-args=SSH_EXTRA_ARGSspecify extra arguments to pass to ssh only (e.g. -R)Some modules do not make sense in Ad-Hoc (include, meta, etc)
[root@localhost ~]# ansible-docUsage: ansible-doc [-l|-F|-s] [options] [-t <plugin type> ] [plugin]plugin documentation toolOptions:-h, --help show this help message and exit-j, --json **For internal testing only** Dump json metadata forall plugins.-l, --list List available plugins #列出可用插件-F, --list_files Show plugin names and their source files withoutsummaries (implies --list)-M MODULE_PATH, --module-path=MODULE_PATHprepend colon-separated path(s) to module library (default=~/.ansible/plugins/modules:/usr/share/ansible/plugins/modules)-s, --snippet Show playbook snippet for specified plugin(s) #查看该模块(插件)使用手册-t TYPE, --type=TYPE Choose which plugin type (defaults to "module").Available plugin types are : ('become', 'cache','callback', 'cliconf', 'connection', 'httpapi','inventory', 'lookup', 'shell', 'module', 'strategy','vars')-v, --verbose verbose mode (-vvv for more, -vvvv to enableconnection debugging)--version show program's version number, config file location,configured module search path, module location,executable location and exitSee man pages for Ansible CLI options or website for tutorials
配置文件:
一般来说,主配置文件保持默认就行
[root@localhost ~]# ansible-doc -s ping- name: Try to connect to host, verify a usable python and return `pong' onping:data: # Data to return for the `ping' return value. Ithis parameter isset to `crash',the module willcause anexception.
ansible的执行状态:
绿色:执行成功且不需要做操作
黄色:执行成功
红色:执行失败
user模块
[root@localhost ~]# ansible-doc -s user- name: Manage user accountsuser:append: # If `yes', add the user to the groups specifiein `groups'. If`no', user willonly be added tothe groupsspecified in`groups',removing themfrom all othergroups.authorization: # Sets the authorization of the user. Does nothwhen used withother platforms.Can set multipleauthorizationsusing commaseparation. Todelete allauthorizations,use `authorization='''. Currentlysupported onIllumos/Solaris.comment: # Optionally sets the description (aka `GECOS')user account.create_home: # Unless set to `no', a home directory will bemade for the userwhen the accountis created or ifthe homedirectory doesnot exist.Changed from`createhome' to`create_home' inAnsible 2.5.expires: # An expiry time for the user in epoch, it willignored onplatforms that donot support this.Currentlysupported onGNU/Linux,FreeBSD, andDragonFlyBSD.Since Ansible 2.6you can removethe expiry timespecify anegative value.Currentlysupported onGNU/Linux andFreeBSD.force: # This only affects `state=absent', it forcesremoval of theuser andassociateddirectories onsupportedplatforms. Thebehavior is thesame as `userdel--force', checkthe man page for`userdel' on yoursystem fordetails andsupport. Whenused with `generate_ssh_key=yes'this forces anexisting key tobe overwritten.generate_ssh_key: # Whether to generate a SSH key for the user inquestion. Thiswill *not*overwrite anexisting SSH keyunless used with`force=yes'.group: # Optionally sets the user's primary group (taka group name).groups: # List of groups user will be added to. When seto an emptystring `''',`null', or `~',the user isremoved from allgroups except theprimary group.(`~' means `null'in YAML) BeforeAnsible 2.3, theonly input formatallowed was acomma separatedstring.hidden: # macOS only, optionally hide the user from thelogin window andsystempreferences. Thedefault will be`yes' if the`system' optionis used.home: # Optionally set the user's home directory.local: # Forces the use of "local" command alternativeon platforms thatimplement it.This is useful inenvironments thatuse centralizedauthentificationwhen you want tomanipulate thelocal users (i.e.it uses`luseradd'instead of`useradd'). Thiswill check`/etc/passwd' foran existingaccount beforeinvokingcommands. If thelocal accountdatabase existssomewhere otherthan`/etc/passwd',this setting willnot workproperly. Thisrequires that theabove commands aswell as`/etc/passwd'must exist on thetarget host,otherwise it willbe a fatal error.login_class: # Optionally sets the user's login class, afeature of mostBSD OSs.move_home: # If set to `yes' when used with `home: ', atteto move theuser's old homedirectory to thespecifieddirectory if itisn't therealready and theold home exists.name: # (required) Name of the user to create, removemodify.non_unique: # Optionally when used with the -u option, thisoption allows tochange the userID to a non-unique value.password: # Optionally set the user's password to thiscrypted value. OnmacOS systems,this value has tobe cleartext.Beware ofsecurity issues.To create adisabled accounton Linux systems,set this to `'!''or `'*''. See https://docs.ansible.com/ansible/faq.html#how-do-i-generate-crypted-passwords-for-the-user-modulefor details onvarious ways togenerate thesepassword values.password_lock: # Lock the password (usermod -L, pw lock, userm-C). BUTimplementationdiffers ondifferentplatforms, thisoption does notalways mean theuser cannot loginvia othermethods. Thisoption does notdisable the user,only lock thepassword. Do notchange thepassword in thesame task.Currentlysupported onLinux, FreeBSD,DragonFlyBSD,NetBSD, OpenBSD.profile: # Sets the profile of the user. Does nothing whused with otherplatforms. Canset multipleprofiles usingcomma separation.To delete all theprofiles, use`profile='''.Currentlysupported onIllumos/Solaris.remove: # This only affects `state=absent', it attemptsremovedirectoriesassociated withthe user. Thebehavior is thesame as `userdel--remove', checkthe man page fordetails andsupport.role: # Sets the role of the user. Does nothing whenused with otherplatforms. Canset multipleroles using commaseparation. Todelete all roles,use `role='''.Currentlysupported onIllumos/Solaris.seuser: # Optionally sets the seuser type (user_u) onselinux enabledsystems.shell: # Optionally set the user's shell. On macOS,before Ansible2.5, the defaultshell for non-system users was`/usr/bin/false'.Since Ansible2.5, the defaultshell for non-system users onmacOS is`/bin/bash'. Onother operatingsystems, thedefault shell isdetermined by theunderlying toolbeing used. SeeNotes fordetails.skeleton: # Optionally set a home skeleton directory.Requires`create_home'option!ssh_key_bits: # Optionally specify number of bits in SSH keycreate.ssh_key_comment: # Optionally define the comment for the SSH keyssh_key_file: # Optionally specify the SSH key filename. If tis a relativefilename then itwill be relativeto the user'shome directory.This parameterdefaults to`.ssh/id_rsa'.ssh_key_passphrase: # Set a passphrase for the SSH key. If nopassphrase isprovided, the SSHkey will defaultto having nopassphrase.ssh_key_type: # Optionally specify the type of SSH key togenerate.Available SSH keytypes will dependon implementationpresent on targethost.state: # Whether the account should exist or not, takiaction if thestate isdifferent fromwhat is stated.system: # When creating an account `state=present',setting this to`yes' makes theuser a systemaccount. Thissetting cannot bechanged onexisting users.uid: # Optionally sets the `UID' of the user.update_password: # `always' will update passwords if they differ`on_create' willonly set thepassword fornewly createdusers.
group模块
[root@localhost ~]# 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 alternative
on platforms that
implement it.
This is useful in
environments that
use centralized
authentication
when you want to
manipulate the
local groups.
(e.g. it uses
`lgroupadd'
instead of
`groupadd'). 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.
non_unique: # This option allows to change the group ID to
non-unique value.
Requires `gid'.
Not supported on
macOS or BusyBox
distributions.
state: # Whether the group should be present or not on
the remote host.
system: # If `yes', indicates that the group created is
system group
command模块
shell模块
copy模块
[root@localhost ~]# ansible-doc -s copy
- name: Copy files to remote locations
copy:
attributes: # The attributes the resulting file or director
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'. The
`=' 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.
checksum: # SHA1 checksum of the file being transferred.
Used to validate
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
a file directly to the specified
value. For
advanced
formatting or if
`content'
contains a
variable, use the
`template'
module.
decrypt: # This option controls the autodecryption of
source files
using vault.
dest: # (required) Remote absolute path where the fil
should be copied
to. If `src' is a
directory, this
must be a
directory too. If
`dest' is a non-
existent path and
if either `dest'
ends with "/" or
`src' is a
directory, `dest'
is created. If
`dest' is a
relative path,
the starting
directory is
determined by the
remote host. If
`src' and `dest'
are files, the
parent directory
of `dest' is not
created and the
task fails if it
does not already
exist.
directory_mode: # When doing a recursive copy set the mode for
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
destination, if
they exist,
should be
followed.
force: # Influence whether the remote file must always
replaced. If
`yes', the remote
file will be
replaced 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
source tree, if
they exist,
should be
followed.
mode: # The permissions of the destination file or
directory. 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
Ansible 1.8, the
mode may be
specified as a
symbolic mode
(for example,
`u+rwx' or
`u=rw,g=r,o=r').
As of Ansible
2.3, the mode may
also be the
special string
`preserve'.
`preserve' means
that the file
will be given the
same permissions
as the source
file.
owner: # Name of the user that should own the
file/directory,
as would be fed
to `chown'.
remote_src: # Influence whether `src' needs to be transferr
or already is
present remotely.
If `no', it will
search for `src'
at originating/ma
ster machine. If
`yes' it will go
to the
remote/target
machine for the
`src'.
`remote_src'
supports
recursive copying
as of version
2.8. `remote_src'
only works with
`mode=preserve'
as of version
2.6.
selevel: # The level part of the SELinux file context. T
is the MLS/MCS
attribute,
sometimes known
as the `range'.
When set to
`_default', it
will use the
`level' portion
of the policy if
available.
serole: # The role part of the SELinux file context. Wh
set to
`_default', it
will use the
`role' portion of
the policy if
available.
setype: # The type part of the SELinux file context. Wh
set to
`_default', it
will use the
`type' portion of
the policy if
available.
seuser: # The user part of the SELinux file context. By
default it uses
the `system'
policy, where
applicable. When
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. This 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 the
`rsync' command
line tool.
unsafe_writes: # Influence when to use atomic operation to
prevent data
corruption or
inconsistent
reads from the
target file. By
default this
module uses
atomic operations
to prevent data
corruption or
inconsistent
reads from the
target files, but
sometimes systems
are configured or
just broken in
ways that prevent
this. One example
is docker mounted
files, which
cannot be updated
atomically from
inside the
container and can
only be written
in an unsafe
manner. This
option allows
Ansible to fall
back to unsafe
methods of
updating files
when atomic
operations fail
(however, it
doesn't force
Ansible to
perform unsafe
writes).
IMPORTANT! Unsafe
writes are
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 examples
below. The
command is passed
securely so shell
features like
expansion and
pipes will not
work.
file模块
state:
state=directory:如果目录不存在即创建目录
file 即使文件不存在,也不会创建
link 创建链接
hard 创建硬链接
touch 如果文件不存在,会创建一个文件夹
absent:删除目录、文件、取消链接
force:
yum模块
service模块
enabled
disabled:
name = 服务名称
state=
started 启动
stopped 停止
restarted 重启
reloaded 重载配置
setup模块
[root@localhost ~]# ansible-doc -s setup
- name: Gathers facts about remote hosts #获取远程主机相关信息
absible
selinux模块
curl模块
ansible-playbook
playbook由一个或多个“play”组成的列表,可以让它们联同起来按照事先编排的机制执行,每个play中由多task,每个task都是调用ansible的一个模块,而模块参数可以使用变量,模块执行是幂等的,这就意味着多次执行是安全的,因为它的结果均是一致的。
特点:
1.yuml可读性好
2.yuml与脚本语言的交互性好
3.yuml使用实现语言的数据类型
4.yum有一个一致的信息模型
5.yuml易于实现
6.yuml可以基于流来处理
7.yuml表达能力强,拓展好
playbook的结构组成:
hosts:执行的远程主机列表
tasks:任务,由模块定义的操作的列表
variables:内置模块或自定义表里在playbook中可以进行调用
templates:模板,使用模板
- 官方实例
```
hosts: webservers vars: http_port: 80 max_clients: 200 remote_user: root tasks:
- name: ensure apache is at the latest version #定义任务名称 yum: #调用yum模块 name: httpd #yum模块的参数 state: latest
- name: write the apache config file #定义任务名称
template: #模块,模板语法为j2
src: /srv/httpd.j2
dest: /etc/httpd.conf
notify: #调用一个触发器(当条件满足的时候)
- restart apache
- name: ensure apache is running #定义任务名称
service: #service模块
name: httpd
state: started
handlers: #触发后的操作
- name: restart apache service: name: httpd state: restarted ```
运行playbook命令:
ansible-playbook -t:tag指定运行特定任务
ansible-playbook —skip-tags=SKIP_TAGS 跳过指定的标签
ansible-playbook —start-at-task=START_AT_TASK 从哪个任务后执行
ansible-playbook —syntax-check:运行测试,检查语法
ansible-playbook —check:测试运行
- 变量
- 文本文件,内部嵌套有模板语法脚本(使用模板语言编写)
- jinja2是由python编写的,在我们打算使用基于文本的模板语言是,jinja2是很好的解决方案,jinja2是写配置文件模板的
- 功能
- 将模板文件的变量转换成对应的本机主机的确定值
eg:
- Jinja2语法
- 字面量:
- 字符串:使用单引号或者双引号
- 数字:整数、浮点数……
- 列表:
- 元组
- 字典:
- 布尔型:
- 算术运算符
- 比较操作:== > < !=
- 逻辑运算符:and or not
- 字面量:
- 条件判断:
- -name:restart httpd
- 循环迭代:
- 基于字符串列表:
- tasks:
- -name:create file
- tasks:
- 基于字符串列表:
copy:src =
- with_items 嵌套的子变量
- 基于字典列表
- 1.定义变量
port:
index_dir:/var/www/data/
- 2.使用Jinja2语法配置格式语法:
角色
/etc/ansible/roles:存放角色
