ansible的脚本——playbook剧本

目录

一、playbook的组成

[二、 playbook安装httpd服务](#二、 playbook安装httpd服务)

1.编写playbook剧本

2.运行playbook

三、定义、引用变量

[四、 指定远程主机sudo切换用户](#四、 指定远程主机sudo切换用户)

五、when条件判断

六、迭代

[七、Templates 模块](#七、Templates 模块)

[1.先准备一个以 .j2 为后缀的 template 模板文件,设置引用的变量](#1.先准备一个以 .j2 为后缀的 template 模板文件,设置引用的变量)

2.修改主机清单文件,使用主机变量定义一个变量名相同,而值不同的变量

[3.编写 playbook](#3.编写 playbook)

[八、tags 模块](#八、tags 模块)

九、利用playbook部署lnmp集群

1.修改nginx配置文件

2.编写lnmp的剧本

3.运行playbook并访问验证


一、playbook的组成

  1. Tasks:任务,即通过 task 调用 ansible 的模板将多个操作组织在一个 playbook 中运行
  2. Variables:变量
  3. Templates:模板
  4. Handlers:处理器,当changed状态条件满足时,(notify)触发执行的操作
  5. Roles:角色

二、 playbook安装httpd服务

1.编写playbook剧本

bash 复制代码
vim test1.yaml
---     #yaml文件以---开头,以表明这是一个yaml文件,可省略
- name: first play     #定义一个play的名称,可省略
  gather_facts: false    #设置不进行facts信息收集,这可以加快执行速度,可省略
  hosts: webservers    #指定要执行任务的被管理主机组,如多个主机组用冒号分隔
  remote_user: root    #指定被管理主机上执行任务的用户
  tasks:     #定义任务列表,任务列表中的各任务按次序逐个在hosts中指定的主机上执行
   - name: test connection    #自定义任务名称
     ping:     #使用 module: [options] 格式来定义一个任务
   - name: disable selinux
     command: '/sbin/setenforce 0'    #command模块和shell模块无需使用key=value格式
     ignore_errors: True     #如执行命令的返回值不为0,就会报错,tasks停止,可使用ignore_errors忽略失败的任务
   - name: disable firewalld
     service: name=firewalld state=stopped    #使用 module: options 格式来定义任务,option使用key=value格式
   - name: install httpd
     yum: name=httpd state=latest
   - name: install configuration file for httpd
     copy: src=/opt/httpd.conf dest=/etc/httpd/conf/httpd.conf    #这里需要一个事先准备好的/opt/httpd.conf文件
     notify: "restart httpd"    #如以上操作后为changed的状态时,会通过notify指定的名称触发对应名称的handlers操作
   - name: start httpd service
     service: enabled=true name=httpd state=started
  handlers:     #handlers中定义的就是任务,此处handlers中的任务使用的是service模块
   - name: restart httpd    #notify和handlers中任务的名称必须一致
     service: name=httpd state=restarted
##Ansible在执行完某个任务之后并不会立即去执行对应的handler,而是在当前play中所有普通任务都执行完后再去执行handler,这样的好处是可以多次触发notify,但最后只执行一次对应的handler,从而避免多次重启。

2.运行playbook

bash 复制代码
ansible-playbook test1.yaml

//补充参数:
-k(--ask-pass):用来交互输入ssh密码
-K(-ask-become-pass):用来交互输入sudo密码
-u:指定用户
ansible-playbook test1.yaml --syntax-check    #检查yaml文件的语法是否正确
ansible-playbook test1.yaml --list-task       #检查tasks任务
ansible-playbook test1.yaml --list-hosts      #检查生效的主机
ansible-playbook test1.yaml --start-at-task='install httpd'     #指定从某个task开始运行

三、定义、引用变量

bash 复制代码
- name: second play
  hosts: webservers
  remote_user: root
  vars:                 #定义变量
   - groupname: mysql   #格式为 key: value
   - username: nginx
  tasks:
   - name: create group
     group: name={{groupname}} system=yes gid=306    #使用 {{key}} 引用变量的值
   - name: create user
     user: name={{username}} uid=306 group={{groupname}} 
   - name: copy file
     copy: content="{{ansible_default_ipv4}}" dest=/opt/vars.txt    #在setup模块中可以获取facts变量信息
     copy: content="{{ansible_default_ipv4.address}}" dest=/opt/vars.txt    #在setup模块中可以获取facts变量信息下子字段address字段值(IP地址)

bash 复制代码
- name: second play
  hosts: webservers
  remote_user: root
  tasks:
   - name: create group
     group: name={{groupname}} system=yes gid=306
   - name: create user
     user: name={{username}} uid=306 group={{groupname}}
   - name: copy file
     copy: content="{{ansible_default_ipv4}}" dest=/opt/vars.txt
     copy: content="{{ansible_default_ipv4.address}}" dest=/opt/vars.txt                                                                       

四、 指定远程主机sudo切换用户

bash 复制代码
- hosts: dbservers
  remote_user: zhangsan            
  become: yes	                 #2.6版本以后的参数,之前是sudo,意思为切换用户运行
  become_user: root              #指定sudo用户为root
执行playbook时:ansible-playbook test3.yml -k -K 

五、when条件判断

在Ansible中,提供的唯一一个通用的条件判断是when指令,当when指令的值为true时,则该任务执行,否则不执行该任务。

bash 复制代码
#when一个比较常见的应用场景是实现跳过某个主机不执行任务或者只有满足条件的主机执行任务
vim test3.yaml
---
- hosts: all
  remote_user: root
  tasks:
   - name: shutdown host 
     command: /sbin/shutdown -r now
     when: ansible_default_ipv4.address == "192.168.88.20"      #when指令中的变量名不需要手动加上 {{}} 
     #when: inventory_hostname == "<主机名>"
	
ansible-playbook test4.yaml

六、迭代

Ansible提供了很多种循环结构,一般都命名为with_items,作用等同于 loop 循环。

bash 复制代码
- name: play1
  hosts: dbservers
  gather_facts: false
  tasks: 
    - name: create file
      file:
        path: "{{item}}"
        state: touch
      with_items: [ /opt/a, /opt/b, /opt/c, /opt/d ]

- name: play2
  hosts: dbservers
  gather_facts: false		
  vars:
    test:
    - /tmp/test1
    - /tmp/test2
    - /tmp/test3
    - /tmp/test4
  tasks: 
    - name: create directories
      file:
        path: "{{item}}"
        state: directory
      with_items: "{{test}}"   #循环引用变量

- name: play3
  hosts: dbservers
  gather_facts: false
  tasks:
    - name: add users
      user: name={{item.name}} state=present groups={{item.groups}}
      with_items:                  #多参数循环
        - name: test1
          groups: wheel
        - name: test2
          groups: root
或
      with_items:
        - {name: 'test1', groups: 'wheel'}
        - {name: 'test2', groups: 'root'}

七、Templates 模块

Jinja是基于Python的模板引擎。Template类是Jinja的一个重要组件,可以看作是一个编译过的模板文件,用来产生目标文本,传递Python的变量给模板去替换模板中的标记。

1.先准备一个以 .j2 为后缀的 template 模板文件,设置引用的变量

bash 复制代码
cp /etc/httpd/conf/httpd.conf /opt/httpd.conf.j2

vim /opt/httpd.conf.j2
Listen {{http_port}}				#42行,修改
ServerName {{server_name}}			#95行,修改
DocumentRoot "{{root_dir}}"          #119行,修改

2.修改主机清单文件,使用主机变量定义一个变量名相同,而值不同的变量

bash 复制代码
vim /etc/ansible/hosts       
[webservers]
192.168.88.20 http_port=192.168.88.20:8080 server_name=www.accp.com:8080 root_dir=/var/www/html/accp

[dbservers]
192.168.88.30 http_port=192.168.88.30:80 server_name=www.benet.com:80 root_dir=/var/www/html/benet

3.编写 playbook

bash 复制代码
vim apache.yaml
---
- hosts: all
  remote_user: root
  vars:
    - package: httpd
    - service: httpd
  tasks:
    - name: install httpd package
      yum: name={{package}} state=latest
    - name: install configure file
      template: src=/opt/httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf     #使用template模板
      notify:
        - restart httpd
    - name: create accp dir
	  file: path=/var/www/html/accp state=directory
      when: inventory_hostname == "192.168.88.20"
    - name: create accp dir
	  file: path=/var/www/html/benet state=directory
      when: inventory_hostname == "192.168.88.30"
    - name: start httpd server
      service: name={{service}} enabled=true state=started
  handlers:
    - name: restart httpd
      service: name={{service}} state=restarted

ansible-playbook apache.yaml

八、tags 模块

可以在一个playbook中为某个或某些任务定义"标签",在执行此playbook时通过ansible-playbook命令使用--tags选项能实现仅运行指定的tasks。

playbook还提供了一个特殊的tags为always。作用就是当使用always作为tags的task时,无论执行哪一个tags时,定义有always的tags都会执行。

bash 复制代码
vim webhosts.yaml
---
- hosts: webservers
  remote_user: root
  tasks:
    - name: Copy hosts file
      copy: src=/etc/hosts dest=/opt/hosts
      tags:
      - only     #可自定义
    - name: touch file
      file: path=/opt/testhost state=touch
	  tags:
	  - always    #表示始终要运行的代码

ansible-playbook webhosts.yaml --tags="only"

九、利用playbook部署lnmp集群

1.修改nginx配置文件

bash 复制代码
/配置 nginx 支持 PHP 解析
vim default.conf
......
    location ~ \.php$ {
        root           html;
        fastcgi_pass   127.0.0.1:9000;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  /usr/share/nginx/html$fastcgi_script_name;  #将 /scripts 修改为nginx的工作目录
        include        fastcgi_params;
    }

2.编写lnmp的剧本

bash 复制代码
vim lnmp.yml
- name: nginx
  gather_facts: false
  hosts: webservers
  remote_user: root
  tasks:
#yum安装nginx
  - name: create nginx yum
    copy: src=/etc/yum.repos.d/nginx.repo dest=/etc/yum.repos.d/nginx.repo
  - name: install nginx
    yum: name=nginx
#将编辑好的nginx配置文件复制到远程主机 
  - name: nginx congruation file
    copy: src=/opt/default.conf dest=/etc/nginx/conf.d/default.conf
  - name: start nginx
    service: name=nginx state=started enabled=yes
  - name: wordpress
    copy: src=/opt/lnmp/nginx/www/wordpress dest=/usr/share/nginx/html/

- name: mysql
  hosts: webservers
  remote_user: root
  tasks:
#安装mysql
  - name: remove mariadb
    shell: yum -y remove mariadb*
    ignore_errors: true
  - name: wegt
    command: wget https://repo.mysql.com/mysql57-community-release-el7-11.noarch.rpm
  - name: inatsll mysqlrpm
    command: rpm -ivh mysql57-community-release-el7-11.noarch.rpm
  - name: change mysql-community.rpm
    shell: sed -i 's/gpgcheck=1/gpgcheck=0/'  /etc/yum.repos.d/mysql-community.repo
  - name: install mysql
    yum: name=mysql-server
  - name: start mysqld
    service: name=mysqld.service state=started enabled=yes
  - name: echo password
    shell: grep "password" /var/log/mysqld.log | awk 'NR==1{print $NF}'  #在日志文件中找出root用户的初始密码
    register: mysql_password   #将初始密码导入到mysql_password的变量中
  - name: echo
    debug:                      
     msg: "{{ mysql_password }}"  #输出变量mysql_password的值
#登录mysql,修改MySQL登录密码  
  - name: grant location
    shell:  mysql --connect-expired-password -uroot -p"{{ mysql_password['stdout'] }}" -e "ALTER USER 'root'@'localhost' IDENTIFIED BY 'Admin@123';"
#修改权限 
  - name: grant option
    shell: mysql --connect-expired-password -uroot -pAdmin@123 -e "grant all privileges on *.* to 'root'@'%' identified by 'Admin@123456' with grant option;"
#创建wordpress数据库
  - name: create database
    shell: mysql --connect-expired-password -uroot -pAdmin@123 -e "create database wordpress;"
#赋予admin用户访问wordpress的权限
  - name: grant
    shell: mysql --connect-expired-password -uroot -pAdmin@123 -e "grant all on wordpress.* to 'admin'@'%' identified by 'Admin@123456';"
  - name: grant
    shell: mysql --connect-expired-password -uroot -pAdmin@123 -e "grant all on wordpress.* to 'admin'@'localhost' identified by 'Admin@123456';"
  - name: flush
    shell: mysql --connect-expired-password -uroot -pAdmin@123 -e 'flush privileges;'
#为了防止每次yum操作都会自动更新,卸载这个软件
  - name: yum
    command: yum -y remove mysql57-community-release-el7-11.noarch

#安装php及其依赖包
- name: php
  hosts: webservers
  remote_user: root
  tasks:
  - name: yum rpm
    command: yum -y install https://rpms.remirepo.net/enterprise/remi-release-7.rpm
  - name: yum
    yum: name=yum-utils
  - name: yum-config
    command: yum-config-manager --enable remi-php74
  - name: install yilaibao
    command: yum -y install php  php-cli php-fpm php-mysqlnd php-zip php-devel php-gd php-mcrypt php-mbstring php-curl php-xml php-pear php-bcmath php-json php-redis
  - name: start php
    service: name=php-fpm state=started enabled=yes

3.运行playbook并访问验证

bash 复制代码
ansible-playbook lnmp.yml

#验证
浏览器访问http://192.168.88.30/wordpress/index.php

相关推荐
Dobby_052 天前
【Ansible】变量与敏感数据管理:Vault加密与Facts采集详解
linux·运维·云原生·ansible
Adorable老犀牛3 天前
ansible playbook 实战案例roles | 实现基于 IHS 的 AWStats 访问监控系统
ansible·playbook·roles·角色
小白不想白a3 天前
【Ansible】变量、机密、事实
运维·云原生·ansible
2302_799525744 天前
【ansible】2.实施ansible playbook
linux·运维·ansible
IT成长日记4 天前
【自动化运维神器Ansible】Playbook调用Role详解:从入门到精通
运维·自动化·ansible·playbook·role
小白不想白a4 天前
【Ansible】将文件部署到受管主机1:文件模块
ansible
skywalk81634 天前
设计简洁的Ansible:目前非常流行的开源配置管理和自动化工具
开源·自动化·ansible
2302_799525744 天前
【ansible】4.实施任务控制
linux·服务器·ansible
2401_831501734 天前
Linux之Ansible自动化运维(二)
运维·自动化·ansible
Adorable老犀牛4 天前
ansible playbook 实战案例roles | 实现基于firewalld添加端口
ansible·防火墙·firewalld·roles