模块是Ansible执行的最小单位,可以是由Python编写,也可以是Shell编写,也可以是由其他语言编写。
测试连接可通性,没有参数。通的话返回pong。
ansible all -m ping
执行结果:
[root@192-168-38-144 node_init]# ansible all -m ping
192.168.38.145 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
192.168.38.144 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"ping": "pong"
}
主要用于获取主机信息,在playbooks里经常会用到的一个参数gather_facts就与该模块相关。setup模块下经常使用的一个参数是filter参数,具体使用示例如下(由于输出结果较多,这里只列命令不写结果)
每个被管理节点在接收并运行管理命令之前,会将自己主机相关信息(如系统版本,主机IP地址)告知ansible管理主机
ansible-doc -s setup
--tree :将所有主机的输出信息保存到/tmp/目录下,以/etc/ansible/hosts里的主机名为文件名
ansible all -m setup -a 'filter=ansible_distribution_version' --tree /tmp/
filter :过滤关键字
#ansible db -m setup -a 'filter=ansible_distribution_version'
gather_subset:按子集收集信息,值有all, min, hardware, network, virtual, ohai, facter。不包含请使用!号,如,!network
ansible web -m setup
command 命令模块,默认模块(可省略),用于在远程执行命令(不能使用变量)
1 creates:一个文件名,当该文件存在,则该命令不执行
2 free_form:要执行的linux指令
3 chdir:在执行指令之前,先切换到该指定的目录
4 removes:一个文件名,当该文件不存在,则该选项不执行
5 executable:切换shell来执行指令,该执行路径必须是一个绝对路径
[root@192-168-38-144 node_init]# ansible node -a 'date'
192.168.38.145 | CHANGED | rc=0 >>
2020年 08月 17日 星期一 15:01:49 CST
cron 定时任务模块
1 backup:对远程主机上的原任务计划内容修改之前做备份
2 cron_file:如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户的任务计划
3 day:日(1-31,*,*/2,……)
4 hour:小时(0-23,*,*/2,……)
5 minute:分钟(0-59,*,*/2,……)
6 month:月(1-12,*,*/2,……)
7 weekday:周(0-7,*,……)
8 job:要执行的任务,依赖于state=present
9 name:该任务的描述
10 special_time:指定什么时候执行,参数:reboot,yearly,annually,monthly,weekly,daily,hourly
11 state:确认该任务计划是创建还是删除
12 user:以哪个用户的身份执行
ansible db -m cron -a 'minute="" hour="" day="" month="" weekday="" job="" name="(必须填写)" state=
1、定时设置指定值的写入即可,没有设置的可以不写(默认是*)
2、name必须写
3、state有两个状态:present(添加(默认值))or absent(移除)
1、添加定时任务
ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="present"'
ansible db -a "crontab -l"
ansible db -m cron -a 'minute="*/10" job="/bin/echo hello" name="test cron job" state="absent"'
ansible db -a "crontab -l"
user模块是请求的是useradd, userdel, usermod三个指令,goup模块请求的是groupadd, groupdel, groupmod 三个指令。
1、英文
# ansible-doc -s user
- name: Manage user accounts
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.
comment: # Optionally sets the description (aka `GECOS') of user
account.
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.
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.
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.
generate_ssh_key: # Whether to generate a SSH key for the user in question.
This will *not*
overwrite an existing
SSH key.
group: # Optionally sets the user's primary group (takes a group
name).
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.
hidden: # Darwin/OS X only, optionally hide the user from the
login window and system
preferences. The default
will be 'True' if the
`system' option is used.
home: # Optionally set the user's home directory.
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.
login_class: # Optionally sets the user's login class, a feature of
most BSD OSs.
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.
name: # (required) Name of the user to create, remove or
modify.
non_unique: # Optionally when used with the -u option, this option
allows to change the
user ID to a non-unique
value.
password: # Optionally set the user's password to this crypted
value. On Darwin/OS X
systems, this value has
to be cleartext. Beware
of security issues. 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.
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.
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.
seuser: # Optionally sets the seuser type (user_u) on selinux
enabled systems.
shell: # Optionally set the user's shell. On Mac OS X, 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
Mac OS X is /bin/bash.
skeleton: # Optionally set a home skeleton directory. Requires
create_home option!
ssh_key_bits: # Optionally specify number of bits in SSH key to create.
ssh_key_comment: # Optionally define the comment for the SSH key.
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.
ssh_key_passphrase: # Set a passphrase for the SSH key. If no passphrase is
provided, the SSH key
will default to having
no passphrase.
ssh_key_type: # Optionally specify the type of SSH key to generate.
Available SSH key types
will depend on
implementation present
on target host.
state: # Whether the account should exist or not, taking action
if the state is
different from what is
stated.
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.
uid: # Optionally sets the `UID' of the user.
update_password: # `always' will update passwords if they differ.
`on_create' will only
set the password for
newly created users.
ansible-doc -s user
2、中文
groups:指定用户的属组
uid:指定用的uid
password:为用户设置登陆密码,此密码是明文密码加密后的密码
update_password:always/on_create
always:只有当密码不相同时才会更新密码(默认)
on_create:只为新用户设置密码
name:指定用户名
createhome:是否创建家目录 yes|no(默认是yes)
system:是否为系统用户
remove:当state=absent时,remove=yes则表示连同家目录一起删除,等价于userdel -r(默认是no)
state:是创建还是删除 present(添加(默认值))or absent(移除)
shell:指定用户的shell环境
append:yes/no
yes:增量添加group
no:全量变更group,只设置groups指定的group组(默认)
expires:设置用户的过期时间,值是一个时间戳
3、注意事项
注:指定password参数时,不能使用后面这一串密码会被直接传送到被管理主机的/etc/shadow文件中,所以需要先将密码字符串进行加密处理。然后将得到的字符串放到password中即可。
范例
- user: name=johnd comment="John Doe" uid=1040 group=admin
- user: name=james shell=/bin/bash groups=admins,developers append=yes
- user: name=johnd state=absent remove=yes
- user: name=james18 shell=/bin/zsh groups=developers expires=1422403387
#生成密钥时,只会生成公钥文件和私钥文件,和直接使用ssh-keygen指令效果相同,不会生成authorized_keys文件。
- user: name=test generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa
批量创建用户并设置密码:https://cloud.tencent.com/info/c23babde3ad9ff6bde07c532a6afa1d0.html
1、安装python-pip,并安装加密函数库-passlib
yum -y install python-pip
pip install --upgrade pip
pip install passlib
2、使用加密函数库,获取密文密码
# python -c "from passlib.hash import sha512_crypt; import getpass; print(sha512_crypt.using(rounds=5000).hash(getpass.getpass()))"
Password:
$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2.
3、创建一个系统用户,指定用户密码
ansible db -m user -a 'name="testops" password="$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2."'
4、查看测试
我们可以看到被管理主机已创建用户"testops",并且密码为密文已写入"/etc/shadow"用户文件中,尝试用ssh命令使用testops用户登录被管理主机,登录成功!
ansible db -m shell -a "cat /etc/shadow|grep testops"
ssh [email protected]
1、添加用户并设置密码(加密过程如上)
ansible db -m user -a 'name="testops" password="$6$0lwTSmqKOkL.ktgl$OnBexXC7haBf0FRHVMIZM2edDeFWBbpKJ2r9cxVwNvY.vh3IIUzwFz8n7jFglc0CrtQSY12ziDonVL6e71Og2."'
ansible db -m user -a 'name="testops" state="absent" remove="yes"'
复制文件
backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no
content:用于替代"src",可以直接设定指定文件的值
dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录
directory_mode:递归的设定目录的权限,默认为系统默认权限
force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
others:所有的file模块里的选项都可以在这里使用
src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用"/"来结尾,则只复制目录里的内容,如果没有使用"/"来结尾,则包含目录在内的整个内容全部复制,类似于rsync。
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 visudo example below.
1、使用src
ansible db -m copy -a 'src=/etc/hosts dest=/tmp/ owner=root mode=640 backup=no'
ansible db -m copy -a 'content="Hello ansible\n you are clever!\n" dest=/tmp/ansile.txt owner=root mode=640 backup=no'
ansible db -m copy -a 'content="Hello ansible\nyou are clever!\n" dest=/tmp/ansile.txt force=yes owner=root mode=640 backup=no'
设定文件属性和创建文件的符号链接
force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no
group:定义文件/目录的属组
mode:定义文件/目录的权限
owner:定义文件/目录的属主
path:必选项,定义文件/目录的路径
recurse:递归的设置文件的属性,只对目录有效
src:要被链接的源文件的路径,只应用于state=link的情况
dest:被链接到的路径,只应用于state=link的情况
state: directory:如果目录不存在,创建目录 file:即使文件不存在,也不会被创建 link:创建软链接 hard:创建硬链接 touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间 absent:删除目录、文件或者取消链接文件
2、使用范例
ansible db -m file -a "src=/etc/fstab dest=/tmp/fstab state=link"
ansible db -m file -a "path=/tmp/fstab state=absent"
ansible db -m file -a "path=/tmp/test state=touch"
安装程序包
config_file:yum的配置文件
disable_gpg_check:关闭gpg_check
disablerepo:不启用某个源
enablerepo:启用某个源
name:要进行操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径
state:状态(present安装,absent卸载,latest最新)
1、安装zsh
ansible web -m yum -a 'name=httpd state=latest'
ansible web -m yum -a 'name="@Development tools" state=present'
ansible web -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present'
目标主机验证
# rpm -q zsh
zsh-5.0.2-28.el7.x86_64
2、卸载
ansible web -m yum -a 'name=zsh state=absent'
# rpm -q zsh
package zsh is not installed
arguments:给命令行提供一些选项
enabled:是否开机启动 yes|no
name:必选项,服务名称
pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有响应,就会通过ps指令在进程中根据该模式进行查找,如果匹配到,则认为该服务依然在运行
runlevel:运行级别
sleep:如果执行了restarted,在则stop和start之间沉睡几秒钟
state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)
1、保持服务启动并设置为开机自启
ansible web -m service -a 'enabled=yes name=httpd state=started'
ansible web -a 'service httpd status'
#centOS7.x之前
ansible web -a 'chkconfig --list httpd'
#centOS7.x
ansible web -a 'systemctl is-enabled httpd'
尤其是用到复杂命令时(如带管道符等等)
# ansible-doc -s shell
- name: Execute commands in nodes.
shell:
chdir: # cd into this directory before running the command
creates: # a filename, when it already exists, this step will *not* be run.
executable: # change the shell used to execute the command. Should be an absolute path to the executable.
free_form: # (required) 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!
removes: # a filename, 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/false.
ansible-doc -s shell
使用command模块会报错,无法得到想要的结果。
ansible web -m shell -a "ps -ef|grep httpd"
将本地脚本复制到远程主机,并执行。
ansible-doc -s script
- name: Runs a local script on a remote node after transferring it
script:
chdir: # cd into this directory on the remote node before running the script
creates: # a filename, when it already exists, this step will *not* be run.
decrypt: # This option controls the autodecryption of source files using vault.
executable: # Name or path of a executable to invoke the script with
free_form: # (required) Path to the local script file followed by optional arguments. There is no parameter actually named 'free form'; see the
examples!
removes: # a filename, when it does not exist, this step will *not* be run.
ansible-doc -s script
1、实验脚本
#!/bin/bash
echo "test ansible script">>/tmp/scripts.ansible
2、执行
ansible db -m script -a '/tmp/script.sh'
archive: 归档,相当于同时开启recursive(递归)、links、perms、times、owner、group、-D选项都为yes ,默认该项为开启
checksum: 跳过检测sum值,默认关闭
compress:是否开启压缩
copy_links:复制链接文件,默认为no ,注意后面还有一个links参数
delete: 删除不存在的文件,默认no
dest:目录路径
dest_port:默认目录主机上的端口 ,默认是22,走的ssh协议
dirs:传速目录不进行递归,默认为no,即进行目录递归
rsync_opts:rsync参数部分
set_remote_user:主要用于/etc/ansible/hosts中定义或默认使用的用户与rsync使用的用户不同的情况
mode: push或pull 模块,push模的话,一般用于从本机向远程主机上传文件,pull 模式用于从远程主机上取文件
src=some/relative/path dest=/some/absolute/path rsync_path="sudo rsync"
src=some/relative/path dest=/some/absolute/path archive=no links=yes
src=some/relative/path dest=/some/absolute/path checksum=yes times=no
src=/tmp/helloworld dest=/var/www/helloword rsync_opts=--no-motd,--exclude=.git mode=pull
1 dump fstype:必选项,挂载文件的类型
2 name:必选项,挂载点
3 opts:传递给mount命令的参数
4 src:必选项,要挂载的文件
5 state:必选项 present:只处理fstab中的配置 absent:删除挂载点 mounted:自动创建挂载点并挂载之 umounted:卸载
name=/mnt/dvd src=/dev/sr0 fstype=iso9660 opts=ro state=present
name=/srv/disk src='LABEL=SOME_LABEL' state=present
name=/home src='UUID=b3e48f45-f933-4c8e-a700-22a159ec9077' opts=noatime state=present
ansible test -a 'dd if=/dev/zero of=/disk.img bs=4k count=1024'
ansible test -a 'losetup /dev/loop0 /disk.img'
ansible test -m filesystem 'fstype=ext4 force=yes opts=-F dev=/dev/loop0'
ansible test -m mount 'name=/mnt src=/dev/loop0 fstype=ext4 state=mounted opts=rw'
1 sha256sum:下载完成后进行sha256 check;
2 timeout:下载超时时间,默认10s
3 url:下载的URL
4 url_password、url_username:主要用于需要用户名密码进行验证的情况
5 use_proxy:是事使用代理,代理需事先在环境变更中定义
- name: download foo.conf
get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440
- name: download file with sha256 check
get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf sha256sum=b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c
官方提供的可能用到模块有git、svn版本控制模块,sysctl 、authorized_key_module系统模块,apt、zypper、pip、gem包管理模块,find、template文件模块,mysql_db、redis数据库模块,url 网络模块
https://docs.ansible.com/ansible/latest/modules/modules_by_category.html
ansible暂停模块:https://www.cnblogs.com/Csir/p/8653114.html