30.Ansible的判断、循环语句和条件运算

数据库的一个错误

image-20200613172058065

数据库有密码,想要操作数据库,得先连接数据库(登录数据库)
login_user: root
login_password: '123'
login_host: localhost
login_port: 3306

判断语句

使用: when

## 根据系统判断

- hosts: web_group
  tasks:
    - name: Install CentOS Httpd
      yum:
        name: httpd
        state: present
      when: ansible_distribution == "CentOS"

    - name: Install Ubuntu Httpd
      yum:
        name: apache2
        state: present
      when: ansible_facts['os_family'] == "Ubuntu"

Ansible判断官方文档:TP

- hosts: all
  tasks:
    - name: Install Rsync Server
      yum:
        name: rsync
        state: present
      when: ansible_fqdn == 'backup' or ansible_fqdn == 'nfs'

    - name: Configure Rsync Conf
      copy:
        src: /root/ansible/rsync/rsyncd.conf
        dest: /etc/rsyncd.conf
      when: ansible_fqdn == 'backup'

    - name: Install Nginx
      yum:
        name: nginx
        state: present
      when: ansible_fqdn is match 'web*'

也可以指定多条件为列表

tasks:
  - name: "shut down CentOS 6 systems"
    command: /sbin/shutdown -t now
    when:
      - ansible_facts['distribution'] == "CentOS"
      - ansible_facts['distribution_major_version'] == "6"

条件运算

tasks:
  - shell: echo "only on Red Hat 6, derivatives, and later"
    when: ansible_facts['os_family'] == "RedHat" and ansible_facts['lsb']['major_release']|int >= 6

通过register将命令执行结果保存至变量,然后通过when语句进行判断

- hosts: web_group
  tasks:
    - name: Check Httpd Server
      command: systemctl is-active httpd
      ignore_errors: yes
      register: check_httpd

    - name: debug outprint
      debug: var=check_httpd

    - name: Httpd Restart
      service:
        name: httpd
        state: restarted
      when: check_httpd.rc == 0

循环语句

# 启动多个服务
- hosts: web_group
  tasks:
    - name: start service
      systemd:
        name: "{{ item }}"
        state: started
      with_items:
        - httpd
        - php-fpm
        - mariadb


## 字典循环

# 创建用户
[root@m01 ~]# cat loop.yml
- hosts: web_group
  tasks:
    - name: Add Users
      user:
        name: "{{ item.name }}"
        groups: "{{ item.groups }}"
        state: present
      with_items:
        - { name: 'zls', groups: 'linux' }
        - { name: 'egon', groups: 'python' }
        
   
# 拷贝文件
- hosts: web_group
  tasks:
    - name: copy conf and code
      copy:
        src: "{{ item.src }}"
        dest: "{{ item.dest }}"
        mode: "{{ item.mode }}"
      with_items:
        - { src: "./httpd.conf", dest: "/etc/httpd/conf/", mode: "0644" }
        - { src: "./upload_file.php", dest: "/var/www/html/", mode: "0600" }

作业

环境准备

主机名 wanIP lanIP 安装的服务 角色
web01 10.0.0.7 172.16.1.7 nginx,php web
web02 10.0.0.8 172.16.1.8 nginx,php web
nfs 10.0.0.31 172.16.1.31 nfs,rsync 共享存储
backup 10.0.0.41 172.16.1.41 rsync 备份机
db01 10.0.0.51 172.16.1.51 mariadb-server 数据库
m01 10.0.0.61 172.16.1.61 ansible 管理机

导数据库

# 之前准备好项目导出来
# 导出数据库
[root@db01 ~]# mysql -B wp > /root/wp.sql
# 打包项目
[root@db01 ~]# tar zcf wordpress.tgz wordpress

# 把之前图片的文件目录发出来,等挂载好了在移动回去,不然挂载以后之前的图片就没了
[root@web01 /code/wordpress/wp-content/uploads]# rsync -az 2020 172.16.1.61:/root/ansible/mysql

剧本准备前

# ping通其他主机
#!/bin/bash
for i in 7 8 31 41 51 61;do
        sshpass -p 1 ssh-copy-id -i ~/.ssh/id_rsa.pub -o StrictHostKeyChecking=no [email protected].$i
done

# 编辑主机清单
[root@m01 ~]# vim /etc/ansible/hosts

[webs]
web01 ansible_ssh_host=172.16.1.7
web02 ansible_ssh_host=172.16.1.8

[nfss]
nfs ansible_ssh_host=172.16.1.31

[backups]
backup ansible_ssh_host=172.16.1.41

[mariadb]
db01 ansible_ssh_host=172.16.1.51

[install_nfs:children]
webs
nfss

[install_rsyncd:children]
nfss
backups


# 创建项目目录
[root@m01 ~]# mkdir ansible/{group_vars,host_vars,mysql,nfs,nginx,rsync} -p

# 准备好一下配置文件和脚本   (变量在下面)
[root@m01 ~/ansible]# tree
.
├── group_vars                                   # 变量
│   ├── all
│   ├── install_nfs
│   ├── install_rsyncd
│   └── webs
├── host_vars
│   ├── backup
│   ├── db01
│   ├── nfs
│   ├── web01
│   └── web02
├── lnmp.yml                                     # 剧本
├── mysql                                        # 之前数据库的图片                                    
│   ├── 2020
│   │   └── 06
│   │       ├── yyy-150x150.jpg
│   │       ├── yyy-213x300.jpg
│   │       └── yyy.jpg
│   ├── wordpress.tgz                             # 之前的项目包
│   └── wp.sql                                    # 之前的数据库
├── nfs
│   └── beifen.sh                                 # 备份脚本
├── nginx
│   ├── nginx.conf                                # nginx配置文件
│   ├── nginx_php.tgz                             # nginx和php的rpm包 
│   ├── QQ.zip                                    # 主题 可以不要因为之前有了
│   ├── wp.conf                                   # nginx配置文件
│   └── www.conf                                  # php主配置文件
└── rsync
    └── rsyncd.conf                               # rsync配置文件



# 准备php和nginx配置文件
...
# 准备rsync的配置文件
[root@m01 ~]# vim ansible/rsyncd.conf 

uid = www
gid = www
port = 873
fake super = yes
use chroot = no
max connections = 200
timeout = 600
ignore errors
read only = false
list = false
log file = /var/log/rsyncd.log
auth users = jkz_bak
secrets file = /etc/rsync_pass
[jkz]
comment = welcome to oldboyedu backup!
path = /backup


### 准备脚本
[root@m01 ~]# vim beifen.sh 
#!/usr/bin/bash
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/root/bin
Host=$(hostname)
Addr=$(ifconfig eth1|awk 'NR==2{print $2}')
Date=$(date +%F)
Dest=${Host}_${Addr}_${Date}
Path=/data
#2.创建备份目录
[ -d $Path/$Dest ] || mkdir -p $Path/$Dest
#3.备份对应的文件
cd / && \
[ -f $Path/$Dest/system.tar.gz ] || tar czf $Path/$Dest/system.tar.gz etc/fstab etc/rsyncd.conf && \
[ -f $Path/$Dest/log.tar.gz ] || tar czf $Path/$Dest/log.tar.gz  var/log/messages var/log/secure && \
#4.携带md5验证信息
[ -f $Path/$Dest/flag ] || md5sum $Path/$Dest/*.tar.gz >$Path/$Dest/flag_$Date
#5.推送本地数据至备份服务器
export RSYNC_PASSWORD=111
rsync -avz $Path/ [email protected]::jkz
#6.本地保留最近7天的数据
find $Path/ -type d -mtime +7|xargs rm -rf



# 编写nginx配置文件
[root@m01 ~/ansible/nginx]# vim wp.conf
server {
        listen 80;
        server_name wp.com;
        root /code/wordpress;
        index index.php;

        location ~ \.php$ {
                fastcgi_pass 127.0.0.1:9000;
                fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
                include fastcgi_params;
        }
}



## 域名解析

设置变量

# 设置变量
[root@m01 ~/ansible]# vim group_vars/all 
all_user: www

[root@m01 ~/ansible]# vim group_vars/install_nfs 
down: nfs-utils

[root@m01 ~/ansible]# vim group_vars/install_rsyncd 
down: rsync

[root@m01 ~/ansible]# vim group_vars/webs 

  - m4-1.4.16-10.el7.x86_64.rpm
  - mod_php71w-7.1.33-1.w7.x86_64.rpm
  - nginx-1.18.0-1.el7.ngx.x86_64.rpm
  - pcre-devel-8.32-17.el7.x86_64.rpm
  - perl-Data-Dumper-2.145-3.el7.x86_64.rpm
  - perl-Test-Harness-3.28-3.el7.noarch.rpm
  - perl-Thread-Queue-3.02-2.el7.noarch.rpm
  - php71w-cli-7.1.33-1.w7.x86_64.rpm
  - php71w-common-7.1.33-1.w7.x86_64.rpm
  - php71w-devel-7.1.33-1.w7.x86_64.rpm
  - php71w-embedded-7.1.33-1.w7.x86_64.rpm
  - php71w-fpm-7.1.33-1.w7.x86_64.rpm
  - php71w-gd-7.1.33-1.w7.x86_64.rpm
  - php71w-mbstring-7.1.33-1.w7.x86_64.rpm
  - php71w-mcrypt-7.1.33-1.w7.x86_64.rpm
  - php71w-mysqlnd-7.1.33-1.w7.x86_64.rpm
  - php71w-opcache-7.1.33-1.w7.x86_64.rpm
  - php71w-pdo-7.1.33-1.w7.x86_64.rpm
  - php71w-pear-1.10.4-1.w7.noarch.rpm
  - php71w-pecl-igbinary-2.0.5-1.w7.x86_64.rpm
  - php71w-pecl-memcached-3.0.4-1.w7.x86_64.rpm
  - php71w-pecl-mongodb-1.5.3-1.w7.x86_64.rpm
  - php71w-pecl-redis-3.1.6-1.w7.x86_64.rpm
  - php71w-process-7.1.33-1.w7.x86_64.rpm
  - php71w-xml-7.1.33-1.w7.x86_64.rpm

tuisong:
  - { src: '/root/ansible/nginx/nginx.conf' , dest: '/etc/nginx/nginx.conf' }
  - { src: '/root/ansible/nginx/wp.conf' , dest: '/etc/nginx/conf.d/wp.conf' }
  - { src: '/root/ansible/nginx/www.conf' , dest: '/etc/php-fpm.d/www.conf' }

servers:
  - nginx
  - php-fpm
  - nfs
file: code



[root@m01 ~/ansible]# vim host_vars/backup 
file: backup
tuisong:
  - { src: '/root/ansible/rsync/rsyncd.conf' , dest: '/etc/rsyncd.conf'  }
servers:
  - rsyncd


[root@m01 ~/ansible]# vim host_vars/db01 
down:
  - mariadb-server
  - MySQL-python
servers:
  - mariadb
tuisong:
  - { src: '/root/ansible/mysql/wp.sql' , dest: '/tmp/wp.sql'  }


[root@m01 ~/ansible]# vim host_vars/nfs 
file: data
servers:
  - nfs

tuisong:
  - { src: '/root/ansible/nfs/beifen.sh' , dest: '/root/beifen.sh' }


编写剧本

[root@m01 ~/ansible]# cat lnmp.yml 

- hosts: all
  tasks:
    - name: start firewalld
      service:
        name: firewalld
        state: started

    - name: disabled selinux
      selinux:
        state: disabled

    - name: open port
      firewalld:
        port: "{{ item }}"
        permanent: no
        state: enabled
      with_items:
        - 443/tcp
        - 80/tcp
        - 873/tcp
        - 3306/tcp

    - name: open nfs
      firewalld:
        service: nfs
        permanent: no
        state: enabled
      when: ansible_fqdn == 'nfs' or ansible_fqdn is match 'web*'

# 创建用户和用户组
    - name: create zu
      group:
        name: '{{ all_user }}'
        gid: 666

    - name: create user
      user:
        name: '{{ all_user }}'
        uid: 666
        group: '{{ all_user }}'
        shell: /sbin/nologin
        create_home: no

# 创建各种目录
    - name: create file
      file:
        path: /{{ file }}
        state: directory
        owner: '{{ all_user }}'
        group: '{{ all_user }}'
      when: ansible_fqdn == 'nfs' or ansible_fqdn == 'backup' or ansible_fqdn is match 'web*'

# 下载各种rpm 
    - name: yum mariadb,nfs,rsync
      yum:
        name: '{{ down }}'
        state: present

# 解压nginx_php的包到web上
    - name: jieya
      unarchive:
        src: '{{ item.src }}'
        dest: '{{ item.dest }}'
        owner: '{{ all_user }}'
        group: '{{ all_user }}'
      with_items:
        - { src: '/root/ansible/mysql/wordpress.tgz' , dest: '/code/' }
  #      - { src: '/root/ansible/nginx/QQ.zip' , dest: '/code/wordpress/wp-content/themes/' }
        - { src: '/root/ansible/nginx/nginx_php.tgz' , dest: '/root/' }
      when: ansible_fqdn is match 'web*'

# 安装
    - name: anzhuang
      yum:
        name: '/root/nginx_php/{{ item }}'
        state: present
      with_items: '{{ nginx_php }}'
      when: ansible_fqdn is match 'web*'

# 推送各种文件
    - name: tuisongpeizhiwenjian
      copy:
        src: '{{ item.src }}'
        dest: '{{ item.dest }}'
      with_items: '{{ tuisong }}'

# 创建rsync密码文件
    - name: chaungjianmimawenjian
      copy:
        content: jkz_bak:111
        dest: /etc/rsync_pass
        mode: 0600
      when: ansible_fqdn == 'backup'
      
# 设置nfs的配置文件
    - name: chuangjian nfs
      copy:
        content: /data 172.16.1.0/24(sync,rw,all_squash,anonuid=666,anongid=666)
        dest: /etc/exports
      when: ansible_fqdn == 'nfs'

# 启动各种服务
    - name: start servers
      service:
        name: '{{ item }}'
        state: started
        enabled: yes
      with_items: '{{ servers }}'

# 挂载web上的共享目录
    - name: mount uploads
      mount:
        src: 172.16.1.31:/data
        path: /code/wordpress/wp-content/uploads
        fstype: nfs
        state: mounted
      when: ansible_fqdn is match 'web*'

# 推回之前数据库的图片
    - name: chuangjian nfs
      copy:
        src: /root/ansible/mysql/2020
        dest: /code/wordpress/wp-content/uploads
      when: ansible_fqdn is match 'web*'

# 创建数据库用户
    - name: chuangjianyonghu
      mysql_user:
        name: php
        host: '%'
        password: '111'
        priv: '*.*:ALL'
        state: present
      when: ansible_fqdn == 'db01'

    - name: chuanjianshujk
      mysql_db:
        name: wp
        state: present
      when: ansible_fqdn == 'db01'
#  导入数据库
    - name: daorusujuku
      mysql_db:
      #  login_user: 'root'
      #  login_password: '111'
      #  login_host: 'localhost'
        state: import
        name: wp
        target: /tmp/wp.sql
      when: ansible_fqdn == 'db01'

# nfs定时执行脚本
    - name: dingshirenwu
      cron:
        name: dingshibeif
        job: /bin/sh /root/beifen.sh
      when: ansible_fqdn == 'nfs'

登入网站查看

image-20200613190528329

image-20200613190914123

猜你喜欢

转载自www.cnblogs.com/jkz1/p/13170857.html
今日推荐