1、举例:
---
- name: create user
hosts: webserver
remote_user: root
tasks:
- name: creat users
user: name=test1 uid=36 system=yes
- name: create group
group: name=httpd system=yes
模块也可以写成如下格式:
tasks:
- name: creat users
user:
name: test1
uid: 36
system: yes
- name: create group
group:
name: httpd
system: yes
当写成如上格式,引用变量时,变量需要加双引号
tasks:
- name: creat users
user:
name: "{{ name1 }}"
uid: "{{ uid1 }}"
2、举例:
---
- name: install service
hosts: webserver
remote_user: root
tasks:
- name: install httpd
yum: name=httpd state=present
- name: copy conf file
cpoy: src=files/httpd.conf dest=/etc/httpd/conf
- name: start service
service: name=httpd state=started enabled=yes
解析:
- name: copy conf file
cpoy: src=files/httpd.conf dest=/etc/httpd/conf
cpoy: src=files/httpd.conf dest=/etc/httpd/conf
【如上,当一个任务name下有相同的模块时,yml只会识别一个,故需要再写一个任务name】
- name: copy conf file
cpoy: src=files/httpd.conf dest=/etc/httpd/conf
- name: copy conf file2
cpoy: src=files/http.conf dest=/etc/httpd/conf
亦或:
tasks:
- copy: **
- copy: **
用"-" 开头就表示是name任务级别了,即两个copy模块就是两个不同的任务了;此时不要写- name: ** 因为写了- name: **
就必须是 - name: ** 这种格式,- name下一定得接上模块内容。
copy: **
亦或:
tasks:
- name: **
module1: **
- copy: **
- copy: **
解释:- name: ** 到module1 表示一个任务的结束了,另起一行的"-"开头的 - copy表示另一个任务了
notify和handlers的使用
3、举例:当配置文件更改后重新执行脚本,name服务本身是启动的,故不会再起,这样配置文件未生效,所以标记当配置文件
更改并执行后,就执行重启服务的动作。
---
- name: install service
hosts: webserver
remote_user: root
tasks:
- name: install httpd
yum: name=httpd state=present
- name: copy conf file
cpoy: src=files/httpd.conf dest=/etc/httpd/conf
notify: restart service 【注意:当copy的动作执行后就会下发一个通知,由notity下发通知,通知给handlers的name】
- name: start service
service: name=httpd state=started enabled=yes
handlers: 【handlers和tasks同级别】
- name: restart service
service: name=httpd state=restarted
@2、【notify也可同时通知多个handlers的name:】
---
- name: install service
hosts: webserver
remote_user: root
tasks:
- name: install httpd
yum: name=httpd state=present
- name: copy conf file
cpoy: src=files/httpd.conf dest=/etc/httpd/conf
notify:
- restart service
- ping service
- name: start service
service: name=httpd state=started enabled=yes
handlers:
- name: restart service
service: name=httpd state=restarted
- name: ping service
ping:
tags的使用
4、举例:
---
- name: install service
hosts: webserver
remote_user: root
tasks:
- name: install httpd
yum: name=httpd state=present
- name: copy conf file
cpoy: src=files/httpd.conf dest=/etc/httpd/conf
tags: copy_conf
- name: start service
service: name=httpd state=started enabled=yes
tags: services
ansible-palybook -t copy_conf file.yml 【-t 指定tags名称,调用tags标记的任务执行,所以这里只会执行copy conf file一个name任务】
【注:多个任务可以共用一个标签tags】