一、介绍
playbook就是一个用yaml语法把多个模块堆起来的一个文件
核心组件:
Hosts:执行的远程主机列表
Tasks:任务,由模块定义的操作的列表;
Varniables:内置变量或自定义变量在playbook中调用
Templates:模板,即使用了模板语法的文本文件;
Handlers:和nogity结合使用,为条件触发操作,满足条件方才执行,否则不执行;
Roles:角色;
yaml文件示例
- hosts: 10.1.0.1 #定义主机
vars: #定义变量
var1: value
var2: value
tasks: #定义任务
- name: #任务名称。
#这里就可以开始用模块来执行具体的任务了。
handlers: #定义触发通知所作的操作。里面也是跟tasks一样,用模块定义任务。
- name:
remote_user: #远程主机执行任务时的用户。一般都是root,一般也不用指定。
- hosts: web
vars:
tasks:
handlers:
remote_user:
二、简单使用
1、安装httpd
[root@master ~]# cat httpd.yaml
- hosts: all
tasks:
- name: "安装Apache"
command: yum install --quiet -y httpd httpd-devel
- name: "启动Apache,并设置开机启动"
command: service httpd start
command: chkconfig httpd on
#测试
[root@master ~]# ansible-playbook --check http.yaml
2、修改ssh密码
[root@master ~]# cat user.yaml
- hosts: all
remote_user: root
tasks:
- name: update user password
user: name={{name}} password={{chpass|password_hash('sha512')}} update_password=always
[root@master ~]# ansible-playbook user.yaml -e "name=www chpass=123456"
3、添加ssh账号与sudo授权
[root@master ~]# cat add_user.yaml
- hosts: test
tasks:
- name: create ssh user
user: name={{username}} password={{mypass|password_hash('sha512')}}
- name: sudo
lineinfile: dest=/etc/sudoers state=present regexp=^%{{username}} line={{username}} {{sudo}}
#使用创建zhang账号并sudo授予为ALL
[root@master ~]# ansible-playbook add_user.yaml -e "username=zhang mypass=123456 sudo='ALL=(ALL) ALL'"
#测试
[root@master ~]# ssh zhang@172.31.0.181
zhang@172.31.0.181's password:
Welcome to Alibaba Cloud Elastic Compute Service !
[zhang@node ~]$ sudo ls -l /root/.ssh/
We trust you have received the usual lecture from the local System
Administrator. It usually boils down to these three things:
#1) Respect the privacy of others.
#2) Think before you type.
#3) With great power comes great responsibility.
[sudo] password for zhang:
total 4
-rw------- 1 root root 393 Jan 15 13:41 authorized_keys