A-PlayBook示例

时间:2023-02-23 13:01:27

运行playbook的方式

ansible-playbook <filename.yml> ... [options]

常见选项

--check -C 只检测可能会发生的改变,但不真正执行操作
--list-hosts 列出运行任务的主机
--list-tags 列出tag
--list-tasks 列出task
--limit 主机列表 只针对主机列表中的主机执行
-v -vv -vvv 显示过程

ansible-playbook file.yml --check 只检测
ansible-playbook file.yml
ansible-playbook file.yml --limit websrvs

示例-安装httpd

---
- hosts: web
remote_user: root
tasks:
- name: "安装Apache"
yum: name=httpd
- name: "复制配置文件"
copy: src=/tmp/httpd.conf dest=/etc/httpd/conf/
- name: "复制配置文件"
copy: src=/tmp/vhosts.conf dest=/etc/httpd/conf.cd/
- name: "启动Apache,并设置开机启动"
service: name=httpd state=started enabled=yes

示例-设置用户sysuser.yml

---
- hosts: all
remote_user: root
tasks:
- name: create mysql user
user: name=mysql system=yes uid=36
- name: create a group
group: name=httpd system=yes

Handlers使用

- hosts: websrvs
remote_user: root
tasks:
- name: add group nginx
tags: user
user: name=nginx state=present
- name: add user nginx
user: name=nginx state=present group=nginx
- name: Install Nginx
yum: name=nginx state=present
- name: config
copy: src=/root/config.txt dest=/etc/nginx/nginx.conf
notify:
- Restart Nginx
- Check Nginx Process
handlers:
- name: Restart Nginx
service: name=nginx state=restarted enabled=yes
- name: Check Nginx process
shell: killall -0 nginx > /tmp/nginx.log

tags使用

- hosts: websrvs
remote_user: root
tasks:
- name: Install httpd
yum: name=httpd state=present
- name: Install configure file
copy: src=files/httpd.conf dest=/etc/httpd/conf/
tags: conf
- name: start httpd service
tags: service
service: name=httpd state=started enabled=yes

示例:使用setup变量

- hosts: web
remote_user: root
tasks:
- name: create log file
file: name=/var/log/ {{ ansible_fqdn }} state=touch
ansible-playbook var.yml

示例-用户添加

- hosts: websrvs
remote_user: root
vars:
- username: user1
- groupname: group1
tasks:
- name: create group
group: name={{ groupname }} state=present
- name: create user
user: name={{ username }} state=present
ansible-playbook user.yml
ansible-playbook -e "username=user2 groupname=group2” var2.yml

组变量是指赋予给指定组内所有主机上的在playbook中可用的变量

[websrvs:vars]
ntp_server=ntp.magedu.com
nfs_server=nfs.magedu.com

普通变量

[websrvs]
192.168.99.101 http_port=8080 hname=www1
192.168.99.102 http_port=80 hname=www2

公共(组)变量

[websvrs:vars]
http_port=808
mark=“_”
[websrvs]
192.168.99.101 http_port=8080 hname=www1
192.168.99.102 http_port=80 hname=www2
ansible websvrs –m hostname –a ‘name={{ hname }}{{ mark }}{{ http_port }}’

使用变量文件

vim vars.yml
var1: httpd
var2: nginx
vim var.yml
- hosts: web
remote_user: root
vars_files:
- vars.yml
tasks:
- name: create httpd log
file: name=/app/{{ var1 }}.log state=touch
- name: create nginx log
file: name=/app/{{ var2 }}.log state=touch