死磕ansible系列--Ad-hoc模块

Ad-hoc

Ad-Hoc 是指ansible下临时执行的一条命令,并且不需要保存的命令,对于复杂的命令会使用playbook。Ad-hoc的执行依赖于模块,ansible官方提供了大量的模块。 如:command、raw、shell、file、cron等,具体可以通过ansible-doc -l 进行查看 。可以使用ansible-doc -s module来查看某个模块的参数,也可以使用ansible-doc help module来查看该模块更详细的信息。

ansible 命令帮助

一个ad-hoc命令的执行,需要按以下格式进行执行:

1
ansible 主机或组-m 模块名-a '模块参数'  ansible参数
  • 主机和组,是在/etc/ansible/hosts 里进行指定的部分,当然动态Inventory 使用的是脚本从外部应用里获取的主机。
  • 模块名,可以通过ansible-doc -l 查看目前安装的模块,默认不指定时,使用的是command模块,具体可以查看/etc/ansible/ansible.cfg#module_name = command 部分,默认模块可以在该配置文件中进行修改。
  • 模块参数,可以通过 ansible-doc -s 模块名 查看具体的用法及后面的参数。
  • ansible参数,可以通过ansible命令的帮助信息里查看到,这里有很多参数可以供选择,如是否需要输入密码、是否sudo等。

常用选项

1
Ansible <host-pattern> [options]
  • -i:指定hosts
  • -m: 指定执行的模块。
  • -a: 指定相关的参数。
  • -v,--verbose: 输出更详细的执行过程信息
  • -i PATH,--inventory=PATH: 指定inventory信息
  • -f NUM,--fork NUM:指定线程数。
  • --private-key=PRIVATE_KEY_FILE: 指定秘钥文件。
  • -M DIRECTORY,--module-path=DIRECTORY: 指定模块存放路径。
  • -a ’ARGUMECTORY’,--args=’ARGUMENTS’:模块参数。
  • -k,--ask-pass SSH:认证密码(通常在node机器上没有做过免秘钥的时候用)。
  • -K,--ask-sudo-pass sudo:用户密码(–sudo时用)。
  • -t DIRECTORY,--tree=DIRECTORY:输出信息至DIRECTORY目录下,结果文件以远程主机名命名。
  • -t SECONDS,--timeout=SECONDS: 指定远程主机最大超时,单位是秒。
  • -u USERNAME,--username: 指定远程主机以username运行命令。
  • -l SUBSET,--limit=SUBSET: 指定运行主机。
  • -l ~REGEX: 指定运行主机(正则)。
  • --list-hosts: 列出符合条件的主机列表,不执行任何命令。

ansible和ansible-playbook默认会fork5个线程并发执行命令此时可使用-k num,根据自己主机硬件配置做调整,建议并发数是CPU的偶数倍

例子

1
2
3
ansible -i inventory/devlop linux-node2 -m ping ## 指定devlop组内的linux-node2主机执行ping
ansible -i inventory/devlop "~linux-node[1:3]" -m ping ##匹配正则必须~开头,匹配1和3两台机器
ansible -i inventory/devlop "~linux-node[1-3]" -m ping ## 匹配1,2,3 三台机器

后台执行

当命令执行时间比较长时,也可以放到后台执行,使用-B(后台放置多少秒)、-P(多少秒检查一下状态)参数,如下:

1
2
3
ansible all -B 3600-a "/usr/bin/long_running_operation --do-stuff" #后台执行命令3600s,-B 表示后台执行的时间
ansible all -m async_status -a "jid=123456789" #检查任务的状态
ansible all -B 1800-P 60-a "/usr/bin/long_running_operation --do-stuff" #后台执行命令最大时间是1800s即30分钟,-P 每60s检查下状态,默认15s

命令执行模块

命令执行模块包含如下 四个模块:

  • command模块:该模块通过-a跟要执行的命令可以直接执行,不过命令里如果有带有如下字符部分则执行不成功 “ “<”, “>”, “|”, “&” ;
  • shell 模块:用法基本和command一样,不过其是通过/bin/sh进行执行,所以shell 模块可以执行任何命令,就像在本机执行一样;
  • raw模块:用法和shell 模块一样 ,其也可以执行任意命令,就像在本机执行一样;
  • script模块:其是将管理端的shell 在被管理主机上执行,其原理是先将shell 复制到远程主机,再在远程主机上执行,原理类似于raw模块。

注:raw模块和comand、shell 模块不同的是其没有chdir、creates、removes参数,chdir参数的作用就是先切到chdir指定的目录后,再执行后面的命令,这在后面很多模块里都会有该参数 。
shell 和 command 的区别 :shell 支持管道命令。

command模块包含如下选项:

  • creates:一个文件名,当该文件存在,则该命令不执行 。
  • free_form:要执行的linux指令 。
  • chdir:在执行指令之前,先切换到该指定的目录 。
  • removes:一个文件名,当该文件不存在,则该选项不执行。
  • executable:切换shell来执行指令,该执行路径必须是一个绝对路径。

使用chdir的示例:

1
2
3
ansible 192.168.1.1 -m command -a 'chdir=/tmp/test.txt touch test.file'
ansible 192.168.1.1 -m shell -a 'chdir=/tmp/test.txt touch test2.file'
ansible 192.168.1.1 -m raw -a 'chdir=/tmp/text.txt touch test3.file'

三个命令都会返回执行成功的状态。不过实际上只有前两个文件会被创建成功。使用raw模块的执行的结果文件事实上也被正常创建了,不过不是在chdir指定的目录,而是在当前执行用户的家目录。

creates与removes示例:

1
2
3
ansible 192.168.1.1 -a 'creates=/tmp/server.txt uptime' #当/tmp/server.txt文件存在时,则不执行uptime指令

ansible 192.168.1.1 -a 'removes=/tmp/server.txt uptime' #当/tmp/server.txt文件不存在时,则不执行uptime指令

script模块示例:

要执行的脚本文件script.sh内容如下:

1
2
3
#/bin/bash
ifconfig
df -hT

执行ansible指令:ansible 10.212.52.252 -m script -a 'script.sh' |egrep '>>|stdout'

ansible 内置模块

根据zs官方的分类,将模块按功能分类为:云模块、命令模块、数据库模块、文件模块、资产模块、消息模块、监控模块、网络模块、通知模块、包管理模块、源码控制模块、系统模块、单元模块、web设施模块、windows模块 ,具体可以参看官方页面。

这里从官方分类的模块里选择最常用的一些模块进行介绍。

ping模块

测试主机是否是通的,用法很简单,不涉及参数:

1
ansible test -m ping

setup模块

setup模块,主要用于获取主机信息,在playbooks里经常会用到的一个参数gather_facts就与该模块相关。setup模块下经常使用的一个参数是filter参数,具体使用示例如下:

  • ansible test -m setup: 查看服务器的配置信息
  • ansible test -m setup --tree /tmp/hostlist: 将主机信息保存到/tmp/hostlist目录中。
  • ansible test -m setup -a 'filter=ansible_eth0': 过滤出eth0的网卡信息。
  • ansible test -m setup -a 'filter=ansible_*_mb': 过滤出内存信息。

file模块

file模块主要用于远程主机上的文件操作,file模块包含如下选项:

  • force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no 。
  • group:定义文件/目录的属组 。
  • mode:定义文件/目录的权限。
  • owner:定义文件/目录的属主。
  • path:必选项,定义文件/目录的路径。
  • recurse:递归的设置文件的属性,只对目录有效。
  • src:要被链接的源文件的路径,只应用于state=link的情况。
  • dest:被链接到的路径,只应用于state=link的情况 。
  • state:
    • directory:如果目录不存在,创建目录。
    • file:即使文件不存在,也不会被创建。
    • link:创建软链接。
    • hard:创建硬链接。
    • touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间。
    • absent:删除目录、文件或者取消链接文件。

使用示例:

  • ansible test -m file -a 'path=/tmp/test state=touch': 创建一个文件。
  • ansible test -m file -a "src=/etc/fstab dest=/tmp/fstab state=link": 创建一个快捷方式。
  • ansible test -m file -a "path=/tmp/fstab state=absent": 删除刚才创建的快捷方式。

copy模块

复制文件到远程主机,copy模块包含如下选项:

  • backup:在覆盖之前将原文件备份,备份文件包含时间信息。有两个选项:yes|no
  • content:用于替代”src”,可以直接设定指定文件的值
  • dest:必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录
  • directory_mode:递归的设定目录的权限,默认为系统默认权限
  • force:如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes
  • others:所有的file模块里的选项都可以在这里使用
  • src:要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用”/“来结尾,则只复制目录里的内容,如果没有使用”/“来结尾,则包含目录在内的整个内容全部复制,类似于rsync。

示例如下:

  • ansible -s test -m copy -a "src=/etc/hosts dest=/tmp/hosts owner=root group=root mode=0644": 将本地的hosts拷贝到远程的/tmp目录下。
  • ansible test -m copy -a "src=/etc/hosts dest=/tmp/hosts owner=root group=root mode=0644 backup=yes" 在目标文件存在的情况下,备份目标文件备份文件名:hosts.26172.2018-06-04@14:50:10~
  • ansible test -m copy -a "src=/mine/sudoers dest=/etc/sudoers validate='visudo -cf %s'": ???.

lineinfile模块

如果regexp不匹配文件中的任何一行,则将line所指定的行插入到文件的末尾。

示例如下:

1
2
3
4
- name: Disable UseDNS
lineinfile: dest=/etc/ssh/sshd_config regexp=^UseDNS line="UseDNS no"
notify:
- restart sshd

删除行

将/tmp/test.sh文件中所有匹配^pwd的行删除

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
[root@centos7 templates]# ansible test -m lineinfile -a "path=/tmp/test.sh regexp='^pwd' state=absent"
172.20.21.121 | SUCCESS => {
"backup": "",
"changed": true,
"found": 3,
"msg": "3 line(s) removed"
}

# 再次运行,没有匹配行
[root@centos7 templates]# ansible test -m lineinfile -a "path=/tmp/test.sh regexp='^pwd' state=absent"
172.20.21.121 | SUCCESS => {
"backup": "",
"changed": false,
"found": 0,
"msg": ""
}

替换行并设置文件权限

1
2
3
4
5
6
[root@centos7 ~]# ansible test -m lineinfile -a "path=/etc/hosts regexp='^127.0.0.1' line='127.0.0.1 localhost' owner=root group=root mode=0644"
172.20.21.121 | SUCCESS => {
"backup": "",
"changed": true,
"msg": "line replaced"
}

insertafter和insertbefore

当文件中没有匹配正则表达式^Listen80的行时,会将Listen 80插入到^#Listen所匹配的最后一行的后面。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@centos7 ~]# ansible test -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^Listen80' insertafter='^#Listen' line='Listen 80'"
172.20.21.121 | SUCCESS => {
"backup": "",
"changed": true,
"msg": "line added"
}

# insertbefore的使用方法类似
[root@centos7 ~]# ansible test -m lineinfile -a "path=/etc/httpd/conf/httpd.conf regexp='^#Listen80' insertbefore='^Listen 80' line='#Listen 80'"
172.20.21.121 | SUCCESS => {
"backup": "",
"changed": true,
"msg": "line added"
}

为文件新增一行

直接在文件中新增一行(如果line不存在则会插入),而不通过正则表达式进行匹配。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
[root@centos7 ~]# ansible test -m lineinfile -a "path=/root/test.sh line='liuhao test'"
172.20.21.121 | SUCCESS => {
"backup": "",
"changed": true,
"msg": "line added"
}

# 再次执行
[root@centos7 ~]# ansible test -m lineinfile -a "path=/root/test.sh line='liuhao test'"
172.20.21.121 | SUCCESS => {
"backup": "",
"changed": false,
"msg": ""
}

backrefs用法

backrefs为no时,如果没有匹配,则添加一行line。如果匹配了,则把匹配内容替被换为line内容。
backrefs为yes时,如果没有匹配,则文件保持不变。如果匹配了,把匹配内容替被换为line内容。

1
2
3
4
5
6
7
8
9
10
11
12
[root@centos7 ~]# ansible test -m lineinfile -a "path=/root/test.sh line='liuhao test1' regexp='^liuhao' backrefs=yes"
172.20.21.121 | SUCCESS => {
"backup": "",
"changed": true,
"msg": "line replaced"
}
[root@centos7 ~]# ansible test -m lineinfile -a "path=/root/test.sh line='liuhao test1' regexp='^liuhao2' backrefs=yes"
172.20.21.121 | SUCCESS => {
"backup": "",
"changed": false,
"msg": ""
}

blockinfile模块

示例如下:

1
2
3
4
5
- name: change system filelimit
blockinfile:
path: /etc/security/limits.conf
block: |
* - nofile 65535

service模块

用于管理服务
该模块包含如下选项:

  • arguments:给命令行提供一些选项
  • enabled:是否开机启动 yes|no
  • name:必选项,服务名称
  • pattern:定义一个模式,如果通过status指令来查看服务的状态时,没有响应,就会通过ps指令在进程中根据该模式进行查找,如果匹配到,则认为该服务依然在运行
  • runlevel:运行级别
  • sleep:如果执行了restarted,在则stop和start之间沉睡几秒钟
  • state:对当前服务执行启动,停止、重启、重新加载等操作(started,stopped,restarted,reloaded)

使用示例:

1
2
3
ansible test -m service -a "name=httpd state=started enabled=yes"
asnible test -m service -a "name=foo pattern=/usr/bin/foo state=started"
ansible test -m service -a "name=network state=restarted args=eth0"

systemd模块

systemd模块用于控制远程主机的systemd服务,说白了,就是Linux下的systemd命令。需要远程主机支持systemd。

用法和service模块基本相同。

模块参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
- name: Make sure a service is running
systemd: state=started name=httpd

- name: stop service cron on debian, if running
systemd: name=cron state=stopped

- name: restart service cron on centos, in all cases, also issue daemon-reload to pick up config changes
systemd:
state: restarted
daemon_reload: yes
name: crond

- name: reload service httpd, in all cases
systemd:
name: httpd
state: reloaded

- name: enable service httpd and ensure it is not masked
systemd:
name: httpd
enabled: yes
masked: no

- name: enable a timer for dnf-automatic
systemd:
name: dnf-automatic.timer
state: started
enabled: True

- name: just force systemd to reread configs (2.4 and above)
systemd: daemon_reload=yes

cron模块

用于管理计划任务包含如下选项:

  • backup:对远程主机上的原任务计划内容修改之前做备份。
  • cron_file:如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户的任务计划。
  • day:日(1-31,/2,……)。
  • hour:小时(0-23,/2,……) 。
  • minute:分钟(0-59,/2,……)。
  • month:月(1-12,/2,……)。
  • weekday:周(0-7,*,……)。
  • job:要执行的任务,依赖于state=present。
  • name:该任务的描述。
  • special_time:指定什么时候执行,参数:reboot,yearly,annually,monthly,weekly,daily,hourly。
  • state:确认该任务计划是创建还是删除。
  • user:以哪个用户的身份执。

示例:

1
2
3
4
ansible test -m cron -a 'name="a job for reboot" special_time=reboot job="/some/job.sh"'
ansible test -m cron -a 'name="yum autoupdate" weekday="2" minute=0 hour=12 user="root"
ansible test -m cron -a 'backup="True" name="test" minute="0" hour="5,2" job="ls -alh > /dev/null"'
ansilbe test -m cron -a 'cron_file=ansible_yum-autoupdate state=absent'

yum模块

使用yum包管理器来管理软件包,其选项有:

  • config_file:yum的配置文件 。
  • disable_gpg_check:关闭gpg_check 。
  • disablerepo:不启用某个源 。
  • enablerepo:启用某个源。
  • name:要进行操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径 。
  • state:状态(present(当前版本),absent(删除),latest)。

示例如下:

1
2
3
ansible test -m yum -a 'name=httpd state=latest'
ansible test -m yum -a 'name="@Development tools" state=present'
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'

user模块与group模块

user模块是请求的是useradd, userdel, usermod三个指令。
goup模块请求的是groupadd, groupdel, groupmod 三个指令。

user模块

  • home:指定用户的家目录,需要与createhome配合使用.
  • groups:指定用户的属组.
  • uid:指定用的uid.
  • password:指定用户的密码.
  • name:指定用户名.
  • createhome:是否创建家目录 yes|no.
  • system:是否为系统用户.
  • remove:当state=absent时,remove=yes则表示连同家目录一起删除,等价于userdel -r.
  • state:是创建还是删除.
  • shell:指定用户的shell环境.

使用示例:

1
2
3
4
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
user: name=test generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa #生成密钥时,只会生成公钥文件和私钥文件,和直接使用ssh-keygen指令效果相同,不会生成authorized_keys文件。

注:指定password参数时,不能使用明文密码,因为后面这一串密码会被直接传送到被管理主机的/etc/shadow文件中,所以需要先将密码字符串进行加密处理。然后将得到的字符串放到password中即可。

1
2
3
4
shell>  echo "123456" | openssl passwd -1 -salt $(< /dev/urandom tr -dc '[:alnum:]' | head -c 32) -stdin
$1$guC5vhaV$/Ypvq7uxwpwFjoGKLRgZw1
#### 使用上面的密码创建用户
ansible all -m user -a 'name=foo password="$1$4P4PlFuE$ur9ObJiT5iHNrb9QnjaIB0"'

不同的发行版默认使用的加密方式可能会有区别,具体可以查看/etc/login.defs文件确认,centos 6.5版本使用的是SHA512加密算法。

password 密码生成

两种方法设置用户名和密码

第一种 使用ansible自带的函数设置

1
2
3
4
5
6
7
8
---
- hosts: "`hosts`"
gather_facts: false

tasks:
- name: Change password
user: name={{ item }} password={{ user_pass | password_hash('sha512') }}
with_items: users
1
2
### 执行,123456 就是密码
ansible-playbook testuser.yml -e "hosts=jump users=testuser user_pass=*(123456)"

2、第二种 使用python模块先加密完成

1
2
3
4
5
6
7
 2.2 调用crypt 模块

(只用于 Unix)实现了单向的 DES 加密, Unix 系统使用这个加密算法来储存密码。

[root@hrserver1 user]# python -c 'import crypt; print crypt.crypt("hh4213", "hadoop")'
haHAfV7dvUhpM
2.3 得到加密算法密码haHAfV7dvUhpM代入剧本password
1
2
3
4
5
6
7
8
9
---
- hosts: all
user: root
vars:
# created with:
# python -c 'python -c 'import crypt; print crypt.crypt("hh4213", "hadoop")'
password: haHAfV7dvUhpM
tasks:
- user: name=hruser password=`password` update_password=always
1
2
### 执行
ansible-playbook user_pass.yml -v

group模块

1
ansible all -m group -a 'name=somegroup state=present'

synchronize模块

使用 ansible synchronize_module 可以控制机和目标机之间同步目录
使用rsync同步文件,其参数如下:

  • 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 模式用于从远程主机上取文件,默认push模式.

使用示例:

推送 push

1
2
3
ansible test -m synchronize -a 'src=some/relative/path dest=/some/absolute/path rsync_path="sudo rsync" '
ansible test -m synchronize -a 'src=some/relative/path dest=/some/absolute/path archive=no links=yes '
ansible test -m synchronize -a 'src=some/relative/path dest=/some/absolute/path checksum=yes times=no '

拉取 pull

1
ansible test -m synchronize -a 'src=/tmp/helloworld dest=/var/www/helloword rsync_opts=--no-motd,--exclude=.git mode=pull '

synchronize 结合-CD参数

1
2
.d..t...... ./
<f..tpog... jr-sta.conf
  • t: 表示修改了时间。
  • p: 表示修改了权限。
  • o: 表示修改了user。
  • g: 表示修改了group。
  • s: 表示修改了大小。

Explanation of each bit position and value in rsync’s output:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
YXcstpoguax  path/to/file
|||||||||||
||||||||||╰- x: The extended attribute information changed
|||||||||╰-- a: The ACL information changed
||||||||╰--- u: The u slot is reserved for future use
|||||||╰---- g: Group is different
||||||╰----- o: Owner is different
|||||╰------ p: Permission are different
||||╰------- t: Modification time is different
|||╰-------- s: Size is different
||╰--------- c: Different checksum (for regular files), or
|| changed value (for symlinks, devices, and special files)
|╰---------- the file type:
| f: for a file,
| d: for a directory,
| L: for a symlink,
| D: for a device,
| S: for a special file (e.g. named sockets and fifos)
╰----------- the type of update being done::
<: file is being transferred to the remote host (sent)
>: file is being transferred to the local host (received)
c: local change/creation for the item, such as:
- the creation of a directory
- the changing of a symlink,
- etc.
h: the item is a hard link to another item (requires
--hard-links).
.: the item is not being updated (though it might have
attributes that are being modified)
*: means that the rest of the itemized-output area contains
a message (e.g. "deleting")

filesystem模块

在块设备上创建文件系统

  • dev:目标块设备.
  • force:在一个已有文件系统 的设备上强制创建.
  • fstype:文件系统的类型.
  • opts:传递给mkfs命令的选项.

示例:

1
2
3
ansible test -m filesystem -a 'fstype=ext2 dev=/dev/sdb1 force=yes'

ansible test -m filesystem -a 'fstype=ext4 dev=/dev/sdb1 opts="-cc"'

mount模块

配置挂载点

  • fstype:必选项,挂载文件的类型.
  • name:必选项,挂载点.
  • opts:传递给mount命令的参数.
  • src:必选项,要挂载的文件.
  • state:必选项.
    • present:只在fstab中写入配置。
    • absent:删除挂载点。
    • mounted:自动创建挂载点并挂载, 同时写入fstab。
    • umounted:卸载。

示例:

1
2
3
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 创建一个硬盘并挂载

1
2
3
4
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'

get_url 模块

该模块主要用于从http、ftp、https服务器上下载文件(类似于wget),主要有如下选项:

  • sha256sum:下载完成后进行sha256 check.
  • timeout:下载超时时间,默认10s.
  • url:下载的URL.
  • url_password、url_username:主要用于需要用户名密码进行验证的情况.
  • use_proxy:是事使用代理,代理需事先在环境变更中定义.

示例:

1
2
get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440
get_url: url=http://example.com/path/file.conf dest=/etc/foo.conf sha256sum=b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c

unarchive模块

用于解压文件,模块包含如下选项:

  • copy:在解压文件之前,是否先将文件复制到远程主机,默认为yes。若为no,则要求目标主机上压缩包必须存在。
  • creates:指定一个文件名,当该文件存在时,则解压指令不执行。
  • dest:远程主机上的一个路径,即文件解压的路径 。
  • grop:解压后的目录或文件的属组。
  • list_files:如果为yes,则会列出压缩包里的文件,默认为no,2.0版本新增的选项。
  • mode:解决后文件的权限。
  • src:如果copy为yes,则需要指定压缩文件的源路径 。
  • owner:解压后文件或目录的属主。

示例如下:

1
2
3
- unarchive: src=foo.tgz dest=/var/lib/foo
- unarchive: src=/tmp/foo.zip dest=/usr/local/bin copy=no
- unarchive: src=https://example.com/example.zip dest=/usr/local/bin copy=no

sysctl模块

示例如下:

1
2
3
4
- name: set sysctl
sysctl: name={{ item.name }} value={{ item.value }} state=present
with_items:
- { name: vm.max_map_count, value: 262144 }

authorized_key 模块

用于向远程主机的某个账户的authorized_keys文件中增加公钥 或 从中移除公钥。

  • exclusive: 是否从authorized_keys文件中移除所有其他的未指定的公钥。当想要指定多个公钥的时候,可以将key参数指定为 新行 分隔的公钥列表。需要注意的是,当使用with_*的时候,每次迭代都会进行移除操作。(Choices: yes, no)[Default: no]

  • key: ssh公钥。可以是一个字符串,也可以是一个url。

  • manage_dir: 是否管理authorized_keys文件所在的目录。如果设置了这个选项,那么authorized_key模块,会创建这个目录,并且会设置目录的所有者和权限。(Choices: yes, no)[Default: yes]

  • path: 给authorized_keys文件设置一个替代的路径。[Default: (homedir)+/.ssh/authorized_keys]

  • state: present表示添加公钥,absent表示删除公钥。

  • user: 远程主机上的用户名。

  • validate_certs: 只有key的值是https url的时候,才起作用。如果设置该选项为no,那么不会校验SSL证书。(Choices: yes, no)[Default: yes]

例子

使用管理机上的本地文件的例子:

1
- authorized_key: user=charlie key="{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"

使用github url作为key的来源

1
- authorized_key: user=charlie key=https://github.com/charlie.keys

给authorized_keys文件指定一个替代的路径

1
2
3
4
5
- authorized_key:
user: charlie
key: "{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
path: '/etc/ssh/authorized_keys/charlie'
manage_dir: no

使用with_file循环

1
2
3
4
5
- name: Set up authorized_keys for the deploy user
authorized_key: user=deploy key="{{ item }}"
with_file:
- public_keys/doe-jane
- public_keys/doe-john

使用ssh key选项

1
2
3
4
- authorized_key:
user: charlie
key: "{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
key_options: 'no-port-forwarding,from="10.0.1.1"'

使用validate_certs

1
- authorized_key: user=charlie key=https://github.com/user.keys validate_certs=no

向远程主机的root用户的authorized_keys文件中,增加本地的public_keys/doe-jane文件中列出的公钥列表,并删除不在这个列表中的公钥

1
2
3
- authorized_key: user=root key="{{ item }}" state=present exclusive=yes
with_file:
- public_keys/doe-jane

将正在运行ansible的用户的主目录下的.ssh/id_rsa.pub文件里的公钥拷贝到远程主机的ubuntu用户的authorized_keys文件中

1
2
- authorized_key: user=ubuntu key="{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}"
become: yes

参考文档

ansible synchronize 同步文件夹