Ansible-playbook剧本和角色

Ansible 的脚本 --- playbook 剧本

playbooks 本身由以下各部分组成


(1)Tasks:任务,即通过 task 调用 ansible 的模板将多个操作组织在一个 playbook 中运行
(2)Variables:变量
(3)Templates:模板, 允许你在配置文件中插入变量、条件语句、循环等逻辑,从而根据不同的情况生成不同的配置文件。
(4)Handlers:处理器,当changed状态条件满足时,(notify)触发执行的操作
(5)Roles:角色,Roles允许你将相关的任务、变量、文件和处理逻辑组织成一个独立的单元,以便在不同的Playbook中重复使用,并使Playbook更加模块化和易于维护。


//示例:
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,从而避免多次重启。


//运行playbook


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开始运行


//定义、引用变量


- name: second play
  hosts: dbservers
  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变量信息


ansible-playbook test1.yaml -e "username=nginx"     #在命令行里定义变量


//指定远程主机sudo切换用户


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


//when条件判断


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

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


//迭代
Ansible提供了很多种循环结构,一般都命名为with_items,作用等同于 loop 循环。
vim test3.yaml
---
- 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'}

ansible-playbook test3.yaml


Templates 模块


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

1.先准备一个以 .j2 为后缀的 template 模板文件,设置引用的变量
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.修改主机清单文件,使用主机变量定义一个变量名相同,而值不同的变量
vim /etc/ansible/hosts       
[webservers]
192.168.80.11 http_port=192.168.80.11:80 server_name=www.accp.com:80 root_dir=/etc/httpd/htdocs

[dbservers]
192.168.80.12 http_port=192.168.80.12:80 server_name=www.benet.com:80 root_dir=/etc/httpd/htdocs

3.编写 playbook 
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 root dir
      file: path=/etc/httpd/htdocs state=directory
    - 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都会执行。

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"

vim dbhosts.yaml
---
- hosts: dbservers
  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


ansible-playbook dbhosts.yaml --tags="only"
//分别去两台被管理主机上去查看文件创建情况


Roles 模块


roles用于层次性、结构化地组织playbook。roles能够根据层次型结构自动装载变量文件、tasks以及handlers等。要使用roles只需要在playbook中使用include指令引入即可。
简单来讲,roles就是通过分别将变量、文件、任务、模板及处理器放置于单独的目录中,并可以便捷的include它们的一种机制。roles一般用于基于主机构建服务的场景中,但也可以是用于构建守护进程等场景中。主要使用场景代码复用度较高的情况下。

假如我们现在有3个被管理主机,第一个要配置成httpd,第二个要配置成haproxy服务器,第三个要配置成MySQL(mariadb)服务器。我们如何来定义playbook?
第一个play用到第一个主机上,用来构建httpd,第二个play用到第二个主机上,用来构建haproxy。这些个play定义在playbook中比较麻烦,将来也不利于模块化调用,不利于多次调用。比如说后来又加进来一个主机,这第3个主机既是httpd服务器,又是haproxy服务器,我们只能写第3个play,上面写上安装httpd和haproxy。这样playbook中的代码就重复了。
为了避免代码重复,可以定义一个角色叫httpd,第二个角色叫haproxy,并使用roles实现代码重复被调用。

//roles 的目录结构:
cd /etc/ansible/
tree roles/
roles/
├── web/    #相当于 playbook 中的 每一个 play 主题
│   ├── files/
│   ├── templates/
│   ├── tasks/
│   ├── handlers/
│   ├── vars/
│   ├── defaults/
│   └── meta/
└── db/
    ├── files/
    ├── templates/
    ├── tasks/
    ├── handlers/
    ├── vars/
    ├── defaults/
    └── meta/


//roles 内各目录含义解释
●files
用来存放由 copy 模块或 script 模块调用的文件。

●templates
用来存放 jinjia2 模板,template 模块会自动在此目录中寻找 jinjia2 模板文件。

●tasks
此目录应当包含一个 main.yml 文件,用于定义此角色的任务列表,此文件可以使用 include 包含其它的位于此目录的 task 文件。

●handlers
此目录应当包含一个 main.yml 文件,用于定义此角色中触发条件时执行的动作。

●vars
此目录应当包含一个 main.yml 文件,用于定义此角色用到的变量。

●defaults
此目录应当包含一个 main.yml 文件,用于为当前角色设定默认变量。 这些变量具有所有可用变量中最低的优先级,并且可以很容易地被任何其他变量覆盖。所以生产中我们一般不在这里定义变量

●meta
此目录应当包含一个 main.yml 文件,用于定义此角色的元数据信息及其依赖关系。


//在一个 playbook 中使用 roles 的步骤:
(1)创建以 roles 命名的目录
mkdir /etc/ansible/roles/ -p    #yum装完默认就有

(2)创建全局变量目录(可选)
mkdir /etc/ansible/group_vars/ -p
touch /etc/ansible/group_vars/all     #文件名自己定义,引用的时候注意

(3)在 roles 目录中分别创建以各角色名称命名的目录,如 httpd、mysql
mkdir /etc/ansible/roles/httpd
mkdir /etc/ansible/roles/mysql

(4)在每个角色命名的目录中分别创建files、handlers、tasks、templates、meta、defaults和vars目录,用不到的目录可以创建为空目录,也可以不创建
mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta}
mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta}

(5)在每个角色的 handlers、tasks、meta、defaults、vars 目录下创建 main.yml 文件,千万不能自定义文件名
touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml

(6)修改 site.yml 文件,针对不同主机去调用不同的角色
vim /etc/ansible/site.yml
---
- hosts: webservers
  remote_user: root
  roles:
     - httpd
- hosts: dbservers
  remote_user: root
  roles:
     - mysql
     
(7)运行 ansible-playbook
cd /etc/ansible
ansible-playbook site.yml


示例:
mkdir /etc/ansible/roles/httpd/{files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/mysql/{files,templates,tasks,handlers,vars,defaults,meta} -p
mkdir /etc/ansible/roles/php/{files,templates,tasks,handlers,vars,defaults,meta} -p

touch /etc/ansible/roles/httpd/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/mysql/{defaults,vars,tasks,meta,handlers}/main.yml
touch /etc/ansible/roles/php/{defaults,vars,tasks,meta,handlers}/main.yml

------编写httpd模块------
写一个简单的tasks/main.yml
vim /etc/ansible/roles/httpd/tasks/main.yml
- name: install apache
  yum: name={{pkg}} state=latest
- name: start apache
  service: enabled=true name={{svc}} state=started
 
//定义变量:可以定义在全局变量中,也可以定义在roles角色变量中,一般定义在角色变量中
vim /etc/ansible/roles/httpd/vars/main.yml
pkg: httpd
svc: httpd

-------编写mysql模块-------
vim /etc/ansible/roles/mysql/tasks/main.yml
- name: install mysql
  yum: name={{pkg}} state=latest
- name: start mysql
  service: enabled=true name={{svc}} state=started
  
vim /etc/ansible/roles/mysql/vars/main.yml
pkg:
  - mariadb
  - mariadb-server
svc: mariadb

-------编写php模块-----
vim /etc/ansible/roles/php/tasks/main.yml
- name: install php
  yum: name={{pkg}} state=latest
- name: start php-fpm
  service: enabled=true name={{svc}} state=started

vim /etc/ansible/roles/php/vars/main.yml
pkg:
  - php
  - php-fpm
svc: php-fpm

-----编写roles示例-----
vim /etc/ansible/site.yml
---
- hosts: webservers
  remote_user: root
  roles:
   - httpd
   - mysql
   - php


cd /etc/ansible
ansible-playbook site.yml


 

---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_items:
    - 1
    - 2
    - 3
    
    
---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_items: [ 1, 2, 3 ]
    
    
---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item.test1}}"
    with_items:
    - { test1: a, test2: b }
    - { test1: c, test2: d }


---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_items:
    - [ 1, 2, 3 ]
    - [ a, b ]


---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_list:
    - [ 1, 2, 3 ]
    - [ a, b ]


---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_flattened:
    - [ 1, 2, 3 ]
    - [ a, b ]


#with_list、with_items、with_flattened之间的区别:
在处理简单的单层列表时,他们没有区别,但是当处理嵌套的多层列表时,with_items与with_flattened会将嵌套列表”拉平展开”,循环的处理每个元素,而with_list只会处理最外层的列表,将最外层的列表中的每一项循环处理,loop可以替代with_list。


---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_together:
    - [ 1, 2, 3 ]
    - [ a, b, c ]

#with_together可以将两个列表中的元素”对齐合并”:
第一个小列表中的第1个值会与第二个小列表中的第1个值合并在一起输出,
第一个小列表中的第2个值会与第二个小列表中的第2个值合并在一起输出,
第一个小列表中的第3个值会与第二个小列表中的第3个值合并在一起输出,如果第二个小列表中的第3个元素没有值则输出null


---
- hosts: testB
  remote_user: root
  gather_facts: no
  tasks:
  - debug:
      msg: "{{item}}"
    with_cartesian:
    - [ a, b, c ]
    - [ test1, test2 ]

#with_cartesian的作用就是将每个小列表中的元素按照两两组合循环的处理每个组合,比如第一个小列表中的每个元素与第二个小列表中的每个元素都两两组合在了一起。
with_nested与with_cartesian的效果一致,可以无差别使用他们。


- hosts: testB
  remote_user: root
  gather_facts: no
  vars:
    test:
      - a
      - b
      - c  
    demo:
      - test1 
      - test2
  tasks:
  - debug:
      msg: "{{ item[0] }},{{ item[1] }}" 
    with_nested:             
    - "{{test}}"
    - "{{demo}}"
 

tasks任务 模块编写的格式
横向格式:
user: name=zhangsan  groups={{item}}

纵向格式:
user:
  name: zhangsan
  groups: "{{item}}"
  

with_items 的编写格式
横向格式:
值为纯量时
with_items: ["a", "b", "c"]

值为纯量对象时
with_items: 
- {key1: value1, key2: value2}
- {key1: value3, key2: value4}

纵向格式:
值为纯量时
with_items:
- a
- b
- c

值为纯量对象时
with_items: 
- key1: value1
  key2: value2
- key1: value3
  key2: value4


循环 迭代
with_items    with_flattened    with_list    loop
- a
- b
- c
在处理单层列表(每个列表只有一个元素)时,上面几个循环结构体是没有区别的,都会把每个列表的值遍历一遍

with_items    with_flattened    with_list    loop
- [a, b, c]
- [1, 2, 3]
- [A, B, C]
在处理嵌套的多层列表(每个列表只有多个元素)时,with_items 和 with_flattened 会将嵌套列表拉平扩展,将循环处理所有的元素
                        with_list 和 loop 不会嵌套列表拉平扩展,只会按照最外层的列表进行循环处理


with_together  将几个列表的元素对齐合并后输出,比如第一个列表的第一个元素和第二个列表的第一个元素合并输出
                                                   第一个列表的第二个元素和第二个列表的第二个元素合并输出

with_nested 和 with_cartesian 将每个列表的元素分别组合循环输出,比如 a1A a1B a1C  a2A a2B a2C ...


运行playbook
ansible-playbook XXX.yaml --syntax-check               检查剧本的语法是否正确
                          --list-task                  列出剧本里的所有任务
                          --list-hosts                 列出剧本在哪些主机执行
                          --start-at-task='任务名称'   指定从哪个任务开始执行

使用普通用户执行playbook
- remote_user: 普通用户  #远程主机需要事先sudo授权
  become: yes
  become_user: root
  
ansible-playbook XXX.yaml -k -K

定义/引用变量
- name:
  ...
  vars:
  - 变量1: 值1
  - 变量2: 值2
  - 变量3: 
    - key1: value1                     - {key1: value1, key2: value2}
      key2: value2                     - {key1: value3, key2: value4}
    - key1: value3
      key2: value4
  - 变量4:
    - 值1
    - 值2
    - 值3
  - 变量5: [值1, 值2, 值3]

   tasks:
   -name: xxxx
    模块: 参数选项1={{item}}
    with_items: "{{变量4}}"

 在tasks里引用变量时,可以从vars自定义的变量中引用,还可以直接引用 facts 字段的值,
                      还能 ansible-playbook -e "变量名=值" ,此方式优先级大于playbook中vars定义的变量的值

when条件判断
- name:
  ....
  tasks:
  - name: XXXX
    模块: ....
    when: 变量名   条件运算符   "值"             when判断结果为true才会执行当前任务,false不执行任务
                  == != >= <=

template模板模块
1)先要准备一个 xxx.j2 模板文件,在文件中使用 {{变量名}} 引用主机变量 或者 vars自定义的变量 及 facts 字段的值
2)在 playbook 中的 tasks 中定义 template 模板配置  template: src=XXX.j2  dest=XXX
                                                     

tags模块
根据 tags 标签仅执行拥有指定 tags 标签的任务,always 标签在指定任意标签时都会执行
- name:
  ....
  tasks:
  - name: XXXX
    模块:
    tags:
    - 标签1
    - 标签2
    
  - name: XXXX
    模块:
    tags:
    - always

ansible-playbook --tags="标签"  XXX.yaml


角色 roles 的作用?
把 playbook 里的各个 play 看作为角色,将各个角色的 tasks 任务、vars 变量、templates 模块、files 文件等内容放置到角色的目录中统一管理,需要的时候可在 playbook 中直接使用 roles 调用,所以 roles 可以实现代码的复用。

实验:用剧本写一个LNMP一键部署的集中式安装脚本

---
- name: Deploy LNMP Stack
  hosts: your_target_host   # 将目标主机的IP地址替换为你要部署的服务器IP
  gather_facts: yes

  vars:
    mysql_root_password: your_mysql_root_password   # 替换为你自己的MySQL root密码

  tasks:
    - name: Update apt cache and upgrade system packages
      apt:
        update_cache: yes
        upgrade: dist

    - name: Install necessary packages
      apt:
        name: "{{ item }}"
        state: present
      with_items:
        - nginx
        - mysql-server
        - php-fpm
        - php-mysql

    - name: Start and enable Nginx
      service:
        name: nginx
        state: started
        enabled: yes

    - name: Start and enable MySQL
      service:
        name: mysql
        state: started
        enabled: yes

    - name: Secure MySQL installation (optional, remove if not needed)
      expect:
        command: mysql_secure_installation
        responses:
          'Enter password for user root:': "{{ mysql_root_password }}"
          'Change the password for root ? ((Press y|Y for Yes, any other key for No) :': 'n'
          'Remove anonymous users? (Press y|Y for Yes, any other key for No) :': 'y'
          'Disallow root login remotely? (Press y|Y for Yes, any other key for No) :': 'y'
          'Remove test database and access to it? (Press y|Y for Yes, any other key for No) :': 'y'
          'Reload privilege tables now? (Press y|Y for Yes, any other key for No) :': 'y'
        timeout: 10

    - name: Start and enable PHP-FPM
      service:
        name: php7.4-fpm   # 如果使用的PHP版本不同,请根据实际情况更改
        state: started
        enabled: yes

    - name: Copy Nginx virtual host configuration
      template:
        src: nginx_vhost.conf.j2   # 替换为你的Nginx虚拟主机配置模板路径
        dest: /etc/nginx/sites-available/default
      notify:
        - Reload Nginx

    - name: Enable Nginx virtual host
      file:
        src: /etc/nginx/sites-available/default
        dest: /etc/nginx/sites-enabled/default
        state: link
      notify:
        - Reload Nginx

  handlers:
    - name: Reload Nginx
      service:
        name: nginx
        state: reloaded

创建一个名为nginx_vhost.conf.j2的Nginx虚拟主机配置模板文件,并将其与Playbook放在相同的目录下。

server {
    listen 80;
    server_name your_domain.com;   # 替换为你的域名

    root /var/www/html;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$args;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.4-fpm.sock;   # 如果使用的PHP版本不同,请根据实际情况更改
    }

    location ~ /\.ht {
        deny all;
    }
}

实验:用剧本写一个LNMP一键部署的分布式安装脚本

在分布式环境中,一键部署LNMP(Linux, Nginx, MySQL, PHP)可以使用Ansible来实现,假设有三台服务器:一台用作Nginx负载均衡器,两台用作Web服务器,并且所有服务器都已经完成了SSH连接配置。

---
- name: Deploy LNMP Stack
  hosts: all   # 包含负载均衡器和Web服务器的组名,可以在hosts文件中定义
  gather_facts: yes

  vars:
    mysql_root_password: your_mysql_root_password   # 替换为你自己的MySQL root密码

  tasks:
    - name: Update apt cache and upgrade system packages
      apt:
        update_cache: yes
        upgrade: dist

    - name: Install necessary packages
      apt:
        name: "{{ item }}"
        state: present
      with_items:
        - nginx
        - mysql-server
        - php-fpm
        - php-mysql

    - name: Start and enable Nginx
      service:
        name: nginx
        state: started
        enabled: yes

    - name: Start and enable MySQL
      service:
        name: mysql
        state: started
        enabled: yes

    - name: Secure MySQL installation (optional, remove if not needed)
      expect:
        command: mysql_secure_installation
        responses:
          'Enter password for user root:': "{{ mysql_root_password }}"
          'Change the password for root ? ((Press y|Y for Yes, any other key for No) :': 'n'
          'Remove anonymous users? (Press y|Y for Yes, any other key for No) :': 'y'
          'Disallow root login remotely? (Press y|Y for Yes, any other key for No) :': 'y'
          'Remove test database and access to it? (Press y|Y for Yes, any other key for No) :': 'y'
          'Reload privilege tables now? (Press y|Y for Yes, any other key for No) :': 'y'
        timeout: 10

    - name: Start and enable PHP-FPM
      service:
        name: php7.4-fpm   # 如果使用的PHP版本不同,请根据实际情况更改
        state: started
        enabled: yes

    - name: Copy Nginx virtual host configuration for Web servers
      template:
        src: nginx_web_vhost.conf.j2   # 替换为你的Nginx虚拟主机配置模板路径
        dest: /etc/nginx/sites-available/default
      notify:
        - Reload Nginx

    - name: Enable Nginx virtual host for Web servers
      file:
        src: /etc/nginx/sites-available/default
        dest: /etc/nginx/sites-enabled/default
        state: link
      notify:
        - Reload Nginx

  handlers:
    - name: Reload Nginx
      service:
        name: nginx
        state: reloaded

负载均衡器和Web服务器已经定义在Ansible的hosts文件中,并根据实际情况设置了适当的组名。此外,我们假设在nginx_web_vhost.conf.j2模板文件中定义了适用于Web服务器的Nginx虚拟主机配置。



实验 用role 编写一个LNMP 集中部署脚本

下面是一个以角色的方式编写的LNMP(Linux + Nginx + MySQL + PHP)集中部署的Ansible Playbook。我们将把LNMP的各个组件拆分为不同的角色,使配置和维护更加清晰和模块化。

首先,我们需要创建一个名为`lnmp`的角色,然后在该角色中分别创建`nginx`、`mysql`和`php`子角色。在每个子角色中,我们将定义安装和配置相应组件的任务。

1. 创建目录结构:

首先,在Ansible项目的`roles`目录下,创建`lnmp`角色目录结构:

```
roles/
└── lnmp
    ├── tasks
    │   ├── main.yml
    │   ├── nginx.yml
    │   ├── mysql.yml
    │   └── php.yml
    └── vars
        └── main.yml
```

2. 定义`lnmp`角色的`main.yml`:

roles/lnmp/tasks/main.yml:
```yaml
---
# 导入子角色

- import_tasks: nginx.yml
- import_tasks: mysql.yml
- import_tasks: php.yml


```

3. 定义`nginx`子角色的`nginx.yml`:roles/lnmp/tasks/nginx.yml:
```yaml
---

# 安装Nginx

# 启动并开机自启Nginx服务
- name: Start Nginx service
  service:
    name: nginx
    state: started
    enabled: yes

# 复制Nginx配置文件
- name: Copy Nginx configuration
  template:
    src: nginx.conf.j2
    dest: /etc/nginx/nginx.conf
  notify:
    - restart nginx
```

roles/lnmp/vars/main.yml:
```yaml
---

# 定义Nginx配置文件的模板
nginx_config_template: |
  user nginx;
  worker_processes auto;
  error_log /var/log/nginx/error.log;
  pid /run/nginx.pid;

  events {
      worker_connections 1024;
  }

  http {
      include /etc/nginx/mime.types;
      default_type application/octet-stream;

      log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '"$http_user_agent" "$http_x_forwarded_for"';

      access_log  /var/log/nginx/access.log  main;

      sendfile on;
      tcp_nopush on;
      tcp_nodelay on;

      keepalive_timeout 65;

      gzip on;
      gzip_disable "msie6";

      include /etc/nginx/conf.d/*.conf;
  }


```

4. 定义`mysql`子角色的`mysql.yml`:roles/lnmp/tasks/mysql.yml:
```yaml
---

# 安装MySQL
- name: Install MySQL
  package:
    name: mysql-server
    state: present

# 启动并开机自启MySQL服务
- name: Start MySQL service
  service:
    name: mysqld
    state: started
    enabled: yes

# 设置MySQL root密码
- name: Set MySQL root password
  mysql_user:
    name: root
    password: "your_mysql_root_password"
    login_user: root
    login_password: ""


```

5. 定义`php`子角色的`php.yml`:roles/lnmp/tasks/php.yml:
```yaml
---

# 安装PHP及相关组件
- name: Install PHP and related packages
  package:
    name:
      - php
      - php-fpm
      - php-mysql
      - php-mbstring
      - php-xml
    state: present

# 启动并开机自启PHP-FPM服务
- name: Start PHP-FPM service
  service:
    name: php-fpm
    state: started
    enabled: yes


```

6. 定义Nginx的配置文件模板`nginx.conf.j2`:

roles/lnmp/templates/nginx.conf.j2:
```nginx

{{ nginx_config_template }}


```

然后,你可以在主Playbook中调用`lnmp`角色,指定目标主机,以完成LNMP集中部署。```yaml
---

- name: Deploy LNMP stack
  hosts: your_target_hosts
  become: yes

  roles:
    - lnmp


```

请注意,上述Playbook和角色的示例只是一个基本的模板,实际情况可能更复杂,并需要根据你的具体需求进行适当的调整和配置。同时,确保根据实际情况修改MySQL的root密码,并为Nginx和PHP添加更多配置。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值