PLAYBOOK的核心元素
- tasks
- vars
- templates
- handlers
playbook的基础组件
hosts:指定任务的目标主机
remote_user:远程主机执行任务的用户
tasks:任务列表
[root@node1 ansibletest]# cat fir.yaml
- hosts: all
remote_user: root
tasks:
- name: hello
command: hostname
测试
ansible-playbook --check a.yaml
运行
ansible-playbook a.yaml
收集主机信息
ansible all -m setup
web的配置
vim web.yaml
- hosts: all #所以主机
remote_user: root #以root身份运行
tasks: #任务清单
- name: install httpd
yum: name=httpd state=present #安装httpd
- name: cfg
copy: src=files/httpd.conf dest=/etc/httpd/conf/ #拷贝配置文件
- name: service
service: name=httpd state=started #启动服务
- name: check
shell: ss -tnl|grep 8080 #执行shell
[root@node1 ansibletest]# cat sec.yaml
- hosts: all
remote_user: root
tasks:
- name: create file
file: name=/root/file1 state=touch
- name: create user
user: name=testy system=yes shell=/sbin/nologin
- name: packages
yum : name=dstat
- name: copy
copy: src=/etc/fstab dest=/tmp/fs1
- name: echo
shell: echo 'hello world'
handlers
任务:在特定条件下才会触发,接收到其他任务的通知时可以触发动作
notify 通知handlers模块,通过标签来进行关联
- hosts: all
remote_user: root
tasks:
- name: install httpd
yum: name=httpd state=present
- name: cfg
copy: src=files/httpd.conf dest=/etc/httpd/conf/
notify: restart httpd #通知服务,配置文件发生修改
- name: service
service: name=httpd state=started
handlers:
- name: restart httpd #服务名称
service: name=httpd state=restarted #服务动作
tags 执行yaml时选择标签来执行
ansible-playbook -t reshttp http.yaml
- name: start service
service: name=httpd state=started enabled=yes
tags: reshttp
变量
ansible-playbook -m yum -e pkg=httpd --check bl.yaml
命令行-e 对变量进行赋值
vim bl.yaml
- hosts: all
remote_user: root
- name: install {{ pkg }}
yum: name={{ pkg }}
直接赋值变量
-
-
[root@node1 ansibletest]# cat bl.yaml - hosts: all remote_user: root vars: #直接赋值 - pkg: iotop tasks: - name: install pkg yum: name={{ pkg }}
-
根据配置文件来定义变量-全局变量
vim /etc/ansible/ansible.cfg
[web:vars]
nodename=www
domainname=lcc.com
[webs]
192.168.113.161 http_port=81
j2模板文件
- name:
hostname: name={{nodename}}{{}http_port}{{domainname}}
worker_processes {{ ansible_processor_vcpus }};
cat nginx.yaml
- hosts: all
remote_user: root
tasks:
- name: install nginx
yum: name=nginx state=present
- name: conf
template: src=files/nginx.conf dest=/etc/nginx/nginx.conf
notify: restart nginx
tags: instconf
- name: start
service: name=nginx state=started
handlers:
- name: restart nginx
service: name=nginx state=restarted