在 Linux 中,我们可以通过 ansible-doc -l 命令查看到当前 ansible 都支持哪些模块;
通过 ansible-doc -s <模块名> 又可以查看该模块有哪些参数可以使用。 官网文档:http://docs.ansible.com/ansible/latest/list_of_all_modules.html
更多模块请参阅:https://www.kancloud.cn/hiyang/ansiblebook/305224
Ansible常用模块
ping模块
raw模块
yum模块
apt模块
pip模块
synchronize模块
template模块
copy模块
fetch模块
user 模块与group模块
service 模块
get_url 模块
file模块
cron模块
pause模块
wait_for模块
command、shell、script 模块
fail模块
debug模块
stat模块
get_url模块
mount模块
sysctl 模块
lineinfile模块
blockinfile模块
1、ping模块
检查指定节点机器是否还能连通,用法很简单,不涉及参数,主机如果在线,则回复pong
ansible 10.1.1.113 -m ping
[root@localhost ~]# ansible erp -m ping
192.168.10.6 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.10.7 | SUCCESS => {
"changed": false,
"ping": "pong"
}
2、raw模块
执行原始的命令,而不是通过模块子系统。在任何情况下,使用shell或命令模块是合适的。给定原始的参数直接通过配置的远程shell运行。可返回标准输出、错误输出和返回代码。此模块没有变更处理程序支持。
这个模块不需要远程系统上的Python,就像脚本模块一样。此模块也支持Windows目标。
- name: Bootstrap a legacy python 2.4 host
raw: yum -y install python-simplejson
- name: Bootstrap a host without python2 installed
raw: dnf install -y python2 python2-dnf libselinux-python
- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does)
raw: cat < /tmp/*txt
args:
executable: /bin/bash
- name: safely use templated variables. Always use quote filter to avoid injection issues.
raw: "{{package_mgr|quote}} {{pkg_flags|quote}} install {{python_simplejson|quote}}"
3、yum模块
这个模块是RedHat / CentOS作为远端节点的OS的时候,用的最多的。Yum是啥就不多说了,RedHat / CentOS包管理工具
使用`yum’软件包管理器管理软件包,其选项有:
– config_file:yum的配置文件 (optional)
– disable_gpg_check:关闭gpg_check (optional)
– disablerepo:不启用某个源 (optional)
– enablerepo:启用某个源(optional)
– name:要进行操作的软件包的名字,默认最新的程序包,指明要安装的程序包,可以带上版本号,也可以传递一个url或者一个本地的rpm包的路径
– state:状态(present,absent,latest),表示是安装还卸载
present:默认的,表示为安装
latest: 安装为最新的版本
absent:表示删除
[root@localhost ~]# ansible test -m yum -a ‘name=httpd state=latest’
[root@localhost ~]# ansible test -m yum -a ‘name=”@Development tools” state=present’
[root@localhost ~]# ansible test -m yum -a ‘name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present’
4、apt模块
这个模块是ubuntu作为远端节点的OS的时候,用的最多的。Apt是啥就不多说了,Ubuntu/Debian的包管理工具。
– deb: 用于安装远程机器上的.deb后缀的软件包(optional)
– install_recommends:这个参数可以控制远程电脑上是否只是下载软件包,还是下载后安装,默认参数为true,设置为false的时候只下载软件包,不安装
– update_cache: 当这个参数为yes的时候等于apt-get update(optional)
– name: apt要下载的软件包名字,支持name=git=1.6 这种制定版本的模式
– state:状态(present,absent,latest),表示是安装还卸载
present:默认的,表示为安装
lastest: 安装为最新的版本
absent:表示删除
# 在安装foo软件包前更新然后安装foo
- apt: name=foo update_cache=yes
# 移除foo软件包
- apt: name=foo state=absent
# 安装foo软件包
- apt: name=foo state=present
# 安装foo 1.0软件包
- apt: name=foo=1.00 state=present
# 安装nginx最新的名字为squeeze-backport发布包,并且安装前执行更新
- apt: name=nginx state=latest default_release=squeeze-backports update_cache=yes
# 只下载openjdk-6-jdk最新的软件包,不安装
- apt: name=openjdk-6-jdk state=latest install_recommends=no
# 安装所有软件包到最新版本
- apt: upgrade=dist
# 更新apt-get的list
- apt: update_cache=yes
# 3600秒后停止update_cache
- apt: update_cache=yes cache_valid_time=3600
# 安装远程节点上的/tmp/mypackage.deb软件包
- apt: deb=/tmp/mypackage.deb
5、pip模块
用于管理Python库依赖项,为了使用pip模块,必须提供参数name或者requirements
– chdir: 执行pip命令前cd进入的目录
– name:要安装的Python库的名称或远程包的URL。
– requirements:一个pip requirements.txt文件的路径,它应该是远程系统的本地文件,如果使用chdir选项,则可以将文件指定为相对路径。
– version:指定的Python库的安装版本。
– extra_args:额外的参数传递给pip。
– executable:显式可执行文件或可执行文件的路径名,用于为系统中安装的特定版本的Python运行pip。 例如pip-3.3,如果系统中安装了Python 2.7和3.3,并且想要为Python 3.3安装运行pip。 它不能与“virtualenv”参数一起指定(在2.1中添加)。 默认情况下,它将采用适用于python解释器的版本。 pip3在python 3上,pip2或pip在python 2上。
– virtualenv:要安装到的virtualenv目录的可选路径。 它不能与’executable’参数一起指定(在2.1中添加)。 如果virtualenv不存在,则将在安装软件包之前创建它。 可选的virtualenv_site_packages,virtualenv_command和virtualenv_python选项会影响virtualenv的创建。
– virtualenv_command:用于创建虚拟环境的命令或路径名。 例如pyvenv,virtualenv,virtualenv2,~/bin /virtualenv,/usr/local/bin/virtualenv。
– virtualenv_python:用于创建虚拟环境的Python可执行文件。 例如python3.5,python2.7。 未指定时,将使用用于运行ansible模块的Python版本。 当virtualenv_command使用pyvenv或-m venv模块时,不应使用此参数。
– state:状态(present,absent,latest, forcereinstall),表示是安装还卸载
present:默认的,表示为安装
lastest: 安装为最新的版本
absent:表示删除
forcereinstall:“forcereinstall”选项仅适用于可ansible 2.1及更高版本。
# 安装bottle python包。
- pip:
name: bottle
# 在0.11版安装bottle python包。
- pip:
name: bottle
version: 0.11
# 使用远程协议(bzr +,hg +,git +,svn +)安装MyApp。 您不必在extra_args中提供'-e'选项。
- pip:
name: svn+http://myrepo/svn/MyApp#egg=MyApp
# 使用远程协议(bzr +,hg +,git +)安装MyApp。
- pip:
name: git+http://myrepo/app/MyApp
# 从本地压缩包安装MyApp
- pip:
name: file:///path/to/MyApp.tar.gz
# 将bottle安装到指定的virtualenv中,继承全局安装的模块
- pip:
name: bottle
virtualenv: /my_app/venv
virtualenv_site_packages: yes
# 使用Python 2.7将bottle安装到指定的virtualenv中
- pip:
name: bottle
virtualenv: /my_app/venv
virtualenv_command: virtualenv-2.7
# 在用户主目录中安装bottle。
- pip:
name: bottle
extra_args: --user
# 安装指定的python requirements
- pip:
requirements: /my_app/requirements.txt
# 在指定的virtualenv中安装指定的python requirements。
- pip:
requirements: /my_app/requirements.txt
virtualenv: /my_app/venv
# 安装指定的python requirements和自定义pip源URL
- pip:
requirements: /my_app/requirements.txt
extra_args: -i https://example.com/pypi/simple
# 专门为Python 3.3安装bottle,使用'pip-3.3'可执行文件。
- pip:
name: bottle
executable: pip-3.3
# 安装 bottle,如果已安装,强制重新安装
- pip:
name: bottle
state: forcereinstall
6、synchronize模块
使用rsync同步文件,将主控方目录推送到指定节点的目录下,其参数如下:
– src: 要同步到目的地的源主机上的路径; 路径可以是绝对的或相对的。如果路径使用”/”来结尾,则只复制目录里的内容,如果没有使用”/”来结尾,则包含目录在内的整个内容全部复制
– dest:目的地主机上将与源同步的路径; 路径可以是绝对的或相对的。
– archive:是否采用归档模式同步,即以源文件相同属性同步到目标地址,默认开启
– dest_port :目标接受的端口,ansible配置文件中的 ansible_ssh_port 变量优先级高于该 dest_port 变量
– checksum:是否效验
– compress:开启压缩,默认为开启
– copy_links:同步的时候是否复制连接
– delete:删除源中没有而目标存在的文件(即以推送方为主),默认no
– dirs:以非递归的方式传输目录
– existing_only:Skip creating new files on receiver.
– group:Preserve group
– links:Copy symlinks as symlinks.
– mode:rsync 同步的方式 PUSH\PULL,默认push,一般用于从本机向远程主机上传文件,pull 模式用于从远程主机上取文件。
– recursive :是否递归 yes/no
– rsync_opts:通过传递数组来指定其他rsync选项。
– rsync_path:服务的路径,指定 rsync 命令来在远程服务器上运行。这个参考rsync命令的--rsync-path参数,--rsync-path=PATH # 指定远程服务器上的rsync命令所在路径信息
– rsync_timeout:指定 rsync 操作的 IP 超时时间,和rsync命令的 --timeout 参数效果一样,单位为秒
– set_remote_user:put user@ for the remote paths. If you have a custom ssh config to define the remote user for
– --exclude=.Git 忽略同步.git结尾的文件
# 将控制机器上的src同步到远程主机上
- hosts: nginx
remote_user: root
tasks:
- name: push nginx file
synchronize:
src: /data/nginx-config/
dest: /etc/nginx/
archive: no
mode: push
delete: yes
recursive: yes
rsync_timeout: 300
rsync_opts:
- "--exclude=.git"
tags:
- push_files
- name: nginx service reload
shell: /opt/openresty/nginx/sbin/nginx -s reload
tags:
- nginx_reload
7、template模块
基于模板方式生成一个文件复制到远程主机(template使用Jinjia2格式作为文件模版,进行文档内变量的替换的模块。它的每次使用都会被ansible标记为”changed”状态。)
– backup: 如果原目标文件存在,则先备份目标文件 。默认值:no
– src:在ansible控制器上的Jinja2格式化模板的路径。 这可以是相对或绝对的路径。
– dest:将模板渲染到远程机器上的位置。
force:是否强制覆盖,默认为yes
– owner:目标文件属主
– group:目标文件属组
– mode:目标文件的权限模式,模式可以被指定为符号模式(例如,u + rwx或u = rw,g = r,o = r)。
# Example from Ansible Playbooks
- template:
src: /mytemplates/foo.j2
dest: /etc/file.conf
owner: bin
group: wheel
mode: 0644
# 同样的例子,但使用等效于0644的符号模式
- template:
src: /mytemplates/foo.j2
dest: /etc/file.conf
owner: bin
group: wheel
mode: "u=rw,g=r,o=r"
8、copy模块
在远程主机执行复制操作文件。
– src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用”/”来结尾,则只复制目录里的内容,如果没有使用”/”来结尾,则包含目录在内的整个内容全部复制,类似于rsync。
– content:用于替代”src”,可以直接设定指定文件的值
– dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录
– directory_mode:递归的设定目录的权限,默认为系统默认权限
– force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
– others:所有的file模块里的选项都可以在这里使用
# Example from Ansible Playbooks
- copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: 0644
# 与上述同样的例子,但是使用等价于0644的符号模式
- copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u=rw,g=r,o=r
# 另一个符号模式示例,添加一些权限并删除其他
- copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u+rw,g-wx,o-rwx
9、fetch模块
它用于从远程机器获取文件,并将其本地存储在由主机名组织的文件树中。
– src:远程系统上要获取的文件。 这必须是一个文件,而不是一个目录。 后续版本可能会支持递归提取。
– dest:保存文件的目录。 例如,如果dest目录是/backup,在主机host.example.com上命名为/ etc/profile的src文件将被保存到/backup/host.example.com/etc/profile。
– flat:只下载目标文件到本地路径中。在使用参数为flat的时候,如果dest的后缀名为/,那么就会保存在目录中,然后直接保存为文件名;当dest后缀不为/的时候,那么就会直接保存为dest路径结尾的文件名。
# 将文件存储到/tmp/fetched/host.example.com/tmp/somefile中
- fetch:
src: /tmp/somefile
dest: /tmp/fetched
# 直接指定路径
- fetch:
src: /tmp/somefile
dest: /tmp/prefix-{{ inventory_hostname }}
flat: yes
# 指定目标路径
- fetch:
src: /tmp/uniquefile
dest: /tmp/special/
flat: yes
10、user 模块与group模块
user模块是请求的是useradd, userdel, usermod三个指令,goup模块请求的是groupadd, groupdel, groupmod 三个指令。
1、user模块
– home:指定用户的家目录,需要与createhome配合使用。
– groups:指定用户的属组。
– uid:指定用的uid。
– password:指定用户的密码。
注意:指定password参数时,不能使用明文密码,因为后面这一串密码会被直接传送到被管理主机的/etc/shadow文件中,所以需要先将密码字符串进行加密处理。然后将得到的字符串放到password中即可。
echo “123456” | openssl passwd -1 -salt (</dev/urandomtr−dc‘[:alnum:]′|head−c32)−stdin(</dev/urandomtr−dc‘[:alnum:]′|head−c32)−stdin14P4PlFuE4P4PlFuEur9ObJiT5iHNrb9QnjaIB0
– name:指定用户名。
– createhome:是否创建家目录 yes|no。
– system:是否为系统用户。
– remove:当state=absent时,remove=yes则表示连同家目录一起删除,等价于userdel -r。
– state:是创建还是删除。(present,absent)
– shell:指定用户的shell环境。
– generate_ssh_key:是否为相关用户生成SSH密钥。 这不会覆盖现有的SSH密钥。
– ssh_key_bits:可选择指定要创建的SSH密钥中的位数。
– ssh_key_passphrase:设置SSH密钥的密码。 如果没有提供密码,SSH密钥将默认没有密码。
– ssh_key_file:指定SSH密钥文件名(可选)。 如果这是一个相对的文件名,那么它将是相对于用户的主目录。
– ssh_key_type:指定要生成的SSH密钥的类型(可选)。 可用的SSH密钥类型将取决于目标主机上的实现。
# 使用bash shell添加用户“james”,将组“管理员”和“开发人员”附加到用户组
- user:
name: james
shell: /bin/bash
groups: admins,developers
append: yes
# 删除用户'johns'
- user:
name: johnd
state: absent
remove: yes
# 在~/.ssh/id_rsa中为用户jsmith创建一个2048位的SSH密钥
- user:
name: jsmith
generate_ssh_key: yes
ssh_key_bits: 2048
ssh_key_file: .ssh/id_rsa
2、group模块
– gid:指定用的gid。
– name:指定用户名。
– state:是创建还是删除。(present,absent)
– system:如果是,则表示创建的组是系统组。
# Example group command from Ansible Playbooks
- group:
name: somegroup
state: present
11、service 模块
用于管理服务,记得针对Centos7就不要使用这个模块了。
– arguments:给命令行提供一些选项
– enabled:是否开机启动 yes|no, 要求状态(state)和启用(enabled)中至少有一个。
– name:必选项,服务名称
– runlevel:运行级别
– sleep:如果执行了restarted,在则stop和start之间沉睡几秒钟
– state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)
# 启动服务httpd,如果不运行
- service:
name: httpd
state: started
# 停止服务httpd,如果运行
- service:
name: httpd
state: stopped
# 启用服务httpd的示例操作,而不使用运行状态
- service:
name: httpd
enabled: yes
12、get_url 模块
该模块主要用于从http、ftp、https服务器上下载文件(类似于wget),主要有如下选项:
– sha256sum:下载完成后进行sha256 check;
– timeout:下载超时时间,默认10s
– url:下载的URL
– url_password、url_username:主要用于需要用户名密码进行验证的情况
– dest:将文件下载到哪里的绝对路径。如果dest是目录,则使用服务器提供的文件名,或者如果没有提供,将使用远程服务器上的URL的基本名称。
– headers:以格式“key:value,key:value”为请求添加自定义HTTP标头。
- name: Download foo.conf
get_url:
url: http://example.com/path/file.conf
dest: /etc/foo.conf
mode: 0440
- name: Download file with custom HTTP headers
get_url:
url: http://example.com/path/file.conf
dest: /etc/foo.conf
headers: 'key:value,key:value'
- name: Download file with check (sha256)
get_url:
url: http://example.com/path/file.conf
dest: /etc/foo.conf
checksum: sha256:b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c
13、file模块
file模块主要用于远程主机上的文件操作,file模块包含如下选项:
– force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
– group:定义文件/目录的属组
– mode:定义文件/目录的权限
– owner:定义文件/目录的属主
– path:必选项,定义文件/目录的路径
– recurse:递归的设置文件的属性,只对目录有效
– src:要被链接的源文件的路径,只应用于state=link的情况
– dest:被链接到的路径,只应用于state=link的情况
– state:
directory:如果目录不存在,创建目录
file:即使文件不存在,也不会被创建
link:创建软链接
hard:创建硬链接
touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间
absent:删除目录、文件或者取消链接文件
# 更改文件所有权,组和模式。 当使用八进制数指定模式时,第一个数字应始终为0。
- file:
path: /etc/foo.conf
owner: foo
group: foo
mode: 0644
# touch创建文件,使用符号模式设置权限(相当于0644)
- file:
path: /etc/foo.conf
state: touch
mode: "u=rw,g=r,o=r"
# touch创建文件,添加/删除一些权限
- file:
path: /etc/foo.conf
state: touch
mode: "u+rw,g-wx,o-rwx"
# 创建一个目录,如果它不存在
- file:
path: /etc/some_directory
state: directory
mode: 0755
14、unarchive模块
用于解压文件,模块包含如下选项:
– copy:在解压文件之前,是否先将文件从本地 'master' 复制到远程主机,默认为yes。若为no,则要求目标主机上压缩包必须存在。此选项与remote_src互斥。
– creates(path):如果指定的绝对路径(文件或目录)已经存在,则将不会运行此步骤。
– dest:远程主机上的一个路径,即文件解压的绝对路径。 – keep_newer( yes | no): 不要替换比存档中的文件更新的现有文件。– group:解压后的目录或文件的属组 – owner:解压后文件或目录的属主– remote_src:设置为yes指示已归档文件已在远程系统上,而不是在Ansible控制器本地。此选项与copy互斥。– list_files:如果为yes,则会列出压缩包里的文件,默认为no,2.0版本新增的选项 – mode:解压后文件的权限
– src (path / required):
如果
remote_src=no
(默认),则为要复制到目标服务器的存档文件的本地路径;可以是绝对的或相对的。如果为remote_src=yes,则目标服务器上要解压缩的现有存档文件的路径。
如果
remote_src=yes
和src
包含://
,则远程计算机将首先从URL下载文件。(版本2.0)。仅在简单情况下,要完全下载支持,请使用get_url模块。
- name: 将foo.tgz解压缩到/var/lib/foo中
unarchive:
src: foo.tgz
dest: /var/lib/foo
- name: 解压远程计算机上已存在的文件
unarchive:
src: /tmp/foo.zip
dest: /usr/local/bin
remote_src: yes
- name: 解压文档需要下载的文件(2.0中添加)
unarchive:
src: https://example.com/example.zip
dest: /usr/local/bin
remote_src: yes
15、cron 模块
Ansible cron模块主要用于添加、删除、更新操作系统的crontab任务计划
cron模块使用详解:
name:任务计划名称
cron_file:替换客户端该用户的任务计划的文件
minute:分(0-59, * ,*/2)
hour:时(0-23, * ,*/2)
day:日(1-31, * ,*/2)
month:月(1-12, * , */2)
weekday:周(0-6或1-7, *)
job:任何计划执行的命令,state要等于present
backup:是否备份之前的任务计划
user:新建任务计划的用户
state:指定任务计划present、absent
(1)基于cron模块,创建crontab任务计划,例如:让所有的后端服务器在每天的00:00点从172.25.70.250主机上用ntpdate同步实践,任务名称为:Ntpdate server for sync time,一定要注意这个定时服务,一定要在172.25.70.250配置好ntp服务器
ansible all -m cron -a "minute=0 hour=0 day=* month=* weekday=* name='Ntpdate server for sync time' job='ntpdate 172.25.70.250'"
(2)backup=yes,表示开启备份,备份文件会存放在客户端/tmp/目录下面
ansible 172.25.70.1 -m cron -a "minute=0 hour=0 day=* month=* weekday=* name='Ntpdate server for sync time' backup=yes job='ntpdate www.lcl.com'"
(3)删除crontab任务计划
ansible all -m cron -a "name='Ntpdate server for sync time' state=absent"
16、pause 模块
在playbook执行的过程中暂停一定时间或者提示用户进行某些操作
常用参数:
minutes:暂停多少分钟
seconds:暂停多少秒
prompt:打印一串信息提示用户操作
示例:
- name: wait on user input
pause: prompt="Warning! Detected slight issue. ENTER to continue CTRL-C a to quit"
- name: timed wait
pause: seconds=30
17、wait_for 模块
在playbook的执行过程中,等待某些操作完成以后再进行后续操作
常用参数:
connect_timeout:在下一个任务执行之前等待连接的超时时间
delay:等待一个端口或者文件或者连接到指定的状态时,默认超时时间为300秒,在这等待的300s的时间里,wait_for模块会一直轮询指定的对象是否到达指定的状态,delay即为多长时间轮询一次状态。
host:wait_for模块等待的主机的地址,默认为127.0.0.1
port:wait_for模块待待的主机的端口
path:路径,只有当这个文件存在时,下一任务才开始执行,即等待该文件创建完成
state:等待的状态,即等待的文件或端口或者连接状态达到指定的状态时,下一个任务开始执行。当等的对象为端口时,状态有started,stoped,即端口已经监听或者端口已经关闭;当等待的对象为文件时,状态有present或者started,absent,即文件已创建或者删除;当等待的对象为一个连接时,状态有drained,即连接已建立。默认为started
timeout:wait_for的等待的超时时间,默认为300秒
示例:
- wait_for: port=8080 state=started #等待8080端口已正常监听,才开始下一个任务,直到超时
- wait_for: port=8000 delay=10 #等待8000端口正常监听,每隔10s检查一次,直至等待超时
- wait_for: host=0.0.0.0 port=8000 delay=10 state=drained #等待8000端口直至有连接建立
- wait_for: host=0.0.0.0 port=8000 state=drained exclude_hosts=10.2.1.2,10.2.1.3 #等待8000端口有连接建立,如果连接来自10.2.1.2或者10.2.1.3,则忽略。
- wait_for: path=/tmp/foo #等待/tmp/foo文件已创建
- wait_for: path=/tmp/foo search_regex=completed #等待/tmp/foo文件已创建,而且该文件中需要包含completed字符串
- wait_for: path=/var/lock/file.lock state=absent #等待/var/lock/file.lock被删除
- wait_for: path=/proc/3466/status state=absent #等待指定的进程被销毁
- local_action: wait_for port=22 host="{{ ansible_ssh_host | default(inventory_hostname) }}" search_regex=OpenSSH delay=10 #等待openssh启动,10s检查一次
18、command 模块和shell
用于在各被管理节点运行指定的命令
shell和command的区别:shell模块可以特殊字符,而command是不支持
1、command模块
在远程主机上执行命令,模块包含如下选项:
– creates:一个文件名,当该文件存在,则该命令不执行
– free_form:要执行的linux指令
– chdir:在执行指令之前,先切换到该目录
– removes:一个文件名,当该文件不存在,则该选项不执行
– executable:更改用于执行命令的shell(bash,sh),该执行路径必须是一个绝对路径
- name: return motd to registered var
command: cat /etc/motd
register: mymotd
- name: Run the command if the specified file does not exist.
command: /usr/bin/make_database.sh arg1 arg2 creates=/path/to/database
# 您还可以使用“args”表单提供选项。
- name: This command will change the working directory to somedir/ and will only run when /path/to/database doesn't exist.
command: /usr/bin/make_database.sh arg1 arg2
args:
chdir: somedir/
creates: /path/to/database
2、shell模块
切换到某个shell执行指定的指令,参数与command相同:
- name: Execute the command in remote shell; stdout goes to the specified file on the remote.
shell: somescript.sh >> somelog.txt
- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does)
shell: cat < /tmp/*txt
args:
executable: /bin/bash
3、script模块
1、一个简单的创建目录的例子,创建/usr/local/src/data/log 目录,如下:
# cat test1.sh
#---------------------------------------------------
#!/bin/bash
if [ -z $1 ] || [ -z $2 ];then
echo "Wrong,Please input two args"
echo "Usage `basename $0` arguments arguments"
exit 6
fi
mkdir -pv /usr/local/src/$1/$2
#####################################################
# cat createdir.yml
---
- hosts: "{{ host }}"
user: "{{ user }}"
gather_facts: True
tasks:
- name: Create Dir in client server
script: /etc/ansible/test1.sh data log
执行:
ansible-playbook createdir.yml -e "host=web user=root"
2、一个批量修改root密码的例子:
# cat alter.sh
#---------------------------------------------------
#!/bin/bash
##modify passwd##
echo 'root:1234567890' |chpasswd
if [ $? -eq 0 ]
then
echo "Change password for root OK!!!"
else
echo "Change password for root failure!!!"
fi
#####################################################
# cat modify_all_password.yml
---
- hosts: all
user: root
gather_facts: True
tasks:
- name: Modify root passwd in all client
script: /etc/ansible/roles/alter.sh
然后执行:
ansible-playbook modify_all_password.yml
ansible-playbook可以跟很多参数,可以使用--help查看
19、fail 模块
用于终止当前playbook的执行,通常与条件语句组合使用,当满足条件时,终止当前play的运行。可以直接由failed_when取代。
选项只有一个:
msg:终止前打印出信息
示例:
- fail: msg="The system may not be provisioned according to the CMDB status."
when: cmdb_status != "to-be-staged"
20、debug 模块
该模块 用于在调试中输出信息,对于调试变量或表达式非常有用,而不必停止播放本。与'when:'指令一起调试很有用。Windows目标也支持此模块。
msg:调试输出的消息
var:将某个任务执行的输出作为变量传递给debug模块,debug会直接将其打印输出
verbosity:debug的级别(默认是0级,全部显示)
示例:
---
- hosts: test
gather_facts: F #开启debug
vars:
war: "ps -ef | grep tomcat | grep -v grep | awk '{print $2}'"
tasks:
- name: stop tomcat
shell: nohup /bin/bash /tmp/stop_tomcat.sh&
ignore_errors: True
register: tomcat_out #定义变量存储返回的结果
- name: show 结果 #定义输出结果的task
debug: var=tomcat_out verbosity=0 #这样写不光输出命令结果,还返回相关调试信息,只输出执行结果则使用 tomcat_out.stdout。
- name: back war
shell: cp /home/admin/taobao-tomcat-production-7.0.59.3/deploy/ROOT.war /tmp/
- name: remove romate dir
file: path=/home/admin/taobao-tomcat-production-7.0.59.3/deploy/ROOT state=absent
- name: remove romate war
file: path=/home/admin/taobao-tomcat-production-7.0.59.3/deploy/ROOT.war state=absent
- name: copy war
copy: src=/home/admin/.jenkins/jobs/NET-hangfa/workspace/aecc_purchase_portal_web/xx.war dest=/home/admin/taobao-tomcat-production-7.0.59.3/deploy/ROOT.war owner=admin group=wheel mode=0644
- name: start tomcat
shell: nohup sh /home/admin/taobao-tomcat-production-7.0.59.3/bin/startup.sh &
- name: tomcatalive
shell: "{{war}}"
register: check
- name: show
debug: var=check.stdout verbosity=0 #check.stdout 显示出的信息会看的更清晰点
21、stat模块
获取远程文件状态信息,包括atime,ctime,mtime,md5,uid,gid等信息
# ansible 10.0.90.25 -m stat -a "path=/etc/sysctl.conf"
10.0.90.25 | SUCCESS => {
"changed": false,
"stat": {
"atime": 1459270210.5650001,
"checksum": "a27c7ce2e6002c37f3cb537ad997c6da7fd76480",
"ctime": 1441217442.5749998,
"dev": 2051,
"exists": true,
"gid": 0,
"gr_name": "root",
"inode": 1181554,
"isblk": false,
"ischr": false,
"isdir": false,
"isfifo": false,
"isgid": false,
"islnk": false,
"isreg": true,
"issock": false,
"isuid": false,
"md5": "c97839af771c8447b9fc23090b4e8d0f",
"mode": "0644",
"mtime": 1413471211.0,
"nlink": 1,
"path": "/etc/sysctl.conf",
"pw_name": "root",
"rgrp": true,
"roth": true,
"rusr": true,
"size": 1150,
"uid": 0,
"wgrp": false,
"woth": false,
"wusr": true,
"xgrp": false,
"xoth": false,
"xusr": false
}
}
##显示所有的ansible默认变量信息
ansible web -m setup
22、get_url模块
实现在远程主机下载指定URL到本地,支持sha256sum文件校验
例如:
#ansible host1 -m get_url -a "url=http://www.baidu.com dest=/tmp/index.html mode=0440 force=yes"
172.16.29.193 | success >> {
"changed": true,
"checksum": "8bc43056c39fbb882cf5d7b0391d70b6e84096c6",
"dest": "/tmp/index.html",
"gid": 0,
"group": "root",
"md5sum": "324aa881293b385d2c0b355cf752cff9",
"mode": "0440",
"msg": "OK (unknown bytes)",
"owner": "root",
"secontext": "unconfined_u:object_r:user_tmp_t:s0",
"sha256sum": "",
"size": 93299,
"src": "/tmp/tmp3WI5fE",
"state": "file",
"uid": 0,
"url": "http://www.baidu.com"
}
23、mount 模块:远程主机分区挂载
#ansible host1 -m mount -a "name=/mnt/data src=/dev/sd0 fstype=ext3 opts=ro state=present"
24、sysctl 模块:远程linux主机sysctl配置模块
sysctl: name=kernel.panic value=3 sysctl_file=/etc/sysctl.conf checks=before reload=yes
以下是定义在yml格式文件中的例子:
- sysctl: name=net.ipv4.tcp_rmem 'value=4096 87380 16777216' state=present
- sysctl: name=net.ipv4.tcp_wmem 'value=4096 65536 16777216' state=present
- sysctl: name=net.ipv6.conf.lo.disable_ipv6 value=1 state=present
25、lineinfile模块
Ensure a particular line is in a file, or replace an existing line using a back-referenced regular expression 确保特定的行在文件中,或使用反向引用正则表达式替换现有的行
用法:
# NOTE: Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- name: Ensure SELinux is set to enforcing mode
ansible.builtin.lineinfile:
path: /etc/selinux/config
regexp: '^SELINUX='
line: SELINUX=enforcing
- name: Make sure group wheel is not in the sudoers configuration
ansible.builtin.lineinfile:
path: /etc/sudoers
state: absent
regexp: '^%wheel'
- name: Replace a localhost entry with our own
ansible.builtin.lineinfile:
path: /etc/hosts
regexp: '^127\.0\.0\.1'
line: 127.0.0.1 localhost
owner: root
group: root
mode: '0644'
- name: Ensure the default Apache port is 8080
ansible.builtin.lineinfile:
path: /etc/httpd/conf/httpd.conf
regexp: '^Listen '
insertafter: '^#Listen '
line: Listen 8080
- name: Ensure we have our own comment added to /etc/services
ansible.builtin.lineinfile:
path: /etc/services
regexp: '^# port for http'
insertbefore: '^www.*80/tcp'
line: '# port for http by default'
- name: Add a line to a file if the file does not exist, without passing regexp
ansible.builtin.lineinfile:
path: /tmp/testfile
line: 192.168.1.99 foo.lab.net foo
create: yes
# NOTE: Yaml requires escaping backslashes in double quotes but not in single quotes
- name: Ensure the JBoss memory settings are exactly as needed
ansible.builtin.lineinfile:
path: /opt/jboss-as/bin/standalone.conf
regexp: '^(.*)Xms(\d+)m(.*)$'
line: '\1Xms${xms}m\3'
backrefs: yes
# NOTE: Fully quoted because of the ': ' on the line. See the Gotchas in the YAML docs.
- name: Validate the sudoers file before saving
ansible.builtin.lineinfile:
path: /etc/sudoers
state: present
regexp: '^%ADMIN ALL='
line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
validate: /usr/sbin/visudo -cf %s
# See https://docs.python.org/3/library/re.html for further details on syntax
- name: Use backrefs with alternative group syntax to avoid conflicts with variable values
ansible.builtin.lineinfile:
path: /tmp/config
regexp: ^(host=).*
line: \g<1>{{ hostname }}
backrefs: yes
一个例子:
#cat linetest.yml
---
- hosts: web
user: root
gather_facts: flase
tasks:
- name: change /etc/hosts
lineinfile:
dest=/etc/hosts
line='test line 1\ntest line 2\ntest line 3\ntest line 4'
上面的例子是在/etc/hosts中添加4行,如果你只需要添加一行,line='test line 1'即可!
例子:
- name: Check if couchbase.host is already defined
lineinfile:
state: absent
path: "/database.properties"
regexp: "^couchbase.host="
check_mode: true
changed_when: false # This just makes things look prettier in the logs
register: check
- name: Define couchbase.host if undefined
lineinfile:
state: present
path: "/database.properties"
line: "couchbase.host=127.0.0.1"
when: check.found == 0
26、blockinfile模块 Insert/update/remove a text block surrounded by marker lines
注意:dest后面的路径和文件名一定要存在,否则会报错。
用法:
- name: 在 /etc/ssh/sshd_config 插入/更新 "Match User" 配置块
blockinfile:
dest: /etc/ssh/sshd_config
block: |
Match User ansible-agent
PasswordAuthentication no
- name: 在 /etc/network/interfaces 插入/更新 eth0 configuration stanza
(it might be better to copy files into /etc/network/interfaces.d/)
blockinfile:
dest: /etc/network/interfaces
block: |
iface eth0 inet static
address 192.168.0.1
netmask 255.255.255.0
- name: insert/update HTML surrounded by custom markers after <body> line
blockinfile:
dest: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
insertafter: "<body>"
content: |
<h1>Welcome to `ansible_hostname`</h1>
<p>Last updated on `ansible_date_time`.`iso8601`</p>
- name: remove HTML as well as surrounding markers ##此文件实现将上面添加的内容删除
blockinfile:
dest: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
content: ""
- name: insert/update "Match User" configuation block in /etc/ssh/sshd_config
blockinfile:
dest: /etc/hosts
block: |
`item`.`name` `item`.`ip`
marker: "# {mark} ANSIBLE MANAGED BLOCK `item`.`name`"
with_items:
- { name: host1, ip: 10.10.1.10 }
- { name: host2, ip: 10.10.1.11 }
- { name: host3, ip: 10.10.1.12 }
第一个例子:在/etc/hosts文件中添加3行
#cat blockinfile.yml
---
- hosts: web
user: root
tasks:
- name: this is test blockinfile module
blockinfile:
dest: /etc/hosts
block: |
this is a test line 1
this is a test line 2
this is a test line 3
结果:
#cat /etc/hosts
# BEGIN ANSIBLE MANAGED BLOCK
this is a test line 1
this is a test line 2
this is a test line 3
# END ANSIBLE MANAGED BLOCK
第二个例子:创建一个index.html文件,并写入html格式内容
#cat blockinfile.yml
---
- hosts: web
user: root
tasks:
- name: create a test file
file: path=/root/index.html state=touch
- name: this is test blockinfile module
blockinfile:
dest: /root/index.html
marker: "<!-- {mark} ansible managed block -->"
insertafter: "<body>"
content: |
<h1>welcome to `ansible_hostname`</h1>
<p>Last updated on `ansible_date_time`.`iso8601`</p>
结果:
#cat index.html
<!-- BEGIN ansible managed block -->
<h1>welcome to http</h1>
<p>Last updated on 2016-05-19T03:17:35Z</p>
<!-- END ansible managed block -->
注意:上面yml文件中ansible_hostname和ansible_date_time.iso8601变量是ansible默认的系统变量,这个变量可以通过-m setup查看到!
所以上面的ansible_date_time.iso8601可以改为iso8601_basic_short(人类可读)
结果就变成了如下:因为当前时间就是#Thu May 19 11:33:29 CST 2016
<p>Last updated on 20160519T113219</p>
第三个例子:index.html已经存在,并且内容如下:
#cat index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
创建ansible的playbook文件如下:
#cat blockinfile.yml
---
- hosts: 10.0.90.25
user: root
gather_facts: True
tasks:
- name: this is test blockinfile module
blockinfile:
dest: /root/index.html
marker: "<!-- {mark} ansible managed block -->"
insertafter: "<body>"
content: |
<h1>welcome to `ansible_hostname`</h1>
<p>Last updated on `ansible_date_time`.`iso8601_basic_short`</p>
执行之后,再查看index.html
#cat index.html
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
body {
width: 35em;
margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif;
}
</style>
</head>
<body>
<!-- BEGIN ansible managed block --> ###从这里开始
<h1>welcome to http</h1>
<p>Last updated on 20160519T115013</p>
<!-- END ansible managed block --> ###在这里结束
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
<p><em>Thank you for using nginx.</em></p>
</body>
</html>
第四个例子:使用变量
#cat blockinfile.yml
---
- hosts: 10.0.90.25
user: root
gather_facts: True
tasks:
- name: this is test blockinfile module
blockinfile:
dest: /etc/hosts
block: |
`item`.`name` `item`.`ip`
marker: "# {mark} ansible managed block `item`.`name`"
with_items:
- { name: host1, ip: 10.10.1.10}
- { name: host2, ip: 10.10.1.11}
- { name: host3, ip: 10.10.1.12}
执行后,结果如下:
#cat /etc/hosts
# BEGIN ansible managed block host1
host1 10.10.1.10
# END ansible managed block host1
# BEGIN ansible managed block host2
host2 10.10.1.11
# END ansible managed block host2
# BEGIN ansible managed block host3
host3 10.10.1.12
# END ansible managed block host3