[root@ansible roles]# cat web.yml - hosts: web remote_user: root tasks: - name: create file file: name=/tmp/new.file state=touch - name: create new user user: name=test2 system=yes shell=/sbin/nologin - name: install package yum: name=httpd state=installed - name: copy html copy: src=/root/index.html dest=/var/www/html/index.html - name: start service service: name=httpd state=started enabled=yes
添加httpd index文件
[root@ansible ~]# cat index.html
123
测试访问
[root@ansible ~]# curl 10.0.0.8
123
- --limit 选则组里的某台机器执行命令
ansible web -m ping --limit 10.0.0.7
# 只在web组的 10.0.0.7上执行ping
- --list-tasks 查看任务列表
[root@ansible roles]# ansible-playbook web.yml --list-tasks
playbook: web.yml
play #1 (web): web TAGS: []
tasks:
create file TAGS: []
create new user TAGS: []
install package TAGS: []
copy html TAGS: []
start service TAGS: []
- handlers 和notify 结合重启服务
"web.yml" 20L, 546C 12,7 All - hosts: web remote_user: root tasks: - name: install package yum: name=httpd state=installed - name: copy html copy: src=file/httpd.conf dest=/etc/httpd/conf/ backup=yes notify: restart httpd - name: start httpd service: name=httpd state=started enabled=yes handlers: - name: restart httpd service: name=httpd state=restarted enabled=yes
变量
- setup 查看内置变量
过滤变量 -setup -a 'ilter =变量'
[root@ansible roles]# ansible web -m setup -a 'filter=*addr' 10.0.0.8 | SUCCESS => { "ansible_facts": {}, "changed": false } #支持 通配符 *号 [root@ansible roles]# ansible web -m setup -a 'filter=*ipv4' 10.0.0.8 | SUCCESS => { "ansible_facts": { "ansible_default_ipv4": { "address": "10.0.0.8", "alias": "eth0", "broadcast": "10.0.0.255", "gateway": "10.0.0.2", "interface": "eth0", "macaddress": "00:0c:29:24:58:ed", "mtu": 1500, "netmask": "255.255.255.0", "network": "10.0.0.0", "type": "ether" } }, "changed": false }
playbook中定义引用变量
[root@ansible roles]# cat app.yml - hosts: web remote_user: root tasks: - name: install package yum: name={{ pkname }} state=installed - name: start httpd service: name={{ pkname }} state=started enabled=yes
命令行中 -e 调用playbook 中的变量 变量优先级 1
ansible-playbook -e 'pkname=redis' -C app.yml
vars:playbook中定义变量 yum模块直接引用变量
- hosts: web remote_user: root vars: - pkname1: httpd - pkname2: mysql tasks: - name: install package yum: name={{ pkname1 }} state=installed - name: install package yum: name={{ pkname2 }} state=installed
主机清单变量
对组内主机定义不同变量此时 内的主机会有不同的端口 变量优先级 2
[web]
10.0.0.52 http_port=10080 #只对 52主机生效
10.0.0.53 http_port=8080 #只对 53生效
对组内的主机定义相同的变量 变量优先级 3
比如web组里有1000个主机,要写端口为2020,就得写1000个,下面给web组设置个变量写好端口
省的重复在web里写http_prot=2020
[web] 10.0.0.51 10.0.0.52 10.0.0.53
[web:vars] http_prot=2020 对web组的所有主机生效