小机灵鬼|自动化运维工具:ansible(二)( 三 )


[root@ansible ansible]#ansible-playbook -t install -C httpd.ymlPLAY [all] *************************************************************************TASK [Gathering Facts] *************************************************************ok: [192.168.100.20]ok: [192.168.100.10]TASK [install httpd package] *******************************************************changed: [192.168.100.20]changed: [192.168.100.10]PLAY RECAP *************************************************************************192.168.100.10: ok=2changed=1unreachable=0failed=0skipped=0rescued=0ignored=0192.168.100.20: ok=2changed=1unreachable=0failed=0skipped=0rescued=0ignored=0[root@ansible ansible]#ansible-playbook -t install httpd.ymlPLAY [all] *************************************************************************TASK [Gathering Facts] *************************************************************ok: [192.168.100.20]ok: [192.168.100.10]TASK [install httpd package] *******************************************************changed: [192.168.100.10]changed: [192.168.100.20]PLAY RECAP *************************************************************************192.168.100.10: ok=2changed=1unreachable=0failed=0skipped=0rescued=0ignored=0192.168.100.20: ok=2changed=1unreachable=0failed=0skipped=0rescued=0ignored=0[root@ansible ansible]#ansible all -m shell -a 'rpm -q httpd'[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'.If you need to use command because yum, dnf or zypper is insufficient you can add'warn: false' to this command task or set 'command_warnings=False' in ansible.cfgto get rid of this message.192.168.100.20 | CHANGED | rc=0 >>httpd-2.4.6-67.el7.centos.x86_64192.168.100.10 | CHANGED | rc=0 >>httpd-2.4.6-67.el7.centos.x86_64[root@ansible ansible]#ansible all -m shell -a 'ss -ntl | grep 80'192.168.100.20 | FAILED | rc=1 >>non-zero return code192.168.100.10 | FAILED | rc=1 >>non-zero return code(8)运行playbook
如果命令或脚本的退出码不为零 , 可以使用如下方式替代
tasks:- name: run this command and ignore the resultshell: /usr/bin/somecommand || /bin/true或者使用ignore_errors来忽略错误信息:
tasks:- name: run this command and ignore the resultshell: /usr/bin/somecommandignore_errors: True运行playbook的方式
ansible-playbook ... [options]
常见选项:
--check只检测可能会发生的改变 , 但不真正执行操作
--list-hosts 列出运行任务的主机
--limit主机列表只针对主机列表中的主机执行
-v显示过程-vv -vvv 更详细
示例:ansible-playbook file.yml --check #只检测ansible-playbook file.yml #执行ansible-playbook file.yml --limit webserver(9)ansible-playbook支持变量:
变量名:仅能由字母、数字和下划线组成 , 且只能以字母开头
变量来源:
1.ansible setup facts远程主机的所有变量都可直接调用
2.在/etc/ansible/hosts中定义

  • 普通变量:主机组中主机单独定义 , 优先级高于公共变量
  • 公共(组)变量:针对主机组中所有主机定义统一变量

小机灵鬼|自动化运维工具:ansible(二)3.通过命令行指定变量 , 优先级最高


推荐阅读