Ansible模块简介
ansible 模块文档
[root@ansible-manager ~]# ansible-doc -l # 列出 Ansible 支持的模块
[root@ansible-manager ~]# ansible-doc ping #查看ping模块帮助信息
如果想要获取到各个模块更加详细的用法,可以使用ansible-doc -s
命令
比如,我们想要获取 ping 模块的详细使用方法,则可以使用如下命令:
[root@ansible-manager ~]# ansible-doc -s ping
- name: Try to connect to host, verify a usable python and return `pong' on success
ping:
data: # Data to return for the `ping' return value. If this parameter is set to `crash', the module will cause an exception.
ansible 常用模块
类型 | 模块 |
---|---|
命令 | command,shell,script |
文件/磁盘操作 | stat,find,file,template,archive,replace,lifeline,blockinfile,filesystem,mount |
传输 | copy,fetch,slurp,unarchive ,get_url ,synchronize |
包管理 | yum , package ,gem,npm, pip,easy_install,rpm_key |
用户、用户组管理 | user, group |
文件包含 | import_tasks , include_tasks , include_vars |
MySql数据库 | mysql_user,mysql_db, mysql_replication |
PostGresql数据库 | postgresql_user,postgresql_db |
服务 | service ,systemd ,supervisorctl |
检查 | wait_for,ping |
其他 | hostname,cron,debug ,fail ,selinux ,set_fact ,setup,sysctl ,authorized_key |
command
-
参考:https://docs.ansible.com/ansible/2.9/modules/command_module.html#command-module
-
功能:在远程主机执行命令,默认模块,可忽略
-m
选项。
常用参数
chdir
参数 : 此参数的作用就是指定一个目录,在执行对应的命令之前,会先进入到 chdir 参数指定的目录中。creates
参数 :当指定的文件存在时,就不执行对应命令,比如,如果 /testdir/test文件存在,就不执行我们指定的命令。free_form
参数 :必须参数,指定需要远程执行的命令。需要说明一点,free_form 参数与其他参数(如果想要使用一个参数,那么则需要为这个参数赋值,也就是name=value模式)并不相同。比如,当我们想要在远程主机上执行 ls 命令时,我们并不需要写成”free_form=ls” ,这样写反而是错误的,因为并没有任何参数的名字是 free_form,当我们想要在远程主机中执行 ls 命令时,直接写成 ls 即可。因为 command 模块的作用是执行命令,所以,任何一个可以在远程主机上执行的命令都可以被称为 free_form。removes
参数 :与 creates 参数的作用正好相反,它的作用是当指定的文件不存在时,就不执行对应命令,比如,如果 /testdir/tests 文件不存在,就不执行我们指定的命令,此参数并不会帮助我们删除文件。
此命令不支持 有重定向、管道符、 $VARNAME < > | ; & 等,需要使用shell模块实现;另外,如果远程节点是 windows 操作系统,则需要使用 win_command 模块。
#配置文件,command作为默认模块
[root@localhost ~]# cat /etc/ansible/ansible.cfg | grep module_name -B2
# default module name for /usr/bin/ansible
#module_name = command
示例:
# 查看 Client 分组主机内存使用情况
[root@ansible-manager ~]# ansible Client -m command -a "free -m"
# 查看root目录下的文件:
[root@ansible-manager ~]# ansible ansible-demo3 -m command -a "ls"
#上面命令表示在 ansible-demo3 主机上执行 ls 命令,因为使用的是 root 用户,所以默认情况下,ls 出的结果是 ansible-demo3 主机中 root 用户家目录中的文件列表。
#chdir 参数表示执行命令之前,会先进入到指定的目录中,所以上面命令表示查看 ansible-demo3 主机上 /testdir 目录中的文件列表,返回显示有2个文件。
[root@ansible-manager ~]# ansible ansible-demo3 -m command -a "chdir=/testdir ls"
ansible-demo3 | SUCCESS | rc=0 >>
testfile1
testfile2
#命令包含通配符
[root@ansible-manager ~]# ansible all -m command -a "/bin/bash -c 'mv /etc/yum.repos.d/Cent* /etc/yum.repos.d/bak'"
playbook示例:
多行命令【编译安装时】
- command: "{{ item }}"
args:
chdir: "/src/package/"
with_items:
- "./configure"
- "/usr/bin/make"
- "/usr/bin/make install"
获取主机名
- hosts: all
gather_facts: false
tasks:
- name: Get hostname
command: /bin/hostname
register: my_hostname
- debug: var=my_hostname.stdout
shell
-
参考:https://docs.ansible.com/ansible/2.9/modules/shell_module.html#shell-module
-
功能:shell 模块可以帮助我们在远程主机上执行命令。与 command 模块不同的是,shell 模块在远程主机中执行命令时,会经过远程主机上的 /bin/sh 程序处理。
常用参数:
chdir
参数 : 此参数的作用就是指定一个目录,在执行对应的命令之前,会先进入到 chdir 参数指定的目录中。cmd
参数:要运行的命令,后跟可选参数。creates
参数 :指定一个文件,当指定的文件存在时,就不执行对应命令。executable
参数:默认情况下,shell 模块会调用远程主机中的 /bin/sh 去执行对应命令,通常情况下,远程主机中的默认 shell 都是 bash。如果你想要使用其他类型的 shell 执行命令,则可以使用此参数指定某种类型的 shell 去执行对应的命令。指定 shell 文件时,需要使用绝对路径。free_form
参数 :shell模块以字符串形式运行自由格式命令。 没有名为“自由格式”的实际参数。 请参阅有关如何使用此模块的示例。removes
参数 :指定一个文件,当指定的文件不存在时,就不执行对应命令。stdin
参数:将命令的stdin设置为指定的值stdin_add_newline
参数:是否在标准输入数据后面添加换行符。warn
参数:是否启用任务警告。
示例:
[root@localhost ~]# ansible all -m shell -a "chdir=/root echo mytest > test"
192.168.93.63 | CHANGED | rc=0 >>
playbook示例:
多行命令【编译安装时】
- name: Build nginx
shell: |
cd nginx-1.11.13
sudo ./configure
sudo make
sudo make install
- name: install-proj
shell: cd /home/application/gis-soft/proj.4-4.9.2;./configure --prefix=/home/application/gis/proj.4-4.9.2;make -j 24;make install
shell判断pg sql命令是否执行成功
- name: check postgis
shell: su - postgres -c "psql --command="select * from pg_available_extensions where name like 'postgis%';""
register: shell_result
- debug:
var: shell_result.stdout
shell 判断mysql-slave 状态
- name: Get Slave
mysql_replication:
mode: getslave
login_user: root
login_password: "{{ mysql_password }}"
login_unix_socket: '/tmp/mysql.sock'
register: slave_status
when: mysql_role == "slave"
- name: Slave_IO_Running
debug: msg="Slave_IO_Running {{ slave_status.Slave_IO_Running }}"
when: mysql_role == "slave"
- name: Slave_SQL_Running
debug: msg="Slave_SQL_Running {{ slave_status.Slave_SQL_Running }}"
when: mysql_role == "slave"
shell 判断swap分区是否分区
- name: shutdown | get the status of swap
shell: grep swap /etc/fstab | grep -c "#"
register: swap
ignore_errors: yes
tags: swap
- name: shutdown | swapoff -a
shell: swapoff -a
when: swap.stdout == "0"
ignore_errors: yes
tags: swap
- name: shutdown | 注释/etc/fstab/swap 那一行
replace: dest=/etc/fstab regexp='(.*)swap(\s+)swap' replace='# \1swap\2swap'
when: swap.stdout == "0"
ignore_errors: yes
tags: swap
shell 返回值
Key | Returned | Description |
---|---|---|
cmd string | always | The command executed by the task Sample:rabbitmqctl join_cluster rabbit@master |
delta string | always | The command execution delta time Sample:0:00:00.325771 |
end string | always | The command execution end time Sample:2016-02-25 09:18:26.755339 |
msg boolean | always | changed Sample:True |
rc int | always | The command return code (0 means success) |
start string | always | The command execution start time Sample:2016-02-25 09:18:26.429568 |
stderr string | always | The command standard error Sample:ls: cannot access foo: No such file or directory |
stdout string | always | The command standard output Sample:Clustering node rabbit@slave1 with rabbit@master ... |
stdout_lines list | always | The command standard output split in lines Sample:["u'Clustering node rabbit@slave1 with rabbit@master ...'"] |
script
-
参考:https://docs.ansible.com/ansible/2.9/modules/script_module.html#script-module
-
功能:script 模块可以在远程主机上执行 ansible 管理主机上的脚本,也就是说,脚本一直存在于 ansible 管理主机本地,不需要手动拷贝到远程主机后再执行。
常用参数:
chdir
参数 : 此参数的作用就是指定一个远程主机中的目录,在执行对应的脚本之前,会先进入到 chdir 参数指定的目录中。cmd
:要运行的本地脚本的路径,后跟可选参数。creates
参数 :指定一个远程主机中的文件,当指定的文件存在时,就不执行对应脚本,可参考 command 模块中的解释。decrypt
:此选项使用Vault控制源文件的自动解密executable
:用来调用脚本的可执行文件的名称或路径free_form
参数 :本地脚本文件的路径,后跟可选参数removes
参数 :远程节点上的文件名(如果文件名不存在)将不会运行
示例:
- ansible 主机中的 /testdir/testscript.sh 脚本将在 ansible-demo3 主机中执行,执行此脚本之前,会先进入到 ansible-demo3 主机中的 /opt 目录
ansible ansible-demo3 -m script -a "chdir=/opt /testdir/testscript.sh"
- ansible-demo3 主机中的 /testdir/testfile1文件已经存在,ansible 主机中的 /testdir/testscript.sh 脚本将不会在 ansible-demo3 主机中执行。
ansible ansible-demo3 -m script -a "creates=/testdir/testfile1 /testdir/testscript.sh"
- ansible-demo3 主机中的 /testdir/testfile1 文件存在,ansible 主机中的 /testdir/testscript.sh 脚本则会在 ansible-demo3 主机中执行。
ansible ansible-demo3 -m script -a "removes=/testdir/testfile1 /testdir/testscript.sh"
playbook示例:
- name: Run a script with arguments (free form)
script: /some/local/script.sh --some-argument 1234
- name: Run a script with arguments (using 'cmd' parameter)
script:
cmd: /some/local/script.sh --some-argument 1234
- name: Run a script only if file.txt does not exist on the remote node
script: /some/local/create_file.sh --some-argument 1234
args:
creates: /the/created/file.txt
- name: Run a script only if file.txt exists on the remote node
script: /some/local/remove_file.sh --some-argument 1234
args:
removes: /the/removed/file.txt
- name: Run a script using an executable in a non-system path
script: /some/local/script
args:
executable: /some/remote/executable
- name: Run a script using an executable in a system path
script: /some/local/script.py
args:
executable: python3
临时执行脚本
# cat test.yaml
- name: test
hosts: hosts
user: root
any_errors_fatal: true
tasks:
- name: resolve docker
script: resolve.sh
stat
- 参考:https://docs.ansible.com/ansible/2.9/modules/stat_module.html#stat-module
- 功能:检查文件或文件系统的状态
常用参数:
path
:文件/对象的完整路径,required
[root@localhost ~]# ansible all -m stat -a "path=/etc/sysctl.conf"
示例:
tasks:
- name: Check that the somefile.conf exists
stat:
path: /etc/file.txt
register: stat_result
- name: Create the file, if it doesnt exist already
file:
path: /etc/file.txt
state: touch
when: stat_result.stat.exists == False
tasks:
- name: Ansible check file exists.
stat:
path: /etc/issue
register: p
- debug:
msg: "File exists..."
when: p.stat.exists
- debug:
msg: "File not found"
when: p.stat.exists == False
find
- 参考:https://docs.ansible.com/ansible/2.9/modules/find_module.html#find-module
- 功能:根据特定搜索条件,查找符合条件的文件,返回文件列表
常用参数:
paths
参数 :必须参数,指定在哪个目录中查找文件,可以指定多个路径,路径间用逗号隔开,此参数有别名,使用别名 path 或者别名 name 可以代替 paths。recurse
参数 : 默认情况下,只会在指定的目录中查找文件,也就是说,如果目录中还包含目录,ansible 并不会递归的进入子目录查找对应文件,如果想要递归的查找文件,需要使用 recurse 参数,当 recurse 参数设置为 yes 时,表示在指定目录中递归的查找文件。hidden
参数 :默认情况下,隐藏文件会被忽略,当 hidden 参数的值设置为 yes 时,才会查找隐藏文件。file_type
参数 : 默认情况下, ansible 只会根据条件查找”文件” ,并不会查找”目录”或”软链接”等文件类型,如果想要指定查找的文件类型,可以通过 file_type 指定文件类型,可指定的文件类型有 any、directory、file、link 四种。patterns
参数 : 使用此参数指定需要查找的文件名称,支持使用 shell(比如通配符)或者正则表达式去匹配文件名称,默认情况下,使用 shell 匹配对应的文件名,如果想要使用 python 的正则去匹配文件名,需要将 use_regex 参数的值设置为 yes。use_regex
参数:默认情况下,find 模块不会使用正则表达式去解析 patterns 参数中对应的内容,当 use_regex 设置为 yes 时,表示使用 python 正则解析 patterns 参数中的表达式,否则,使用 glob 通配符解析 patterns 参数中的表达式。contains
参数:使用此参数可以根据文章内容查找文件,此参数的值为一个正则表达式,find 模块会根据对应的正则表达式匹配文件内容。age
参数 :使用此参数可以根据时间范围查找文件,默认以文件的 mtime 为准与指定的时间进行对比,比如,如果想要查找 mtime 在3天之前的文件,那么可以设置 age=3d,如果想要查找 mtime 在3天以内的文件,可以设置 age=-3d,这里所说的3天是按照当前时间往前推3天,可以使用的单位有秒(s)、分(m)、时(h)、天(d)、星期(w)。age_stamp
参数 :文件的时间属性中有三个时间种类,atime、ctime、mtime,当我们根据时间范围查找文件时,可以指定以哪个时间种类为准,当根据时间查找文件时,默认以 mtime 为准。size
参数 :使用此参数可以根据文件大小查找文件,比如,如果想要查找大于3M的文件,那么可以设置 size=3m,如果想要查找小于50k的文件,可以设置 size=-50k,可以使用的单位有 t、g、m、k、b。get_checksum
参数 :当有符合查找条件的文件被找到时,会同时返回对应文件的 sha1校验码,如果要查找的文件比较大,那么生成校验码的时间会比较长。excludes
参数:排除目录 或 文件
示例:
- 在 ansible-demo3 主机的 /testdir目录中查找文件内容中包含 abc 字符串的文件,隐藏文件会被忽略,不会进行递归查找。
ansible ansible-demo3 -m find -a 'paths=/testdir contains=".*abc.*" '
- ansible-demo3 主机的 /testdir 目录以及其子目录中查找文件内容中包含 abc 字符串的文件,隐藏文件会被忽略。
ansible ansible-demo3 -m find -a 'paths=/testdir contains=".*abc.*" recurse=yes'
- 在ansible-demo3 主机的 /testdir 目录中查找以 .sh 结尾的文件,包括隐藏文件,但是不包括目录或其他文件类型,不会进行递归查找。
ansible ansible-demo3 -m find -a 'paths=/testdir patterns="*.sh" hidden=yes'
- ansible-demo3 主机的 /testdir 目录中查找以 .sh 结尾的文件,包括隐藏文件,包括所有文件类型,比如文件、目录、或者软链接,但是不会进行递归查找。
ansible ansible-demo3 -m find -a 'paths=/testdir patterns="*.sh" file_type=any hidden=yes'
- 在ansible-demo3 主机的 /testdir 目录中查找以 .sh 结尾的文件,只不过 patterns 对应的表达式为正则表达式,查找范围包括隐藏文件,包括所有文件类型,但是不会进行递归查找,不会对 /testdir 目录的子目录进行查找。
ansible ansible-demo3 -m find -a 'paths=/testdir patterns=".*\.sh" use_regex=yes file_type=any hidden=yes'
- 在 ansible-demo3 主机的 /testdir 目录中以及其子目录中查找 mtime 在1天以内的文件,不包含隐藏文件,不包含目录或软链接文件等文件类型。
ansible ansible-demo3 -m find -a "path=/testdir age=-1d recurse=yes"
- 在 ansible-demo3 主机的 /testdir 目录中以及其子目录中查找大于 2g 的文件,不包含隐藏文件,不包含目录或软链接文件等文件类型。
ansible ansible-demo3 -m find -a "paths=/testdir size=2g recurse=yes"
- 在 ansible-demo3 主机的 /testdir 目录中以及其子目录中查找以 .sh 结尾的文件,并且返回符合条件文件的 sha1 校验码,包括隐藏文件。
ansible ansible-demo3 -m find -a "paths=/testdir patterns=*.sh get_checksum=yes hidden=yes recurse=yes"
playbook示例:
获取文件名
---
- name: Register screen session
find:
paths: '/var/run/screen/S-root/'
file_type: 'any'
patterns: '*.stress'
register: find_result
- name: clean screen session
shell: 'screen -X -S {{ item.path | basename }} quit'
with_items: "{{ find_result.files }}"
when: find_result.matched != 0
获取文件并删除
- name: find old jar
find:
paths: "{{ app_path }}/"
patterns: "*.jar"
register: files_to_delete
- name: remove old jar
file:
path: "{{ item.path }}"
state: absent
with_items: "{{ files_to_delete.files }}"
清理jenkins 工作目录源代码【除了打包依赖缓存】
- name: "############清理workspace-1######################################"
find:
paths: "/var/lib/jenkins/workspace/{{ job_name }}"
file_type: any
excludes: 'node_modules'
register: files_to_delete
ignore_errors: yes
tags: workspace
- name: "############清理workspace-2######################################"
file:
path: "{{ item.path }}"
state: absent
with_items: "{{ files_to_delete.files }}"
ignore_errors: yes
tags: workspace
file
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:对文件的基本操作。比如,创建文件或目录、删除文件或目录、修改文件权限等,甚至是软硬连接
常用参数:
path
参数 :必选参数,用于指定要操作的文件或目录。state
参数 :此参数非常灵活,其对应的值需要根据情况设定。state=directory 创建目录 ; state=touch 创建文件 ; state=link 创建软连接; state=hard 创建硬链接; sate=absent 删除目标- 文件权限,所属人,所属组:
owner
,group
,mode
recurse
参数:当要操作的文件为目录,将recurse设置为yes,可以递归的修改目录中文件的属性。src
参数 :当state设置为link或者hard时,表示我们想要创建一个软链或者硬链,所以,我们必须指明软链或硬链链接的哪个文件,通过src参数即可指定链接源。force
参数 : 当state=link的时候,可配合此参数强制创建链接文件,当force=yes时,表示强制创建链接文件。不过强制创建链接文件分为三种情况。
情况一:当要创建的链接文件指向的源文件并不存在时,使用此参数,可以先强制创建出链接文件。
情况二:当要创建链接文件的目录中已经存在与链接文件同名的文件时,将force设置为yes,会将同名文件覆盖为链接文件,相当于删除同名文件,创建链接文件。
情况三:当要创建链接文件的目录中已经存在与链接文件同名的文件,并且链接文件指向的源文件也不存在,这时会强制替换同名文件为链接文件。
示例:
- 在 ansible-demo3 主机上创建一个名为 testfile1的文件,如果 testfile1文件已经存在,则更新文件时间戳,与 touch 命令的作用相同。
ansible ansible-demo3 -m file -a "path=/testdir/testfile1 state=touch"
- 在 ansible-demo3 主机上创建一个名为 /testdir/testdir 的目录,如果 /testdir/testdir 目录已经存在,则不进行任何操作。
ansible ansible-demo3 -m file -a "path=/testdir/testdir state=directory"
- 在 ansible-demo3 上为 testfile1 文件创建软链接文件,软链接名为 linkfile1,执行下面命令的时候,testfile1 已经存在。
ansible ansible-demo3 -m file -a "path=/testdir/linkfile1 state=link src=/testdir/testfile1"
- 在 ansible-demo3 上为 testfile2 文件创建硬链接文件,硬链接名为 hardfile2,执行下面命令的时候,testfile2 已经存在。
ansible ansible-demo3 -m file -a "path=/testdir/hardfile2 state=hard src=/testdir/testfile2"
- 在创建链接文件时,如果源文件不存在,或者链接文件与其他文件同名时,强制覆盖同名文件或者创建链接文件,参考上述 force 参数的解释。返回的 state 为 absent,表示源文件不存在。
ansible ansible-demo3 -m file -a "path=/testdir/linkfile3 state=link src=/testdir/sourcefile force=yes"
- 在创建文件或目录的时候指定属主,或者修改远程主机上的文件或目录的属主。
ansible ansible-demo3 -m file -a "path=/testdir/abc state=touch owner=ding"
ansible ansible-demo3 -m file -a "path=/testdir/abc owner=ding"
ansible ansible-demo3 -m file -a "path=/testdir/abc state=directory owner=ding"
- 在创建文件或目录的时候指定属组,或者修改远程主机上的文件或目录的属组。
ansible ansible-demo3 -m file -a "path=/testdir/abb state=touch group=ding"
ansible ansible-demo3 -m file -a "path=/testdir/abb group=ding"
ansible ansible-demo3 -m file -a "path=/testdir/abb state=directory group=ding"
- 在创建文件或目录的时候指定权限,或者修改远程主机上的文件或目录的权限。
ansible ansible-demo3 -m file -a "path=/testdir/abb state=touch mode=0644"
ansible ansible-demo3 -m file -a "path=/testdir/abb mode=0644"
ansible ansible-demo3 -m file -a "path=/testdir/binfile mode=4700"
ansible ansible-demo3 -m file -a "path=/testdir/abb state=directory mode=0644"
- 当操作远程主机中的目录时,同时递归的将目录中的文件的属主属组都设置为ding。
ansible ansible-demo3 -m file -a "path=/testdir/abd state=directory owner=ding group=ding recurse=yes"
playbook示例:
修改文件属主、属组及权限
- name: Change file ownership, group and permissions
file:
path: /etc/foo.conf
owner: foo
group: foo
mode: '0644'
- name: Give insecure permissions to an existing file
file:
path: /work
owner: root
group: root
mode: '1777'
- name: Create a symbolic link
file:
src: /file/to/link/to
dest: /path/to/symlink
owner: foo
group: foo
state: link
- name: Create two hard links
file:
src: '/tmp/{{ item.src }}'
dest: '{{ item.dest }}'
state: hard
loop:
- { src: x, dest: y }
- { src: z, dest: k }
- name: Touch a file, using symbolic modes to set the permissions (equivalent to 0644)
file:
path: /etc/foo.conf
state: touch
mode: u=rw,g=r,o=r
- name: Touch the same file, but add/remove some permissions
file:
path: /etc/foo.conf
state: touch
mode: u+rw,g-wx,o-rwx
- name: Touch again the same file, but dont change times this makes the task idempotent
file:
path: /etc/foo.conf
state: touch
mode: u+rw,g-wx,o-rwx
modification_time: preserve
access_time: preserve
- name: Update modification and access time of given file
file:
path: /etc/some_file
state: file
modification_time: now
access_time: now
- name: Set access time based on seconds from epoch value
file:
path: /etc/another_file
state: file
access_time: '{{ "%Y%m%d%H%M.%S" | strftime(stat_var.stat.atime) }}'
- name: Recursively change ownership of a directory
file:
path: /etc/foo
state: directory
recurse: yes
owner: foo
group: foo
删除文件
- name: Remove file (delete file)
file:
path: /etc/foo.txt
state: absent
创建目录
- name: Create a directory if it does not exist
file:
path: /etc/some_directory
state: directory
mode: '0755'
递归删除目录
- name: Recursively remove directory
file:
path: /etc/foo
state: absent
template
- 参考:https://docs.ansible.com/ansible/2.9/modules/template_module.html#template-module
- 功能: 将文件模板化到远程服务器。
常用参数:
- 文件权限,所属人,所属组:
owner
,group
,mode
playbook示例:
- name: Template a file to /etc/files.conf
template:
src: /mytemplates/foo.j2
dest: /etc/file.conf
owner: bin
group: wheel
mode: '0644'
- name: Template a file, using symbolic modes (equivalent to 0644)
template:
src: /mytemplates/foo.j2
dest: /etc/file.conf
owner: bin
group: wheel
mode: u=rw,g=r,o=r
backup: yes
archive
- 参考:https://docs.ansible.com/ansible/2.9/modules/archive_module.html#archive-module
- 功能:在远程服务器上,创建一个或多个文件压缩存档
常用参数:
format
: 压缩的格式,bz2
,gz
,tar
,xz
,zip
- 文件权限,所属人,所属组:
owner
,group
,mode
remove
: 添加到压缩文件后,删除源文件exclude_path
: 需要排除的文件或目录的绝对路径
playbook示例:
- name: Compress directory /path/to/foo/ into /path/to/foo.tgz
archive:
path: /path/to/foo
dest: /path/to/foo.tgz
- name: Compress regular file /path/to/foo into /path/to/foo.gz and remove it
archive:
path: /path/to/foo
remove: yes
- name: Create a zip archive of /path/to/foo
archive:
path: /path/to/foo
format: zip
- name: Create a bz2 archive of multiple files, rooted at /path
archive:
path:
- /path/to/foo
- /path/wong/foo
dest: /path/file.tar.bz2
format: bz2
- name: Create a bz2 archive of a globbed path, while excluding specific dirnames
archive:
path:
- /path/to/foo/*
dest: /path/file.tar.bz2
exclude_path:
- /path/to/foo/bar
- /path/to/foo/baz
format: bz2
- name: Create a bz2 archive of a globbed path, while excluding a glob of dirnames
archive:
path:
- /path/to/foo/*
dest: /path/file.tar.bz2
exclude_path:
- /path/to/foo/ba*
format: bz2
- name: Use gzip to compress a single archive (i.e don't archive it first with tar)
archive:
path: /path/to/foo/single.file
dest: /path/file.gz
format: gz
replace
- 参考:https://docs.ansible.com/ansible/2.9/modules/replace_module.html#replace-module
- 功能:根据我们指定的正则表达式替换文件中的字符串,文件中所有被匹配到的字符串都会被替换
常用参数:
- path参数 :必须参数,指定要操作的文件,2.3版本之前,只能使用 dest, destfile, name指定要操作的文件,2.4版本中,仍然可以使用这些参数名,这些参数名作为 path 参数的别名使用。
- regexp参数 : 必须参数,指定一个 python 正则表达式,文件中与正则匹配的字符串将会被替换。
- replace参数 : 指定最终要替换成的字符串。
- backup参数 :是否在修改文件之前对文件进行备份,最好设置为yes。
示例:
把 ansible-demo3 主机中的 /testdir/test 文件中的所有 ABC 替换成 abc,并备份
ansible ansible-demo3 -m replace -a 'path=/testdir/test regexp="ABC" replace=abc backup=yes'
playbook示例:
- name: shutdown | 注释/etc/fstab/swap 那一行
replace: dest=/etc/fstab regexp='(.*)swap(\s+)swap' replace='# \1swap\2swap'
when: swap.stdout == "0"
ignore_errors: yes
tags: swap
lineinfile
- 参考:https://docs.ansible.com/ansible/2.9/modules/lineinfile_module.html#lineinfile-module
- 功能:我们可以借助 lineinfile 模块,确保”某一行文本”存在于指定的文件中,或者确保从文件中删除指定的”文本”(即确保指定的文本不存在于文件中),还可以根据正则表达式,替换”某一行文本”
常用参数:
- path参数 :必须参数,指定要操作的文件。
- line参数 : 使用此参数指定文本内容。
- regexp参数 :使用正则表达式匹配对应的行,当替换文本时,如果有多行文本都能被匹配,则只有最后面被匹配到的那行文本才会被替换,当删除文本时,如果有多行文本都能被匹配,这么这些行都会被删除。
- state参数:当想要删除对应的文本时,需要将state参数的值设置为absent,absent为缺席之意,表示删除,state的默认值为present。
- backrefs参数:默认情况下,当根据正则替换文本时,即使regexp参数中的正则存在分组,在line参数中也不能对正则中的分组进行引用,除非将backrefs参数的值设置为yes。backrefs=yes表示开启后向引用,这样,line参数中就能对regexp参数中的分组进行后向引用了,这样说不太容易明白,可以参考后面的示例命令理解。backrefs=yes除了能够开启后向引用功能,还有另一个作用,默认情况下,当使用正则表达式替换对应行时,如果正则没有匹配到任何的行,那么line对应的内容会被插入到文本的末尾,不过,如果使用了backrefs=yes,情况就不一样了,当使用正则表达式替换对应行时,同时设置了backrefs=yes,那么当正则没有匹配到任何的行时,则不会对文件进行任何操作,相当于保持原文件不变。
- insertafter参数:借助insertafter参数可以将文本插入到“指定的行”之后,insertafter参数的值可以设置为EOF或者正则表达式,EOF为End Of File之意,表示插入到文档的末尾,默认情况下insertafter的值为EOF,如果将insertafter的值设置为正则表达式,表示将文本插入到匹配到正则的行之后,如果正则没有匹配到任何行,则插入到文件末尾,当使用backrefs参数时,此参数会被忽略。
- insertbefore参数:借助insertbefore参数可以将文本插入到“指定的行”之前,insertbefore参数的值可以设置为BOF或者正则表达式,BOF为Begin Of File之意,表示插入到文档的开头,如果将insertbefore的值设置为正则表达式,表示将文本插入到匹配到正则的行之前,如果正则没有匹配到任何行,则插入到文件末尾,当使用backrefs参数时,此参数会被忽略。
- backup参数:是否在修改文件之前对文件进行备份。
- create参数 :当要操作的文件并不存在时,是否创建对应的文件。
示例:
- 确保指定的”一行文本”存在于文件中,如果指定的文本本来就存在于文件中,则不做任何操作,如果不存在,默认在文件的末尾插入这行文本,如下命令表示确保 “test lineinfile” 这行文本存在于 /testdir/test 文件中。
[root@ansible-manager ~]# ansible ansible-demo3 -m lineinfile -a 'path=/testdir/test line="test lineinfile" '
- 根据正则表达式替换”某一行”,如果不止一行能够匹配正则,那么只有最后一个匹配正则的行才会被替换,被匹配行会被替换成 line 参数指定的内容,但是如果指定的表达式没有匹配到任何一行,那么 line 中的内容会被添加到文件的最后一行。
[root@ansible-manager ~]# ansible ansible-demo3 -m lineinfile -a 'path=/testdir/test regexp="^line" line="test lineinfile" '
- 正则表达式删除对应行,如果有多行都满足正则表达式,那么所有匹配的行都会被删除。
[root@ansible-manager ~]# ansible ansible-demo3 -m lineinfile -a 'path=/testdir/test regexp="^test" state=absent'
playbook示例:
# NOTE: Before 2.3, option 'dest', 'destfile' or 'name' was used instead of 'path'
- name: Ensure SELinux is set to enforcing mode
lineinfile:
path: /etc/selinux/config
regexp: '^SELINUX='
line: SELINUX=enforcing
- name: Make sure group wheel is not in the sudoers configuration
lineinfile:
path: /etc/sudoers
state: absent
regexp: '^%wheel'
- name: Replace a localhost entry with our own
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
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
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
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
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
lineinfile:
path: /etc/sudoers
state: present
regexp: '^%ADMIN ALL='
line: '%ADMIN ALL=(ALL) NOPASSWD: ALL'
validate: /usr/sbin/visudo -cf %s
blockinfile
- 参考:https://docs.ansible.com/ansible/2.9/modules/blockinfile_module.html#blockinfile-module
- 功能:可以帮助我们在指定的文件中插入,更新,或者删除 ”一段文本”,这段文本是被标记过的,也就是,我们在这段文本上做了记号,以便在以后的操作中可以通过”标记”找到这段文本,然后修改或者删除它
常用参数:
- path参数 :必须参数,指定要操作的文件。
- block参数 :此参数用于指定我们想要操作的那”一段文本”,此参数有一个别名叫”content”,使用content或block的作用是相同的。
- marker参数 :假如我们想要在指定文件中插入一段文本,ansible会自动为这段文本添加两个标记,一个开始标记,一个结束标记,默认情况下,开始标记为# BEGIN ANSIBLE MANAGED BLOCK,结束标记为# END ANSIBLE MANAGED BLOCK,我们可以使用marker参数自定义”标记”。比如,marker=#{mark}test ,这样设置以后,开始标记变成了# BEGIN test,结束标记变成了# END test,没错,{mark}会自动被替换成开始标记和结束标记中的BEGIN和END,我们也可以插入很多段文本,为不同的段落添加不同的标记,下次通过对应的标记即可找到对应的段落。
- state参数 : state参数有两个可选值,present与absent,默认情况下,我们会将指定的一段文本”插入”到文件中,如果对应的文件中已经存在对应标记的文本,默认会更新对应段落,在执行插入操作或更新操作时,state的值为present,默认值就是present,如果对应的文件中已经存在对应标记的文本并且将state的值设置为absent,则表示从文件中删除对应标记的段落。
- insertafter参数 :在插入一段文本时,默认会在文件的末尾插入文本,如果你想要将文本插入在某一行的后面,可以使用此参数指定对应的行,也可以使用正则表达式(python正则),表示将文本插入在符合正则表达式的行的后面。如果有多行文本都能够匹配对应的正则表达式,则以最后一个满足正则的行为准,此参数的值还可以设置为EOF,表示将文本插入到文档末尾。
- insertbefore参数 :在插入一段文本时,默认会在文件的末尾插入文本,如果你想要将文本插入在某一行的前面,可以使用此参数指定对应的行,也可以使用正则表达式(python正则),表示将文本插入在符合正则表达式的行的前面。如果有多行文本都能够匹配对应的正则表达式,则以最后一个满足正则的行为准,此参数的值还可以设置为BOF,表示将文本插入到文档开头。
- backup参数 :是否在修改文件之前对文件进行备份。
- create参数 :当要操作的文件并不存在时,是否创建对应的文件。
示例:
- 插入多行
- name: Insert block in rsyslog.conf
blockinfile:
path: /etc/rsyslog.conf
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
insertafter: "RULES"
block: |
auth.info;user.notice
auth.info;user.notice
- 从文件读取内容块插入另一个文件
- name: Insert block in /etc/bashrc
blockinfile:
block: "{{ lookup('file', '/tmp/bashrc.local') }}"
path: /etc/bashrc
backup: yes
- 优化limit参数
- name: optimization | limits.
blockinfile:
path: /etc/security/limits.d/99-limits.conf
backup: yes
create: yes
marker: "# {mark} ansible os-init"
block: |
root soft nofile 65535
root hard nofile 65535
root soft nproc 65535
root hard nproc 65535
root soft core unlimited
root hard core unlimited
* soft nofile 65535
* hard nofile 65535
* soft nproc 65535
* hard nproc 65535
* soft core unlimited
* hard core unlimited
tags: limits
playbook示例:
# Before Ansible 2.3, option 'dest' or 'name' was used instead of 'path'
- name: Insert/Update "Match User" configuration block in /etc/ssh/sshd_config
blockinfile:
path: /etc/ssh/sshd_config
block: |
Match User ansible-agent
PasswordAuthentication no
- name: Insert/Update eth0 configuration stanza in /etc/network/interfaces
(it might be better to copy files into /etc/network/interfaces.d/)
blockinfile:
path: /etc/network/interfaces
block: |
iface eth0 inet static
address 192.0.2.23
netmask 255.255.255.0
- name: Insert/Update configuration using a local file and validate it
blockinfile:
block: "{{ lookup('file', './local/sshd_config') }}"
dest: /etc/ssh/sshd_config
backup: yes
validate: /usr/sbin/sshd -T -f %s
- name: Insert/Update HTML surrounded by custom markers after <body> line
blockinfile:
path: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
insertafter: "<body>"
block: |
<h1>Welcome to {{ ansible_hostname }}</h1>
<p>Last updated on {{ ansible_date_time.iso8601 }}</p>
- name: Remove HTML as well as surrounding markers
blockinfile:
path: /var/www/html/index.html
marker: "<!-- {mark} ANSIBLE MANAGED BLOCK -->"
block: ""
- name: Add mappings to /etc/hosts
blockinfile:
path: /etc/hosts
block: |
{{ item.ip }} {{ item.name }}
marker: "# {mark} ANSIBLE MANAGED BLOCK {{ item.name }}"
loop:
- { name: host1, ip: 10.10.1.10 }
- { name: host2, ip: 10.10.1.11 }
- { name: host3, ip: 10.10.1.12 }
filesystem
- 参考:https://docs.ansible.com/ansible/2.9/modules/filesystem_module.html#filesystem-module
- 功能:创建一个文件系统
常用参数:
- fstype 文件系统类别:
btrfs ext2 ext3 ext4 ext4dev f2fs lvm ocfs2 reiserfs xfs vfat swap
示例:
- name: optimization | filesystem ext4.
filesystem: dev={{ disk_name }} fstype=ext4
tags: disk
ignore_errors: yes
playbook示例:
- name: Create a ext2 filesystem on /dev/sdb1
filesystem:
fstype: ext2
dev: /dev/sdb1
- name: Create a ext4 filesystem on /dev/sdb1 and check disk blocks
filesystem:
fstype: ext4
dev: /dev/sdb1
opts: -cc
mount
- 参考:https://docs.ansible.com/ansible/2.9/modules/mount_module.html#mount-module
- 功能:配置挂载点
常用参数:
-
state,挂载状态
mounted //挂载设备,并将配置写入/etc/fstab(常用) unmounted //卸载设备,不会清除/etc/fstab写入的配置(常用) present //开机挂载,仅将挂载配置写入/etc/fstab并不会真的挂载 absent //卸载设备,并清理/etc/fstab写入的配置
-
fstype 指定挂载文件的系统类型,必须指定,同上
filesystem
参数 - path 定义挂载到哪个目录,必须指定
- src 定义挂载内容
示例:
#挂载目录,并加入开机自动挂载
[root@m01 ~]# ansible web01 -m mount -a 'src=172.16.1.31:/data path=/code/wordpress fstype=nfs state=mounted'
#取消挂载,并取消开机自动挂载
[root@m01 ~]# ansible web01 -m mount -a 'src=172.16.1.31:/data path=/code/wordpress fstype=nfs state=absent'
- name: optimization | mout /home/application. 挂载目录,并加入开机自动挂载
mount:
path: /home/application
src: "{{ disk_name }}"
fstype: ext4
state: mounted
tags: disk
ignore_errors: yes
playbook示例:
# Before 2.3, option 'name' was used instead of 'path'
- name: Mount DVD read-only
mount:
path: /mnt/dvd
src: /dev/sr0
fstype: iso9660
opts: ro,noauto
state: present
- name: Mount up device by label
mount:
path: /srv/disk
src: LABEL=SOME_LABEL
fstype: ext4
state: present
- name: Mount up device by UUID
mount:
path: /home
src: UUID=b3e48f45-f933-4c8e-a700-22a159ec9077
fstype: xfs
opts: noatime
state: present
- name: Unmount a mounted volume
mount:
path: /tmp/mnt-pnt
state: unmounted
- name: Mount and bind a volume
mount:
path: /system/new_volume/boot
src: /boot
opts: bind
state: mounted
fstype: none
copy
- 参考:https://docs.ansible.com/ansible/2.9/modules/copy_module.html#copy-module
- 功能:将文件复制到远程主机
常用参数:
- src参数 :用于指定需要copy的文件或目录。
- dest参数 :用于指定文件将被拷贝到远程主机的哪个目录中,dest为必须参数。
- content参数 :当不使用src指定拷贝的文件时,可以使用content直接指定文件内容,src与content两个参数必有其一,否则会报错。
- force参数 : 当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否强制覆盖,可选值有yes和no,默认值为yes,表示覆盖,如果设置为no,则不会执行覆盖拷贝操作,远程主机中的文件保持不变。
- backup参数 : 当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否对远程主机的文件进行备份,可选值有yes和no,当设置为yes时,会先备份远程主机中的文件,然后再将ansible主机中的文件拷贝到远程主机。
- owner参数 : 指定文件拷贝到远程主机后的属主,但是远程主机上必须有对应的用户,否则会报错。
- group参数 : 指定文件拷贝到远程主机后的属组,但是远程主机上必须有对应的组,否则会报错。
- mode参数 : 指定文件拷贝到远程主机后的权限,如果你想将权限设置为”rw-r--r--“,则可以使用mode=0644表示,如果你想要在user对应的权限位上添加执行权限,则可以使用mode=u+x表示。
- remote_src: 表示src 是本机 还是 远程主机,默认是 remote_src=no 也就是,从本机拷贝到远程主机上; 若remote_src=yes ,则表示从远程主机 拷贝 到远程主机 本身
示例:
ansible host1 -m copy -a "src=/testdir/copytest dest=/testdir/"
拷贝多个文件:
- name: copy zoo.cfg,kafka.service,zookeeper
copy: "src={{ item.src }} dest={{ item.dest }} owner=root group=root mode=0775"
with_items:
- { src: "zoo.cfg", dest: "/home/application/apache-zookeeper-3.7.0-bin/conf/" }
- { src: "kafka.service", dest: "/etc/systemd/system/" }
- { src: "zookeeper", dest: "/etc/init.d/" }
tags: copy-config
playbook示例:
- name: Copy file with owner and permissions
copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: '0644'
- name: Copy file with owner and permission, using symbolic representation
copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u=rw,g=r,o=r
- name: Another symbolic mode example, adding some permissions and removing others
copy:
src: /srv/myfiles/foo.conf
dest: /etc/foo.conf
owner: foo
group: foo
mode: u+rw,g-wx,o-rwx
- name: Copy a new "ntp.conf file into place, backing up the original if it differs from the copied version
copy:
src: /mine/ntp.conf
dest: /etc/ntp.conf
owner: root
group: root
mode: '0644'
backup: yes
- name: Copy a new "sudoers" file into place, after passing validation with visudo
copy:
src: /mine/sudoers
dest: /etc/sudoers
validate: /usr/sbin/visudo -csf %s
- name: Copy a "sudoers" file on the remote machine for editing
copy:
src: /etc/sudoers
dest: /etc/sudoers.edit
remote_src: yes
validate: /usr/sbin/visudo -csf %s
- name: Copy using inline content
copy:
content: '# This file was moved to /etc/other.conf'
dest: /etc/mine.conf
- name: If follow=yes, /path/to/file will be overwritten by contents of foo.conf
copy:
src: /etc/foo.conf
dest: /path/to/link # link to /path/to/file
follow: yes
- name: If follow=no, /path/to/link will become a file and be overwritten by contents of foo.conf
copy:
src: /etc/foo.conf
dest: /path/to/link # link to /path/to/file
follow: no
fetch
- 参考:https://docs.ansible.com/ansible/2.9/modules/fetch_module.html#fetch-module
- 功能:用于从
远程主机
中拷贝文件到管理主机
,fetch
模块刚好和copy
模块的操作是相反的
常用参数:
- src参数: 远程机器上的文件或文件夹
- dest参数: 保存到本地的目录
- flat参数:默认为NO,如果flat为yes,不按照src的目录来创建目录。flat为no就创建和src一样的目录
示例:
拷贝远程文件到本地
[root@localhost ~]# ansible 192.168.233.167 -m fetch -a "src=/etc/hosts dest=/home/"
192.168.233.167 | CHANGED => {
"changed": true,
"checksum": "68991e742192b6cc45ad7b95eb88ea289658f65c",
"dest": "/home/192.168.233.167/etc/hosts",
"md5sum": "32d544b36aefb5a7f800e75cca57ce8b",
"remote_checksum": "68991e742192b6cc45ad7b95eb88ea289658f65c",
"remote_md5sum": null
}
在本地/home目录下会生成远程机器IP的文件夹,拉取的文件就在该目录下。并且保留目录结构
[root@localhost ~]# tree /home/192.168.233.167/
/home/192.168.233.167/
└── etc
└── hosts
playbook示例:
- name: Specifying a path directly
fetch:
src: /tmp/somefile
dest: /tmp/prefix-{{ inventory_hostname }}
flat: yes
- name: Specifying a destination path
fetch:
src: /tmp/uniquefile
dest: /tmp/special/
flat: yes
slurp
- 参考:https://docs.ansible.com/ansible/2.9/modules/slurp_module.html#slurp-module
- 功能: 模块用于拉取远端文件的 base64 码【Windows 目标也支持此模块】
常用参数:
- src参数: 远程机器上的文件【远程系统上要获取的文件。这必须是文件,而不是目录】
示例:
[root@sre ansible]# ansible -i hosts emqx -m slurp -a "src=/etc/passwd"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
172.16.10.80 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": false,
"content": "cm9vdDp4OjA6MDpyb290Oi9yb290Oi9iaW4vYmFzaApiaW46eDoxOjE6YmluOi9iaW46L3NiaW4vbm9sb2dpbgpkYWVtb246eDoyOjI6ZGFlbW9uOi9zYmluOi9zYmluL25vbG9naW4KYWRtOng6Mzo0OmFkbTovdmFyL2FkbTovc2Jpbi9ub2xvZ2luCmxwOng6NDo3OmxwOi92YXIvc3Bvb2wvbHBkOi9zYmluL25vbG9naW4Kc3luYzp4OjU6MDpzeW5jOi9zYmluOi9iaW4vc3luYwpzaHV0ZG93bjp4OjY6MDpzaHV0ZG93bjovc2Jpbjovc2Jpbi9zaHV0ZG93bgpoYWx0Ong6NzowOmhhbHQ6L3NiaW46L3NiaW4vaGFsdAptYWlsOng6ODoxMjptYWlsOi92YXIvc3Bvb2wvbWFpbDovc2Jpbi9ub2xvZ2luCm9wZXJhdG9yOng6MTE6MDpvcGVyYXRvcjovcm9vdDovc2Jpbi9ub2xvZ2luCmdhbWVzOng6MTI6MTAwOmdhbWVzOi91c3IvZ2FtZXM6L3NiaW4vbm9sb2dpbgpmdHA6eDoxNDo1MDpGVFAgVXNlcjovdmFyL2Z0cDovc2Jpbi9ub2xvZ2luCm5vYm9keTp4Ojk5Ojk5Ok5vYm9keTovOi9zYmluL25vbG9naW4Kc3lzdGVtZC1uZXR3b3JrOng6MTkyOjE5MjpzeXN0ZW1kIE5ldHdvcmsgTWFuYWdlbWVudDovOi9zYmluL25vbG9naW4KZGJ1czp4OjgxOjgxOlN5c3RlbSBtZXNzYWdlIGJ1czovOi9zYmluL25vbG9naW4KcG9sa2l0ZDp4Ojk5OTo5OTg6VXNlciBmb3IgcG9sa2l0ZDovOi9zYmluL25vbG9naW4Kc3NoZDp4Ojc0Ojc0OlByaXZpbGVnZS1zZXBhcmF0ZWQgU1NIOi92YXIvZW1wdHkvc3NoZDovc2Jpbi9ub2xvZ2luCnBvc3RmaXg6eDo4OTo4OTo6L3Zhci9zcG9vbC9wb3N0Zml4Oi9zYmluL25vbG9naW4KY2hyb255Ong6OTk4Ojk5Njo6L3Zhci9saWIvY2hyb255Oi9zYmluL25vbG9naW4KdHNzOng6NTk6NTk6QWNjb3VudCB1c2VkIGJ5IHRoZSB0cm91c2VycyBwYWNrYWdlIHRvIHNhbmRib3ggdGhlIHRjc2QgZGFlbW9uOi9kZXYvbnVsbDovc2Jpbi9ub2xvZ2luCm50cDp4OjM4OjM4OjovZXRjL250cDovc2Jpbi9ub2xvZ2luCnRzaW5neXVuOng6MTAwMDoxMDAwOjovaG9tZS90c2luZ3l1bjovYmluL2Jhc2gKbXlzcWw6eDoxMDAxOjEwMDE6Oi9ob21lL215c3FsOi9zYmluL25vbG9naW4KY2xpY2tob3VzZTp4Ojk5Nzo5OTQ6Oi9ub25leGlzdGVudDovYmluL2ZhbHNlCmNsaWNraG91c2UtYnJpZGdlOng6OTk2Ojk5Mzo6L25vbmV4aXN0ZW50Oi9iaW4vZmFsc2UKemFiYml4Ong6OTk1Ojk5MjpaYWJiaXggTW9uaXRvcmluZyBTeXN0ZW06L3Zhci9saWIvemFiYml4Oi9zYmluL25vbG9naW4KCmVtcXg6eDo5OTQ6OTkxOmVtcXg6L3Zhci9saWIvZW1xeDovYmluL2Jhc2gK",
"encoding": "base64",
"source": "/etc/passwd"
}
playbook示例:
- name: Find out what the remote machine's mounts are
slurp:
src: /proc/mounts
register: mounts
- debug:
msg: "{{ mounts['content'] | b64decode }}"
unarchive
- 参考:https://docs.ansible.com/ansible/2.9/modules/unarchive_module.html#unarchive-module
- 功能:将压缩包解压缩
常用参数:
- remote_src: 默认为no,设置为
yes
表示归档文件已经在远程系统上,而不是 Ansible 本机上 - src:如果copy为yes,则需要指定压缩文件的源路径
- dest:远程主机上的一个路径,即文件解压的路径
- group:解压后的目录或文件的属组
- list_files:如果为yes,则会列出压缩包里的文件,默认为no,2.0版本新增的选项
- creates:如果指定的绝对路径(文件或目录)已经存在,则不执行此步骤,则解压指令不执行
- mode:解压后文件的权限
- owner:解压后文件或目录的属主
- exclude:列出要从存档操作中排除的目录和文件条目。
示例: 解压ansible 上/kafka_2.13-2.7.0.tgz 压缩包到 目标主机的/root 目录下
[root@sre ansible]# ansible -i hosts emqx -m unarchive -a "src=/root/kafka_2.13-2.7.0.tgz dest=/root mode=0755"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
172.16.10.80 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/root",
"extract_results": {
"cmd": [
"/usr/bin/gtar",
"--extract",
"-C",
"/root",
"-z",
"-f",
"/root/.ansible/tmp/ansible-tmp-1653304231.35-24219-41047213765295/source"
],
"err": "",
"out": "",
"rc": 0
},
"gid": 0,
"group": "root",
"handler": "TgzArchive",
"mode": "0550",
"owner": "root",
"size": 4096,
"src": "/root/.ansible/tmp/ansible-tmp-1653304231.35-24219-41047213765295/source",
"state": "directory",
"uid": 0
}
示例: 解压远程主机上 /root/kafka_2.13-2.7.0.tgz 压缩包到 目标主机的/tmp目录下
[root@sre ansible]# ansible -i hosts emqx -m unarchive -a "src=/root/kafka_2.13-2.7.0.tgz dest=/tmp remote_src=yes mode=0755"
[WARNING]: Invalid characters were found in group names but not replaced, use -vvvv to see details
172.16.10.80 | CHANGED => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python"
},
"changed": true,
"dest": "/tmp",
"extract_results": {
"cmd": [
"/usr/bin/gtar",
"--extract",
"-C",
"/tmp",
"-z",
"-f",
"/root/kafka_2.13-2.7.0.tgz"
],
"err": "",
"out": "",
"rc": 0
},
"gid": 0,
"group": "root",
"handler": "TgzArchive",
"mode": "01777",
"owner": "root",
"size": 4096,
"src": "/root/kafka_2.13-2.7.0.tgz",
"state": "directory",
"uid": 0
}
playbook示例:
- name: Unarchive a file that is already on the remote machine
unarchive:
src: /tmp/foo.zip
dest: /usr/local/bin
remote_src: yes
#在线下载压缩包并解压
- name: Unarchive a file that needs to be downloaded (added in 2.0)
unarchive:
src: https://example.com/example.zip
dest: /usr/local/bin
remote_src: yes
#解压层级
- name: Extract archive
unarchive:
src: file.tar.gz
dest: /foo/bar
extra_opts: [--strip-components=1]
#排除目录
---
- hosts: 10.39.140.248
gather_facts: no
tasks:
- name: Extract zip into /tmp
unarchive:
src: /root/pms-rd-server.zip
dest: /tmp
exclude: "pms-rd-server/config/*"
get_url
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
synchronize
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
yum
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
package
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
gem
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
npm
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
pip
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
easy_install
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
rpm_key
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
user
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
group
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
import_tasks
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
include_tasks
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
include_vars
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
mysql_user
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
mysql_db
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
mysql_replication
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
postgresql_user
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
postgresql_db
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
service
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
systemd
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
supervisorctl
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
wait_for
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
ping
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
hostname
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
cron
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
debug
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
fail
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
selinux
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
set_fact
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
setup
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
sysctl
- 参考:https://docs.ansible.com/ansible/2.9/modules/file_module.html#file-module
- 功能:
常用参数:
示例:
playbook示例:
authorized_key
-
参考:https://docs.ansible.com/ansible/2.9/modules/authorized_key_module.html
-
功能: 为特定用户帐户添加或删除SSH授权密钥。
示例:
- name: Set authorized key taken from file
authorized_key:
user: charlie
state: present
key: "{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
- name: Set authorized keys taken from url
authorized_key:
user: charlie
state: present
key: https://github.com/charlie.keys
- name: Set authorized key in alternate location
authorized_key:
user: charlie
state: present
key: "{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
path: /etc/ssh/authorized_keys/charlie
manage_dir: False
- name: Set up multiple authorized keys
authorized_key:
user: deploy
state: present
key: '{{ item }}'
with_file:
- public_keys/doe-jane
- public_keys/doe-john
- name: Set authorized key defining key options
authorized_key:
user: charlie
state: present
key: "{{ lookup('file', '/home/charlie/.ssh/id_rsa.pub') }}"
key_options: 'no-port-forwarding,from="10.0.1.1"'
- name: Set authorized key without validating the TLS/SSL certificates
authorized_key:
user: charlie
state: present
key: https://github.com/user.keys
validate_certs: False
- name: Set authorized key, removing all the authorized keys already set
authorized_key:
user: root
key: '{{ item }}'
state: present
exclusive: True
with_file:
- public_keys/doe-jane
- name: Set authorized key for user ubuntu copying it from current user
authorized_key:
user: ubuntu
state: present
key: "{{ lookup('file', lookup('env','HOME') + '/.ssh/id_rsa.pub') }}"
免密示例:
- name: gen ssh_keypair
openssh_keypair:
path: /root/.ssh/id_rsa
size: 2048
type: rsa
connection: local
run_once: true
- name: ssh-keyscan command
known_hosts:
name: "{{ ansible_host }}"
key: "{{ lookup('pipe', 'ssh-keyscan -t ecdsa-sha2-nistp256 {{ ansible_host }}') }}"
connection: local
- name: install ssh key
authorized_key:
user: root
key: "{{ lookup('file', '/root/.ssh/id_rsa.pub') }}"
state: present