ansible-playbook的基本组件——杂记

定义执行主机和执行用户
- hosts: webserver
remote_user: root
sudu: yes
——————————————
tasks列表,Play的主体部分是task列表,task列表中的各任务按次序逐个在hosts中指定的主机上执行,即在所有主机上完成第一个任务后再开始第二个任务。Task的目的是使用指定的参数执行模块,而在模块参数中可以使用变量,

- name: ensure apache is at the latest version
yum: name=httpd state=latest(见ansible模块参数)

执行时shell和command模块时忽略错误信息,防止剧本被打断。
tasks:
- name: run this command and ignore the result
shell: /usr/bin/somecommand
ignore_errors: True
————————————————

定义变量和模版
- hosts: test
vars:
- package: httpd
vars固定格式,package变量名,httpd变量值
变量名支持字母数字以及下划线,变量名须字母开头。

调用方法
tasks:
- name: ensure apache is at the latest version
yum: name={{ package }} state=latest

在task或template中引用变量都是使用双花括号中间引入变量名即可,如:{{ VAR_NAME }}。
————————————————

handlers
发生改变时执行提前定义好的操作

command执行命令
command: shell命令
————————————————
lineinfile
文件操作
匹配行修改
- name: seline modify enforcing
lineinfile:
dest: /etc/selinux/config
regexp: '^SELINUX='
line: 'SELINUX=enforcing'

匹配上上方插入
- name: httpd.conf modify 8080
lineinfile:
dest: /opt/playbook/test/http.conf
regexp: '^Listen'
insertbefore: '^#Port'
line: 'Listen 8080'

匹配行下方插入
- name: httpd.conf modify 8080
lineinfile:
dest: /opt/playbook/test/http.conf
regexp: '^Listen'
insertafter: '^#Port'
line: 'Listen 8080'

删除某行
- name: delete 192.168.1.1
lineinfile:
dest: /opt/playbook/test/hosts
state: absent
regexp: '^192\.'

末行添加
name: add a line
lineinfile:
dest: /opt/playbook/test/hosts
line: '192.168.1.2 foo.lab.net foo'

 


Register
将命令执行结果存储到变量中
tasks:

- name: retrieve the list of home directories
command: ls /home
register: home_dirs

- name: add home dirs to the backup spooler
file: path=/mnt/bkspool/{{ item }} src=/home/{{ item }} state=link
with_items: home_dirs.stdout_lines

 

 

 

posted @ 2018-03-17 14:20  Leonardo-li  阅读(385)  评论(0编辑  收藏  举报