第 5.2 章 Playbook基本使用--YAML语法和Playbook文件结构

yml语法格式:

缩进表示层级关系

不支持制表符“tab”缩进,使用空格缩进

通常开头缩进 2 个空格

字符后缩进 1 个空格,如冒号、逗号等

“---” 表示YAML格式,一个文件的开始(可有可无)

“#”注释

Playbook文件结构

---
- name: play1   #执行脚本名称,一个执行脚本一个名称,便于执行时能找到哪行代码执行有错
  hosts: web# 指定使用主机清单的组名,这里使用[web]组
  remote_user: root   #指定远程执行playbook的用户,默认使用root
  vars:#脚本执行中所要使用的变量
    var_name: value   #定义变量的值
  
  tasks:      #开始执行playbook的具体工作
  - name: echo     #执行过程中每个任务名会进行输出,便于查看进度
    shell: "echo {{var_name}}"    #输出变量 var_name的值

Nginx安装示例

通过一个Nginx安装示例来了解playbook用法,创建一个目录用来存放Nginx安装所用文件:

mkdir nginx-demo

vim nginx.yml

(注意文件格式。缩进使用空格,不使用Tab键)

#nginx.yml  
- hosts: abc
  vars:
    hello: Ansible
  tasks:
  - name: Add repo 
    yum_repository:
      name: nginx 
      description: nginx repo
      baseurl: http://nginx.org/packages/centos/7/$basearch/ 
      gpgcheck: no
      enabled: 1
  - name: Install nginx 
    yum:
      name: nginx 
      state: latest
  - name: Copy nginx configuration file 
    copy:
       src: ./site.conf
       dest: /etc/nginx/conf.d/site.conf
  - name: Start nginx 
    service:
      name: nginx 
      state: started
  - name: Create wwwroot directory 
    file:
      dest: /var/www/html 
      state: directory
  - name: Create test page index.html
    shell: echo "hello {{hello}}" > /var/www/html/index.html
  - name: firewalld 80
    shell: firewall-cmd --add-port=80/tcp --permanent
  - name: firewall service restart
    service:
      name: firewalld
      state: restarted

创建Nginx配置文件:

vim site.conf
#site.conf
server {
    listen 80;
    server_name www.ctnrs.com; 
    location / {
        root /var/www/html; 
        index index.html;
    }
}

保存后检查yml脚本语法:

yml文件语法检查: ansible-playbook nginx.yml --syntax-check

执行yml文件运行;ansible-playbook nginx.yml

检测abc主机组Nginx安装测试命令:

curl 142.4.123.13 -H "Host:www.ctnrs.com"

curl 47.241.90.203 -H "Host:www.ctnrs.com"

版权声明:
作者:WaterBear
链接:https://l-t.top/2019.html
来源:雷霆运维
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
< <上一篇
下一篇>>
文章目录
关闭
目 录