自动化运维工具Ansible

时间:2024-03-18 11:32:12

目录

一.Ansible基本内容

1.定义

2.特点与优势

优势:

(1)轻便性:无需在被控制服务器上安装客户端,Ansible基于ssh协议

(2)幂等性:大部分模块有幂等性,即如果输入systemctl stop firewalld当发现要停止的服务已经停止就不会做任何操作了,多次停止不会改变结果。systemtl restart是非幂等的。 

(3)判断性:大部分模块在执行时都会判断目标节点是否要执行任务,所有重复执行某个任务大部分时间不会产生副作用

(4)简介性:一个窗口即可管理所有需要控制的机器,无需开启多个窗口

特点:

(1)部署简单,只需要主控端部署Ansible环境,被控端无需做任何操作;

(2)默认使用SSH协议设备进行管理;

(3)主从集中化管理;

(4)配置简单、功能强大、扩展性强;

(5)支持API及自定义模块,可以通过Python轻松扩展

(6)通过playbooks来定制强大的配置、状态管理

(7)对云平台和大数据都有很好的支持

4.Anisible核心程序

(1)HostInventory:记录由Ansible管理的主机信息,端口,ip,密码等

(2)playbooks:'剧本'YAML格式文件,多任务定义在一个文件中,定义主机需要调用那些模块完成功能

(3)core modeules:核心模块主要操作通过调用核心模块来完成管理任务

(4)customodules:自定义模块,完成核心模块无法完成的模块,支持多种语言编写

(5)connectiontugins:连接插件,ansible和主机通信使用(ssh协议)

5.Ansible工作原理 

(1)加载自己的配置文件,默认/etc/ansible/ansible.cfg

(2)查找对应的主机的配置文件,找到要执行的主机或组/etc/ansible/hosts文件

(3)加载自己对应的模块文件,如command、yum、ping、

(4)通过ansible将模块命令生成对应的临时py文件(类似python脚本),并将该文件传输至被管理端

(5)传输到在被控制端的对应用户的家目录下.ansible/tmp/xxx/xxx.py

(6)被控制端给传输过来的py文件加执行权限

(7)执行并返回结果,执行完成后删除py文件并sleep 0退出

6.选项

 二.Ansible自动化运维工具安装

1.yum安装

2.编译安装——不建议

 3.Git安装——不建议

三、相关文件

1.Ansible主配置文件

 2.inventory主机清单文件

 3.示例

3.1修改ssh配置——免密

3.2修改ansible配置——免密

4.Ansible相关工具

5.Ansible选项

6.执行返回结果 

 7.Ansible-doc

8. Ansible-console

四、模块

1.Command 模块

2.Shell 模块

3.Script 模块

4.Copy 模块

5.Get_url 模块

5.1md5sum

 5.2修改名称 

6.Fetch 模块

7.File 模块

7.1新建空文件 

7.2新建目录

7.3删除文件

7.4递归修改目录属性

8.State 模块

9.Unarchive 模块

9.1把本机的压缩包解压到远端主机 

9.2把远端主机的压缩包解压到指定目录 

10.Archive 模块

11.Hostname 模块

12.Cron 模块

12.1生成远端主机的定时计划

12.2disabled——不启用

12.3删除计划任务

13.Yum和Apt 模块

14.yum_repository 模块

15.Service 模块

16.mount 挂载和卸载模块

17.User 模块

18.Group 模块

19.reboot 模块

20.Lineinfile 模块

21.replace 模块

22.setup 模块

22.1主机相关信息

22.2系统总内存

22.3详细显示内存情况

22.4显示可用系统内存

22.5系统所属信息

22.6当前系统版本

22.7当前系统详细版本

22.8显示cpu个数(只显示总的个数)

22.9仅显示ipv4的信息

22.10版本信息

22.11在线时长

22.12内核参数信息

22.13环境变量

22.14setup模块总结——常用信息


一.Ansible基本内容

1.定义

Ansible是基于模块工作的,只是提供了一种运行框架,本身没有完成任务的能力,真正操作的是Anisble的模块。每个模块都是独立的、实现了批量系统配置、批量程序部署、批量运行命令等功能。

2.特点与优势
优势:
(1)轻便性:无需在被控制服务器上安装客户端,Ansible基于ssh协议
(2)幂等性:大部分模块有幂等性,即如果输入systemctl stop firewalld当发现要停止的服务已经停止就不会做任何操作了,多次停止不会改变结果。systemtl restart是非幂等的。 
(3)判断性:大部分模块在执行时都会判断目标节点是否要执行任务,所有重复执行某个任务大部分时间不会产生副作用
(4)简介性:一个窗口即可管理所有需要控制的机器,无需开启多个窗口
特点:
(1)部署简单,只需要主控端部署Ansible环境,被控端无需做任何操作;
(2)默认使用SSH协议设备进行管理;
(3)主从集中化管理;
(4)配置简单、功能强大、扩展性强;
(5)支持API及自定义模块,可以通过Python轻松扩展
(6)通过playbooks来定制强大的配置、状态管理
(7)对云平台和大数据都有很好的支持
4.Anisible核心程序
(1)HostInventory:记录由Ansible管理的主机信息,端口,ip,密码等
(2)playbooks:'剧本'YAML格式文件,多任务定义在一个文件中,定义主机需要调用那些模块完成功能
(3)core modeules:核心模块主要操作通过调用核心模块来完成管理任务
(4)customodules:自定义模块,完成核心模块无法完成的模块,支持多种语言编写
(5)connectiontugins:连接插件,ansible和主机通信使用(ssh协议)

5.Ansible工作原理 

 

(1)加载自己的配置文件,默认/etc/ansible/ansible.cfg
(2)查找对应的主机的配置文件,找到要执行的主机或组/etc/ansible/hosts文件
(3)加载自己对应的模块文件,如command、yum、ping、
(4)通过ansible将模块命令生成对应的临时py文件(类似python脚本),并将该文件传输至被管理端
(5)传输到在被控制端的对应用户的家目录下.ansible/tmp/xxx/xxx.py
(6)被控制端给传输过来的py文件加执行权限
(7)执行并返回结果,执行完成后删除py文件并sleep 0退出
6.选项
--version #显示版本
-m module #指定模块,默认为command
-v #详细过程 -vv -vvv更详细
--list-hosts #显示主机列表,可简写 --list
-C, --check #检查,并不执行
-T, --timeout=TIMEOUT #执行命令的超时时间,默认10s
-k, --ask-pass #提示输入ssh连接密码,默认Key验证 
-u, --user=REMOTE_USER #执行远程执行的用户,默认root
-b, --become #代替旧版的sudo 切换
--become-user=USERNAME #指定sudo的runas用户,默认为root
vim /etc/sudoers 用户权限

-K, --ask-become-pass

#提示输入sudo时的口令
-f FORKS, --forks FORKS #指定并发同时执行ansible任务的主机

 二.Ansible自动化运维工具安装

1.yum安装

[root@localhost ~]#yum install epel-release.noarch -y
[root@localhost ~]#yum install ansible -y
[root@localhost ~]#ansible --version
ansible 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]

2.编译安装——不建议

yum -y install python-jinja2 PyYAML python-paramiko python-babel python-crypto
wget https://releases.ansible.com/ansible/ansible-2.9.27.tar.gz
tar xf ansible-1.5.4.tar.gz
cd ansible-2.9.27
python setup.py build
python setup.py install
mkdir /etc/ansible
cp -r examples/* /etc/ansible

 3.Git安装——不建议

yum install git
git clone git://github.com/ansible/ansible.git --recursive
cd ./ansible
source ./hacking/env-setup

三、相关文件

  • /etc/ansible/ansible.cfg 主配置文件,配置ansible工作特性,也可以在项目的目录中创建此文件,当前目录下如果也有ansible.cfg,则此文件优先生效,建议每个项目目录下,创建独有的ansible.cfg文 件
  • /etc/ansible/hosts 主机清单
  • /etc/ansible/roles/ 存放角色的目录

1.Ansible主配置文件

Ansible 的配置文件可以放在多个不同地方,优先级从高到低顺序如下

ANSIBLE_CONFIG
#环境变量,注意此项用 ansible --version 看不到,但可以生效
./ansible.cfg
#当前目录下的ansible.cfg
~/.ansible.cfg
#当前用户家目录下的.ansible.cfg
/etc/ansible/ansible.cfg
#系统默认配置文件

 Ansible 的默认配置文件 /etc/ansible/ansible.cfg ,其中大部分的配置内容无需进行修改

[defaults]
#inventory     = /etc/ansible/hosts 	#主机列表配置文件
#library = /usr/share/my_modules/ 		#库文件存放目录
#remote_tmp = $HOME/.ansible/tmp 		#临时py命令文件存放在远程主机目录
#local_tmp     = $HOME/.ansible/tmp 	#本机的临时命令执行目录
#forks         = 5   					#默认并发数
#sudo_user     = root 					#默认sudo 用户
#ask_sudo_pass = True 					#每次执行ansible命令是否询问ssh密码
#ask_pass     = True   
#remote_port   = 22
#host_key_checking = False     			#检查对应服务器的host_key,建议取消此行注释,实现第一次连接自动信任目标主机
#log_path=/var/log/ansible.log 			#日志文件,建议启用
#module_name = command   		、mod		#默认模块,可以修改为shell模块
[privilege_escalation] 					#普通用户提权配置
#become=True
#become_method=sudo
#become_user=root
#become_ask_pass=False

 2.inventory主机清单文件

ansible的主要功用在于批量主机操作,为了便捷地使用其中的部分主机,可以在inventory 主机清单文件中将其分组组织

 官方文档: https://docs.ansible.com/ansible/latest/user_guide/intro_inventory.html  

默认的inventory file位置在 /etc/ansible/hosts 

ansible_ssh_host 
#将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.
ansible_ssh_port 
#ssh端口号.如果不是默认的端口号,通过此变量设置.这种可以使用 ip:端口
192.168.1.100:2222
 
ansible_ssh_user 
#默认的 ssh 用户名
 
ansible_ssh_pass 
#ssh 密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)
 
ansible_sudo_pass 
#sudo 密码(这种方式并不安全,我们强烈建议使用 --ask-sudo-pass)
 
ansible_sudo_exe (new in version 1.8)
#sudo 命令路径(适用于1.8及以上版本)
 
ansible_connection 
#与主机的连接类型.比如:local, ssh 或者 paramiko. Ansible 1.2 以前默认使用 paramiko.1.2 以后默认使用 'smart','smart' 方式会根据是否支持 ControlPersist, 来判断'ssh' 方式是否可行.
 
ansible_ssh_private_key_file
#ssh 使用的私钥文件.适用于有多个密钥,而你不想使用 SSH 代理的情况.
 
ansible_shell_type 
#目标系统的shell类型.默认情况下,命令的执行使用 'sh' 语法,可设置为'csh' 或 'fish'.
 
ansible_python_interpreter 
#目标主机的 python 路径.适用于的情况: 系统中有多个 Python, 或者命令路径不是"/usr/bin/python",比如 \*BSD, 或者 /usr/bin/python 不是 2.X 版本的Python.之所以不使用 "/usr/bin/env" 机制,因为这要求远程用户的路径设置正确,且要求 "python" 可执行程序名不可为 python以外的名字(实际有可能名为python26).与ansible_python_interpreter 的工作方式相同,可设定如 ruby 或 perl 的路径....

 3.示例

[root@localhost ~]#vim /etc/ansible/hosts
[root@localhost ~]#sed -n '45,51p' /etc/ansible/hosts 
[web]
192.168.241.22
192.168.241.23
 
 
[all]
192.168.241.[22:26]
[root@localhost ~]#ansible 192.168.91.105 -m ping
#可以指定   m代表使用模块  ping代表ping模块 命令探测下,需要输入 yes 或no

m代表使用模块  ping代表ping模块 命令探测下,需要输入 yes 或no 

 

[root@localhost ~]#ansible web -m ping -k
#-k 输入密码 只有一次机会,如果密码不同无法一起管理,建议ssh免密
SSH password: 
192.168.241.23 | FAILED! => {
    "msg": "Using a SSH password instead of a key is not possible because Host Key checking is enabled and sshpass does not support this.  Please add this host's fingerprint to your known_hosts file to manage this host."
}
192.168.241.22 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
3.1修改ssh配置——免密
[root@localhost ~]#vim /etc/ssh/ssh_config 
[root@localhost ~]#sed -n '35p' /etc/ssh/ssh_config 
   StrictHostKeyChecking ask---->no
[root@localhost ~]#ansible web -m ping -k 
SSH password: 
192.168.241.22 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.241.23 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]#ansible web -m ping
192.168.241.23 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.241.22 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]#ssh-keygen 
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:asSeknDK6vVK7Xq2iCLXjPiCRsAd9d4n7TTSw+v5f+U root@localhost.localdomain
The key's randomart image is:
+---[RSA 2048]----+
|    ..           |
|   .  .          |
|. . .  .         |
|.. . .. . +      |
|. . . o.S+ O     |
| o +.+ o  * +   .|
|o.o*o.=    o   ..|
|*o* *=    . .   E|
|**.+=+.    o.....|
+----[SHA256]-----+
[root@localhost ~]#ssh-copy-id 192.168.241.22
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.241.22's password: 
 
Number of key(s) added: 1
 
Now try logging into the machine, with:   "ssh '192.168.241.22'"
and check to make sure that only the key(s) you wanted were added.
 
[root@localhost ~]#ssh-copy-id 192.168.241.23
/usr/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/root/.ssh/id_rsa.pub"
/usr/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/usr/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@192.168.241.23's password: 
Number of key(s) added: 1
Now try logging into the machine, with:   "ssh '192.168.241.23'"
and check to make sure that only the key(s) you wanted were added.
3.2修改ansible配置——免密
[root@localhost ~]#vim /etc/ansible/ansible.cfg 
[root@localhost ~]#sed -n '71p' /etc/ansible/ansible.cfg 
host_key_checking = False
[root@localhost ~]#echo " " > .ssh/known_hosts 
[root@localhost ~]#cat .ssh/known_hosts 
 
[root@localhost ~]#ansible web -m ping -k
SSH password: 
192.168.241.23 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.241.22 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]#ansible web -m ping
192.168.241.23 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.241.22 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
[root@localhost ~]#cat .ssh/known_hosts 
 
192.168.241.22 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFJ0yF0PqvJxGhvSbYYG8cruLD23vFivSgMr3ozmortbWK+P3BoYjpSdhEB3xv/2s1mEzol/aWLd+/qNgdbqTmc=
192.168.241.23 ecdsa-sha2-nistp256 AAAAE2VjZHNhLXNoYTItbmlzdHAyNTYAAAAIbmlzdHAyNTYAAABBBFNCvnWTWT+7UYGSPzChIOIEvYJk8+OtYDdoiN6DEc222O4Pm0AteuzOGjsgc1La170AhxLWO1DGKDaFCynAwTs=

4.Ansible相关工具

  • /usr/bin/ansible 主程序,临时命令执行工具
  • /usr/bin/ansible-doc 查看配置文档,模块功能查看工具,相当于man ansible-doc -l |grep 关键字 具体模块名字
  • /usr/bin/ansible-playbook 定制自动化任务,编排剧本工具,相当于脚本
  • /usr/bin/ansible-pull 远程执行命令的工具
  • /usr/bin/ansible-vault 文件加密工具
  • /usr/bin/ansible-console 基于Console界面与用户交互的执行工具
  • /usr/bin/ansible-galaxy 下载/上传优秀代码或Roles模块的官网平台

5.Ansible选项

执行临时任务一次性任务

ansible <host-pattern> [-m module_name] [-a args]
命令     主机或者清单中的组 -m 指定模块      -a  执行的任务
选项 含义
--version 显示版本
-m module 指定模块,默认为command
-v 详细过程 -vv -vvv更详细
--list-hosts 显示主机列表,可简写 --list
-C, --check 检查,并不执行
-T, --timeout=TIMEOUT 执行命令的超时时间,默认10s
-k, --ask-pass 提示输入ssh连接密码,默认Key验证 
-u, --user=REMOTE_USER 执行远程执行的用户,默认root
-b, --become 代替旧版的sudo 切换
--become-user=USERNAME 指定sudo的runas用户,默认为root  vim /etc/sudoers 用户权限
-K, --ask-become-pass 提示输入sudo时的口令
-f FORKS, --forks FORKS 指定并发同时执行ansible任务的主机数
[root@localhost ~]#ansible --version
ansible 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]
主机列表   支持通配符
ansible all -m ping
#执行一次计划任务  对all组内的主机执行ping命令
ansible "*" -m ping
#执行一次计划任务  对所有主机进行ping命令
ansible 192.168.241.* -m ping
#对192.168.241网段的主机执行ping
ansible "srvs" -m ping
#指定srvs组的主机执行ping
ansible "192.168.241.22 192.168.241.23" -m ping
#执行特定主机执行ping
 
[root@localhost ~]#ansible web --list
  hosts (2):
    192.168.241.22
    192.168.241.23
[root@localhost ~]#ansible all --list
  hosts (5):
    192.168.241.22
    192.168.241.23
    192.168.241.24
    192.168.241.25
    192.168.241.26
 
#或
[root@localhost ~]#ansible 'web:all' --list-hosts
  hosts (5):
    192.168.241.22
    192.168.241.23
    192.168.241.24
    192.168.241.25
    192.168.241.26
#并且
[root@localhost ~]#ansible 'web:&all' --list-hosts
  hosts (2):
    192.168.241.22
    192.168.241.23
#逻辑非
[root@localhost ~]#ansible 'all:!web' --list-hosts
  hosts (3):
    192.168.241.24
    192.168.241.25
    192.168.241.26
#正则表达式
[root@localhost ~]#ansible "~(w|a).*" -m ping -k
SSH password: 
192.168.241.23 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.241.22 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.241.24 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.241.25 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.241.25 port 22: No route to host", 
    "unreachable": true
}
192.168.241.26 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.241.26 port 22: No route to host", 
    "unreachable": true
}
[root@localhost ~]#ansible web -a "sleep 3" -f1
192.168.241.22 | CHANGED | rc=0 >>
 
192.168.241.23 | CHANGED | rc=0 >>
 
[root@localhost ~]#ansible web -a "sleep 3" -f4
192.168.241.22 | CHANGED | rc=0 >>
 
192.168.241.23 | CHANGED | rc=0 >>

 

 -f1 一台一台的执行操作 -f并行执行

[root@localhost ~]#ansible web -a "sleep 300" -f1
192.168.241.22 | CHANGED | rc=0 >>
 
192.168.241.23 | CHANGED | rc=0 >>
[root@node2 ~]#ls -a
.                .bash_profile  Desktop               .local    Templates
..               .bashrc        Documents             Music     Videos
anaconda-ks.cfg  .cache         Downloads             Pictures  .viminfo
.ansible         .config        .esd_auth             Public    .Xauthority
.bash_history    .cshrc         .ICEauthority         .ssh
.bash_logout     .dbus          initial-setup-ks.cfg  .tcshrc
[root@node2 ~]#tree .ansible/
.ansible/
└── tmp
    └── ansible-tmp-1710222280.45-5420-206640600379694
        └── AnsiballZ_command.py
 
2 directories, 1 file
[root@node2 ~]#tree .ansible/
.ansible/
└── tmp
 
1 directory, 0 files

 如果执行休眠300秒的话,远端主机会有一个py的脚本存在,执行结束后,脚本就自动删除脚本

[root@localhost ~]#ansible web -a "touch /opt/cxk" -v
Using /etc/ansible/ansible.cfg as config file
[WARNING]: Consider using the file module with state=touch rather than running
'touch'.  If you need to use command because file is insufficient you can add
'warn: false' to this command task or set 'command_warnings=False' in
ansible.cfg to get rid of this message.
192.168.241.23 | CHANGED | rc=0 >>
 
192.168.241.22 | CHANGED | rc=0 >>
[root@node2 ~]#ls /opt
apache-tomcat-9.0.16.tar.gz  cxk  jdk-8u291-linux-x64.tar.gz
[root@node3 ~]#ls /opt
apache-tomcat-9.0.16.tar.gz  cxk  jdk-8u291-linux-x64.tar.gz

Ansible命令执行过程

  1. 加载自己的配置文件,默认/etc/ansible/ansible.cfg
  2. 加载自己对应的模块文件,如:command
  3. 通过ansible将模块或命令生成对应的临时py文件,并将该文件传输至远程服务器的对应执行用户($HOME/.ansible/tmp/ansible-tmp-数字/XXX.PY文件)
  4. 给文件+x执行
  5. 执行并返回结果
  6. 删除临时py文件,退出

6.执行返回结果 

vim /etc/ansible/ansible.cfg 
[colors]
#highlight = white
#verbose = blue
#warn = bright purple
#error = red
#debug = dark gray
#deprecate = purple
#skip = cyan
#unreachable = red
#ok = green
#changed = yellow
#diff_add = green
  • 绿色:执行成功并且不需要做改变的操作
  • 黄色:执行成功并且对目标主机做变更
  • 红色:执行失败

 7.Ansible-doc

[root@localhost ~]#ansible-doc
#可以查看所有支持的模块
usage: ansible-doc [-h] [--version] [-v] [-M MODULE_PATH]
                   [--playbook-dir BASEDIR]
                   [-t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}]
                   [-j] [-F | -l | -s | --metadata-dump]
                   [plugin [plugin ...]]
 
plugin documentation tool
 
positional arguments:
  plugin                Plugin
 
optional arguments:
  --metadata-dump       **For internal testing only** Dump json metadata for
                        all plugins.
  --playbook-dir BASEDIR
                        Since this tool does not use playbooks, use this as a
                        substitute playbook directory.This sets the relative
                        path for many features including roles/ group_vars/
                        etc.
  --version             show program's version number, config file location,
                        configured module search path, module location,
                        executable location and exit
  -F, --list_files      Show plugin names and their source files without
                        summaries (implies --list)
  -M MODULE_PATH, --module-path MODULE_PATH
                        prepend colon-separated path(s) to module library (def
                        ault=~/.ansible/plugins/modules:/usr/share/ansible/plu
                        gins/modules)
  -h, --help            show this help message and exit
  -j, --json            Change output into json format.
  -l, --list            List available plugins
  -s, --snippet         Show playbook snippet for specified plugin(s)
  -t {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}, --type {become,cache,callback,cliconf,connection,httpapi,inventory,lookup,netconf,shell,module,strategy,vars}
                        Choose which plugin type (defaults to "module").
                        Available plugin types are : ('become', 'cache',
                        'callback', 'cliconf', 'connection', 'httpapi',
                        'inventory', 'lookup', 'netconf', 'shell', 'module',
                        'strategy', 'vars')
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)
See man pages for Ansible CLI options or website for tutorials
https://docs.ansible.com
ERROR! Incorrect options passed
[root@localhost ~]#ansible-doc -l|wc -l
3387
#共有3387个模块
[root@localhost ~]#ansible-doc ping
#可以查看指定模块
[root@localhost ~]#ansible-doc -s ping
#查看简单模块
- name: Try to connect to host, verify a usable python and return `pong' on s
  ping:
      data:                  # Data to return for the `ping' return value. If
                               this parameter is
                               set to `crash',
                               the module will
                               cause an
                               exception.
[root@localhost ~]#ansible-doc file
#幂等性,安全性,自己写脚本

8. Ansible-console

此工具可交互执行命令,支持tab,ansible 2.0+新增

执行用户@当前操作的主机组 (当前组的主机数量)[f:并发数]$
命令 含义
forks n(forks 10) 设置并发数
cd 主机组(cd web) 切换组
list 列出当前组主机列表
?或help 列出所有的内置命令
[root@localhost ~]#ansible-console
Welcome to the ansible console.
Type help or ? to list commands.
 
root@all (5)[f:5]$ list
192.168.241.22
192.168.241.23
192.168.241.24
192.168.241.25
192.168.241.26
root@all (5)[f:5]$ cd web
root@web (2)[f:5]$ list
192.168.241.22
192.168.241.23
root@web (2)[f:5]$ ping
192.168.241.22 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.241.23 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
root@web (2)[f:5]$ 

四、模块

2015年底270多个模块,2016年达到540个,2018年01月12日有1378个模块,2018年07月15日1852个模块,2019年05月25日(ansible 2.7.10)时2080个模块,2020年03月02日有3387个模块虽然模块众多,但最常用的模块也就2,30个而已,针对特定业务只用10几个模块

常用模块帮助文档参考:

https://docs.ansible.com/ansible/2.9/modules/modules_by_category.html
https://docs.ansible.com/ansible/2.9/modules/list_of_all_modules.html
https://docs.ansible.com/ansible/latest/modules/list_of_all_modules.html
https://docs.ansible.com/ansible/latest/modules/modules_by_category.html

1.Command 模块

功能:在远程主机执行命令,此为默认模块,可忽略 -m 选项

注意:此命令不支持 $VARNAME < > | ; & 等,可能用shell模块实现

注意:此模块不具有幂等性

[root@localhost ~]#ansible web -m command -a "cp /etc/passwd /opt"
192.168.241.22 | CHANGED | rc=0 >>
 
192.168.241.23 | CHANGED | rc=0 >>
[root@node2 ~]#ls /opt
passwd
[root@localhost ~]#ansible web -a "echo hello world > /opt/hello"
192.168.241.22 | CHANGED | rc=0 >>
hello world > /opt/hello
192.168.241.23 | CHANGED | rc=0 >>
hello world > /opt/hello

Command模块不支持重定向;如果想支持重定向可以使用shell模块

2.Shell 模块

功能:和command相似,用shell执行命令,支持各种符号,比如:*,$, >

 注意:此模块不具有幂等性

[root@localhost ~]#ansible web -m shell -a "echo hello world > /opt/hello"
192.168.241.23 | CHANGED | rc=0 >>
 
192.168.241.22 | CHANGED | rc=0 >>
[root@node2 ~]#ls /opt
hello  passwd
[root@node2 ~]#cat /opt/hello 
hello world

可以通过修改默认模块,来支持shell模块

[root@localhost ~]#vim /etc/ansible/ansible.cfg 

3.Script 模块

功能:在远程主机上运行ansible服务器上的脚本(无需执行权限)

 注意:此模块不具有幂等性

[root@localhost ~]#vim test.sh
[root@localhost ~]#cat test.sh 
#!/bin/bash
echo "hello world"
[root@localhost ~]#ansible web -m script -a "~/test.sh"
192.168.241.22 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.241.22 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.241.22 closed."
    ], 
    "stdout": "hello world\r\n", 
    "stdout_lines": [
        "hello world"
    ]
}
192.168.241.23 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.241.23 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.241.23 closed."
    ], 
    "stdout": "hello world\r\n", 
    "stdout_lines": [
        "hello world"
    ]
}
[root@localhost ~]#vim test.sh 
[root@localhost ~]#ll test.sh 
-rw-r--r-- 1 root root 27 3月  12 14:59 test.sh
[root@localhost ~]#ansible web -m script -a "~/test.sh"
192.168.241.22 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.241.22 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.241.22 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}
192.168.241.23 | CHANGED => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.241.23 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.241.23 closed."
    ], 
    "stdout": "", 
    "stdout_lines": []
}

[root@node2 ~]#ls /opt
cxk  hello  passwd

4.Copy 模块

功能:从ansible服务器主控端复制文件到远程主机

 注意: src=file 如果是没指明路径,则为当前目录或当前目录下的files目录下的file文件

关键字

  • src       代表源文件路径
  • dest      代表文件落地路径
  • owner     属主
  • group     属组
  • mode      代表权限
  • backup  如果复制时有同名文件会先备份再复制
[root@localhost ~]#ansible web -m copy -a "src=/etc/fstab dest=/opt/ owner=ghd group=ghd mode=644"
192.168.241.22 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "0a8f7ec11a7ba2691809e9c6c79137d24b91187f", 
    "dest": "/opt/fstab", 
    "gid": 1000, 
    "group": "ghd", 
    "md5sum": "231ccf5a7234d4f3c0f0a30e98fcb19c", 
    "mode": "0644", 
    "owner": "ghd", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 465, 
    "src": "/root/.ansible/tmp/ansible-tmp-1710227335.94-6918-138458584116423/source", 
    "state": "file", 
    "uid": 1000
}
192.168.241.23 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "0a8f7ec11a7ba2691809e9c6c79137d24b91187f", 
    "dest": "/opt/fstab", 
    "gid": 1002, 
    "group": "ghd", 
    "mode": "0644", 
    "owner": "ghd", 
    "path": "/opt/fstab", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 465, 
    "state": "file", 
    "uid": 1002
}
[root@node2 ~]#ls /opt
fstab  cxk  hello  passwd
[root@node2 ~]#cat /opt/fstab 
 
#
# /etc/fstab
# Created by anaconda on Tue Dec 19 00:11:27 2023
#
# Accessible filesystems, by reference, are maintained under '/dev/disk'
# See man pages fstab(5), findfs(8), mount(8) and/or blkid(8) for more info
#
/dev/mapper/centos-root /                       xfs     defaults        0 0
UUID=0ebf43c7-c647-4e61-ab4f-cf6c64fb6a0c /boot                   xfs     defaults        0 0
/dev/mapper/centos-swap swap                    swap    defaults        0 0
[root@node2 ~]#ll /opt/fstab 
-rw-r--r--. 1 ghd ghd 465 Mar 12 03:08 /opt/fstab

 backup 

[root@localhost ~]#vim test.sh 
[root@localhost ~]#cat test.sh 
#!/bin/bash
touch /opt/cxk
123123
[root@localhost ~]#ansible web -m copy -a "src=~/test.sh dest=/opt/ owner=ghd group=ghd mode=777"
192.168.241.23 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "0d1614b01219096a6a8c827827ead953ddaff014", 
    "dest": "/opt/test.sh", 
    "gid": 1002, 
    "group": "ghd", 
    "md5sum": "fb8c0738d3c09da20924bc6b632eb7e7", 
    "mode": "0777", 
    "owner": "ghd", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 34, 
    "src": "/root/.ansible/tmp/ansible-tmp-1710228145.96-7404-18496525191031/source", 
    "state": "file", 
    "uid": 1002
}
192.168.241.22 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "0d1614b01219096a6a8c827827ead953ddaff014", 
    "dest": "/opt/test.sh", 
    "gid": 1000, 
    "group": "ghd", 
    "md5sum": "fb8c0738d3c09da20924bc6b632eb7e7", 
    "mode": "0777", 
    "owner": "ghd", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 34, 
    "src": "/root/.ansible/tmp/ansible-tmp-1710228145.95-7402-249014437514833/source", 
    "state": "file", 
    "uid": 1000
}
[root@node2 ~]#ls /opt
test.sh
[root@node2 ~]#cat /opt/test.sh 
#!/bin/bash
touch /opt/cxk
123123
[root@localhost ~]#vim test.sh 
[root@localhost ~]#cat test.sh 
#!/bin/bash
touch /opt/cxk
123123
123123123123
[root@localhost ~]#ansible web -m copy -a "src=~/test.sh dest=/opt/ owner=ghd group=ghd mode=777 backup=yes"
192.168.241.22 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/opt/test.sh.8274.2024-03-12@03:23:19~", 
    "changed": true, 
    "checksum": "8908a5fb0ed0bf37176a2179267c7425256cae67", 
    "dest": "/opt/test.sh", 
    "gid": 1000, 
    "group": "ghd", 
    "md5sum": "c2be730d6da7cdf3ad9c0bc3c865868f", 
    "mode": "0777", 
    "owner": "ghd", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 47, 
    "src": "/root/.ansible/tmp/ansible-tmp-1710228198.82-7515-126408936780150/source", 
    "state": "file", 
    "uid": 1000
}
192.168.241.23 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "backup_file": "/opt/test.sh.7980.2024-03-12@23:23:18~", 
    "changed": true, 
    "checksum": "8908a5fb0ed0bf37176a2179267c7425256cae67", 
    "dest": "/opt/test.sh", 
    "gid": 1002, 
    "group": "ghd", 
    "md5sum": "c2be730d6da7cdf3ad9c0bc3c865868f", 
    "mode": "0777", 
    "owner": "ghd", 
    "secontext": "system_u:object_r:usr_t:s0", 
    "size": 47, 
    "src": "/root/.ansible/tmp/ansible-tmp-1710228198.83-7517-181272217391761/source", 
    "state": "file", 
    "uid": 1002
}
[root@node2 ~]#ls /opt
test.sh  test.sh.8274.2024-03-12@03:23:19~
[root@node2 ~]#cat /opt/test.sh 
#!/bin/bash
touch /opt/cxk
123123
123123123123

源文件变动后 会有如果复制时有同名文件会先备份再复制  

ansible web -m copy -a "src=/etc dest=/backup"
ansible web -m copy -a "src=/etc/ dest=/backup"
 
 
etc  	不加  	/   	连etc  一起复制  etc会变成子目录
etc   	加  		/	   	只复制etc下的文件  把etc下的文件夹改名为 bakckup
[root@localhost ~]#ansible web -m copy -a "content='test line1\ntest line2\n' dest=/tmp/test.txt"
#指定内容,直接生成目标文件
192.168.241.22 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "bbd9f88cdd0202dc851c4ff635538e652c48da02", 
    "dest": "/tmp/test.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d913c48ee3f663f1e1f2e626aefa7fa9", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 22, 
    "src": "/root/.ansible/tmp/ansible-tmp-1710229571.89-44664-73626291238432/source", 
    "state": "file", 
    "uid": 0
}
192.168.241.23 | CHANGED => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": true, 
    "checksum": "bbd9f88cdd0202dc851c4ff635538e652c48da02", 
    "dest": "/tmp/test.txt", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d913c48ee3f663f1e1f2e626aefa7fa9", 
    "mode": "0644", 
    "owner": "root", 
    "secontext": "unconfined_u:object_r:admin_home_t:s0", 
    "size": 22, 
    "src": "/root/.ansible/tmp/ansible-tmp-1710229571.89-44666-2447328551