一、ansible实现方式
Ad-Hoc ##利用ansible命令直接完成管理,主要用于临时命令使用场景
playbook ##ansible脚本,主要用于大型项目场景,需要前期的规划
二、ansble-doc 获取模块的帮助
ansible-doc [ 参数 ] [ 模块 ]
-l ##列出所有可用模块
-s ##显示指定模块的playbook片段
ansible-doc -l
ansible-doc -s ping ##显示ping模块的playbook片段
ansible-doc -s dnf ##显示dnf模块的playbook片段
三、ansible命令常用参数
参数 | 作用 | 所对应的配置文件的参数 |
--version | 显示版本信息 | \ |
-m | 指定模块,默认为command模块 | \ |
-v | 详细过程 -vv -vvv更详细过程 | \ |
--list | 显示主机列表,也可以用--list-hosts | \ |
-k | 提示输入ssh连接密码,默认key认证。 | ask_pass=True|False |
-C | 预执行(其实并没有执行) | \ |
-T | 执行命令的超时时间,默认10s | \ |
-u | 指定远程执行的用户 | remote_user= |
--become | 执行sudo切换身份操作 | become=True|False |
--become-user=root | 指定sudo的用户为root | become_user= |
-K | 提示输入sudo密码 | become_ask_pass=True|False |
实例:
ansible all -m ping -vv
ansible all --list
ansible all -m ping -k
ansible all -m ping -C
ansible all -m ping -T 15
ansible all -m ping -u wy --become --become-user=root -K
若配置文件里各项参数已设置,则不用加对应参数
[defaults]
inventory = ~/ansible/hosts
host_key_checking = False
ask_pass = False
remote_user = wy
module_name = shell
[privilege_escalation]
become=True
become_method=sudo
become_user=root
become_ask_pass=False
四、ansible中常用模块
1. command
功能: 在远程主机执行命令,此模块为默认模块
参数 | 作用 |
chdir | 执行命令前先进入到指定目录 |
cmd | 运行命令指定,此参数不需要加 |
creates | 如果文件存在将不运行 |
removes | 如果文件存在将运行 |
free_form | 在远程主机中执行的命令,此参数不需要加 |
实例:
ansible all -m command -a 'chdir=/mnt touch file5'
nsible all -m command -a 'chdir=/etc creates=/etc/passwd tail passwd' ##存在则不运行
ansible all -m command -a 'chdir=/etc removes=/etc/passwd tail passwd' ##存在则运行
2. shell
与command功能类似
参数 | 作用 |
chdir | 执行命令前先进入到指定目录 |
cmd | 运行命令指定,此参数不需要加 |
creates | 如果文件存在将不运行 |
removes | 如果文件存在将运行 |
free_form | 在远程主机中执行的命令,此参数不需要加 |
executable | 指定执行环境,默认为sh |
实例:
ansible all -m shell -a 'executable=sh ps ax | grep $$'
ansible all -m shell -a 'executable=bash ps ax | grep $$'