68-ansible实验总结

实验列表

  • 环境准备
  • 实验准备
  • 实验开始
  • 剧本
  • 部署httpd
  • 变量使用
  • 条件判断
  • 模块化安装httpd
  • 点击跳至文章末尾


环境准备

默认所有虚拟机已关闭防火墙、关闭SELINUX、时间同步
虚拟机三台:

主机版本 主/被 主机IP 主机名
CentOS 7 主控端 192.168.124.5 C7
CentOS 7 被控端 192.168.124.13 C7-3
CentOS 7 被控端 192.168.124.14 C7-4

实验准备

#在主控端 主机C7上操作:
#安装ansible
[root@C7 ~]# yum install ansible
Loaded plugins: fastestmirror, langpacks
Loading mirror speeds from cached hostfile
 * base: mirrors.neusoft.edu.cn
 * extras: mirrors.aliyun.com
 * updates: mirrors.neusoft.edu.cn
No package ansible available.
Error: Nothing to do

#很显然,我们的光盘仓库中缺失ansible相关依赖包
#搜索一下epel并添加epel源
[root@C7 ~]# yum list | grep epel-release
epel-release.noarch                         7-11                       extras   
[root@C7 ~]# yum install epel-release -y

#这次安装成功
[root@C7 ~]# yum install ansible
……………
Total download size: 20 M
Installed size: 114 M
Is this ok [y/d/N]: y
…………
Installed:
  ansible.noarch 0:2.9.9-1.el7                                                                                                      

Dependency Installed:
  python-babel.noarch 0:0.9.6-8.el7           python-httplib2.noarch 0:0.9.2-1.el7      python-jinja2.noarch 0:2.7.2-4.el7        
  python-markupsafe.x86_64 0:0.11-10.el7      python-paramiko.noarch 0:2.1.1-9.el7      python2-jmespath.noarch 0:0.9.4-2.el7     
  sshpass.x86_64 0:1.06-2.el7                

Complete!


#在继续实验之前我们需要提前配置好远程被控主机的免密钥登录
#全部直接回车直到结束
[root@C7-3 ~]# ssh-keygen -t rsa -C "ansible@linux"
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:KLIoqlICPAnj9JYIHr5opUN8gH4gnziRF56LlxFyweQ ansible@linux
The key's randomart image is:
+---[RSA 2048]----+
|o+*o             |
|OXoo             |
|%*E..            |
|+&o@   .         |
|=.& . . S        |
|oB.o .           |
|+oo              |
|+                |
|=                |
+----[SHA256]-----+
#这里的 id_rsa 为私钥文件,id_rsa.pub 为公钥文件
#特别注意:.ssh目录的权限需是700
[root@C7-3 ~]# ll /root/.ssh/
total 8
-rw------- 1 root root 1675 Jun  2 17:21 id_rsa
-rw-r--r-- 1 root root  395 Jun  2 17:21 id_rsa.pub

[root@C7 ~]# cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
[root@C7 ~]# ll /root/.ssh/
total 16
-rw-r--r-- 1 root root  395 Jun  3 08:39 authorized_keys
-rw------- 1 root root 1675 Jun  2 17:15 id_rsa
-rw-r--r-- 1 root root  395 Jun  3 08:39 id_rsa.pub

#当前登录远程被控主机提示需要输入密码
[root@C7 ~]# ssh 192.168.124.13
[email protected]'s password: 


#将authorized_keys 文件发送到另外两台被控主机
#中间输入yes;密码输入被控主机的root密钥
[root@C7 ~]# scp /root/.ssh/authorized_keys 192.168.124.13:/root/.ssh/
The authenticity of host '192.168.124.13 (192.168.124.13)' can't be established.
ECDSA key fingerprint is SHA256:Qqm+M0hyyYv59HC4ibs/tKiKpM4TIO7HqrZmDJoGWrs.
ECDSA key fingerprint is MD5:66:0c:de:ae:d5:6a:99:77:2f:f3:f0:20:a7:73:30:1a.
Are you sure you want to continue connecting (yes/no)? yes     #输入yes
Warning: Permanently added '192.168.124.13' (ECDSA) to the list of known hosts.
[email protected]'s password:       #输入被控主机的root密钥
authorized_keys                                                                                        100%  395   121.4KB/s   00:00    

[root@C7 ~]# scp /root/.ssh/authorized_keys 192.168.124.14:/root/.ssh/
The authenticity of host '192.168.124.14 (192.168.124.14)' can't be established.
ECDSA key fingerprint is SHA256:Qqm+M0hyyYv59HC4ibs/tKiKpM4TIO7HqrZmDJoGWrs.
ECDSA key fingerprint is MD5:66:0c:de:ae:d5:6a:99:77:2f:f3:f0:20:a7:73:30:1a.
Are you sure you want to continue connecting (yes/no)? yes     #输入yes
Warning: Permanently added '192.168.124.14' (ECDSA) to the list of known hosts.
[email protected]'s password:        #输入被控主机的root密钥
authorized_keys                                                                                        100%  395   212.5KB/s   00:00    


#现在我们来尝试以下是否可以在主控端远程免密钥登录两台被控主机
[root@C7 ~]# ssh 192.168.124.13
Last login: Tue Jun  2 17:19:57 2020 from 192.168.124.5
[root@C7-3 ~]# exit
logout
Connection to 192.168.124.13 closed.

[root@C7 ~]# ssh 192.168.124.14
Last login: Tue Jun  2 16:14:35 2020 from 192.168.124.1
[root@C7-4 ~]# exit
logout
Connection to 192.168.124.14 closed.
#如果你觉得输入主机IP 进行远程连接过于麻烦,你可以在主控端的 /etc/hosts 文件中配置IP解析
[root@C7 ~]# vim /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
#追加以下两行就行了
192.168.124.13 C7-3
192.168.124.14 C7-4

[root@C7 ~]# ssh C7-3
The authenticity of host 'c7-3 (192.168.124.13)' can't be established.
ECDSA key fingerprint is SHA256:Qqm+M0hyyYv59HC4ibs/tKiKpM4TIO7HqrZmDJoGWrs.
ECDSA key fingerprint is MD5:66:0c:de:ae:d5:6a:99:77:2f:f3:f0:20:a7:73:30:1a.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'c7-3' (ECDSA) to the list of known hosts.
Last login: Tue Jun  2 17:32:53 2020 from 192.168.124.5
[root@C7-3 ~]# exit
logout
Connection to c7-3 closed.

[root@C7 ~]# ssh C7-4
The authenticity of host 'c7-4 (192.168.124.14)' can't be established.
ECDSA key fingerprint is SHA256:Qqm+M0hyyYv59HC4ibs/tKiKpM4TIO7HqrZmDJoGWrs.
ECDSA key fingerprint is MD5:66:0c:de:ae:d5:6a:99:77:2f:f3:f0:20:a7:73:30:1a.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'c7-4' (ECDSA) to the list of known hosts.
Last login: Tue Jun  2 17:33:05 2020 from 192.168.124.5
[root@C7-4 ~]# exit
logout
Connection to c7-4 closed.


#觉得手动操作有些不够逼格呢?这里提供参考脚本
#利用 sshpass 批量实现基于 key 验证
#!/bin/bash
ssh-keygen -f /root/.ssh/id_rsa  -P ''
NET=192.168.124
export SSHPASS=linux
for IP in {10..20}; do
    sshpass -e ssh-copy-id  ${NET}.${IP}
done

建议从此刻状态对所有主机创建虚拟机快照


实验开始

#终于可以配置ansible了,前期工作基本就是这些
#ansible有三个重要的文件,在yum安装下文件默认在:/etc/ansible/ 下
[root@C7 ~]# ls /etc/ansible/
ansible.cfg  hosts  roles

#ansible.cfg 毫无疑问这是ansible的主配置文件
#hosts 远程控制主机清单
#roles 存放角色的目录

#配置hosts文件
[root@C7 ~]# vim /etc/ansible/hosts 
#随便找个位置写即可

[srvs]    # []中的英文尽量写的好记一点,因为后面的终端中要输入
192.168.124.13    #被控主机IP
192.168.124.14    #被控主机IP

#查看被ansible管理的所有主机列表
[root@C7 ~]# ansible srvs --list
  hosts (2):
    192.168.124.13
    192.168.124.14

#测试一下被管理的主机能否ping通
[root@C7 ~]# ansible all -m ping
192.168.124.14 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.124.13 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

#你是否想过:倘若这里管理的主机多达100台,是否我就必须写100行主机IP呢?
#当然不必如此,对于被管理主机非常多的情况下,我们有另一种写法
[root@C7 ~]# vim /etc/ansible/hosts 
#将前面两台主机IP注释掉,添加新行

[srvs]
#192.168.124.13    #被控主机IP
#192.168.124.14    #被控主机IP
192.168.124.[10:20]    #表示10到20的主机IP

#重新查看被ansible管理的所有主机列表
[root@C7 ~]# ansible srvs --list
  hosts (11):
    192.168.124.10
    192.168.124.11
…………..#省略不写
    192.168.124.19
    192.168.124.20

#当然,我这里仅部署了两台被控主机,若此时测试所有主机能否ping通,其余18台主机是不通的
#不仅这些主机ping不通,其ping的过程也并不是按照主机IP顺序进行的
[root@C7 ~]# ansible all -m ping
192.168.124.10 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.124.10 port 22: Connection refused", 
    "unreachable": true
}
192.168.124.14 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.124.13 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.124.11 | UNREACHABLE! => {
    "changed": false, 
    "msg": "Failed to connect to the host via ssh: ssh: connect to host 192.168.124.11 port 22: No route to host", 
    "unreachable": true
}

#为了试验正常进行,还是把hosts主机清单改回来吧

#ansible中拥有非常多的模块,通过这些模块能够帮助我们完成及减少工作当中一些繁琐重复的内容
#例举ansible常用模块:篇幅有限这里仅做例举而不进行详细说明
#若你对此很感兴趣的话,这里提供详细博客链接:点击跳转
Command 模块;Shell 模块;Script 模块;Copy 模块;Fetch 模块;File 模;
unarchive 模块;Archive 模块;Hostname 模块;Cron 模块;Yum 模块;
Service 模块;User 模块;Group 模块;Setup 模块;
#倘若你对这些如此多的模块感到非常迷茫,那么使用ansible-doc是个办法
#其作用是ansible-doc +指定模块 查看该模块的帮助信息

#例如yum模块
[root@C7 ~]# ansible-doc yum
> YUM    (/usr/lib/python2.7/site-packages/ansible/modules/packaging/os/yum.py)

        Installs, upgrade, downgrades, removes, and lists packages and groups with the `yum‘ package
        manager. This module only works on Python 2. If you require Python 3 support see the [dnf]
        module.

  * This module is maintained by The Ansible Core Team
  * note: This module has a corresponding action plugin.
………

#若后面跟 --list 或 -l 则可以查看所有支持的ansible模块
[root@C7 ~]# ansible-doc --list
fortios_router_community_list                                 Configure community lists in Fortinet's FortiOS and FortiGate    
azure_rm_devtestlab_info                                      Get Azure DevTest Lab facts  
……….

剧本

#ansible中有一个非常重要的组成部分,那就是Playbook(剧本)
#通过剧本我们可以实现一次同时部署多台主机
#playbook由YAML语法构成,文件首行固定为 ---,且对缩进有严格要求,敏感大小写
#一个完整的代码块最少包括name和task,且一个name只能包含一个task
#YAML文件扩展名通常为yml或yaml

#尝试编写一个简单的剧本
[root@C7 ~]# mkdir /etc/ansible/roles/playbook
[root@C7 ~]# vim !$/hi.yml
---
- hosts: srvs
  tasks:
    - name: test
      shell: /bin/echo "Hi,I'm `who am i`" > /data/hi.txt

#编辑结束应进行运行测试,是否有语法错误
#俗称干跑,而不进行实际操作
[root@C7 ~]# ansible-playbook --check -C /etc/ansible/roles/playbook/hi.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [test] ************************************************************************************************************************
skipping: [192.168.124.13]
skipping: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

#现在进行真正执行操作
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/hi.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [test] ************************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
#执行完,我们是否可以在本机查看远程被控主机的文件内容呢?
[root@C7 ~]# ansible all -a "cat /data/hi.txt"
192.168.124.14 | CHANGED | rc=0 >>
Hi,I'm root     pts/3        2020-06-03 09:23 (192.168.124.5)
192.168.124.13 | CHANGED | rc=0 >>
Hi,I'm root     pts/3        2020-06-03 09:23 (192.168.124.5)

#很明显可以直接看到内容,那么如果我只想在某一台主机上执行刚才的yml文件呢?
#略微修改一下之前的yml文件内容以作区分
[root@C7 ~]# vim /etc/ansible/roles/playbook/hi.yml
---
- hosts: srvs
  tasks:
    - name: test
      shell: /bin/echo "You can see !" > /data/see.txt


#这次我就不干跑测试了,直接运行
#这次我们只对C7-3主机执行操作
[root@C7 ~]# ansible-playbook --limit 192.168.124.13 /etc/ansible/roles/playbook/hi.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]

TASK [test] ************************************************************************************************************************
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看执行后,远程主机C7-3上的文件内容
#注意,命令参数有顺序要求
[root@C7 ~]# ansible -a 192.168.124.13 "cat /data/see.txt"
[WARNING]: Could not match supplied host pattern, ignoring: cat
[WARNING]: Could not match supplied host pattern, ignoring: /data/see.txt
[WARNING]: No hosts matched, nothing to do

[root@C7 ~]# ansible 192.168.124.13 -a "cat /data/see.txt"
192.168.124.13 | CHANGED | rc=0 >>
You can see !

#很显然我只是把 -a参数写在了前面,但这样会导致命令执行失败

部署httpd

#让我们更近一步,尝试使用ansible-playbook 来完成远程主机的httpd服务的部署
#在部署远程主机httpd服务之前,首先我们要在主控端安装httpd

[root@C7 ~]# yum -y install httpd
[root@C7 ~]# cp /etc/httpd/conf/httpd.conf /etc/ansible/roles/playbook/

[root@C7 ~]# vim /etc/ansible/roles/playbook/index.html
If you can see,that‘s good!


#编写httpd_install.yml  playbook脚本
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: install httpd
      yum: name=httpd
    - name: config httpd service
      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html
    - name: manage httpd service
      service: name=httpd state=started enabled=yes

#在C7-3主机上进行干跑测试
[root@C7 ~]# ansible-playbook --check --limit 192.168.124.13 -C /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]

TASK [install httpd] ***************************************************************************************************************
ok: [192.168.124.13]

TASK [config httpd service] ********************************************************************************************************
ok: [192.168.124.13]

TASK [copy default index.html] *****************************************************************************************************
changed: [192.168.124.13]

TASK [manage httpd service] ********************************************************************************************************
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   



#显示无报错,在C7-3被控主机真正运行操作
[root@C7 ~]# ansible-playbook --limit 192.168.124.13 /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]

TASK [install httpd] ***************************************************************************************************************
ok: [192.168.124.13]

TASK [config httpd service] ********************************************************************************************************
ok: [192.168.124.13]

TASK [copy default index.html] *****************************************************************************************************
changed: [192.168.124.13]

TASK [manage httpd service] ********************************************************************************************************
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#访问C7-3 httpd页面
[root@C7 ~]# curl 192.168.124.13:80
If you can see,that's good!

#查看C7-3 httpd监听端口
[root@C7 ~]# ansible 192.168.124.13 -a "ss -ntul"
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:80                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  

#查看所有主机 httpd监听端口使用 ansible all -a "ss -ntul"
#编写notify 和handlers 实现修改配置文件后触发httpd 服务重启
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: install httpd
      yum: name=httpd
    - name: config httpd service
      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
      notify: restart httpd service        #新行
    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html
    - name: manage httpd service
      service: name=httpd state=started enabled=yes
  handlers:                                #新行
    - name: restart httpd service          #新行
      service: name=httpd state=restarted  #新行

#顺便把httpd 服务端口改了
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd.conf
#Listen 80
Listen 88

#任何时候都不要忘记测试
[root@C7 ~]# ansible-playbook --check -C /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [install httpd] ***************************************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [config httpd service] ********************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [copy default index.html] *****************************************************************************************************
changed: [192.168.124.14]
ok: [192.168.124.13]

TASK [manage httpd service] ********************************************************************************************************
changed: [192.168.124.14]
ok: [192.168.124.13]

RUNNING HANDLER [restart httpd service] ********************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#测试无误后,在所有被控主机上执行操作
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [install httpd] ***************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ********************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [copy default index.html] *****************************************************************************************************
changed: [192.168.124.14]
ok: [192.168.124.13]

TASK [manage httpd service] ********************************************************************************************************
ok: [192.168.124.13]
changed: [192.168.124.14]

RUNNING HANDLER [restart httpd service] ********************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=4    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#访问两台被控主机httpd 页面
[root@C7 ~]# curl C7-3:88
If you can see,that's good!
[root@C7 ~]# curl C7-4:88
If you can see,that's good!

#除了可以这样执行之外,我们还可以利用ansible-playbook仅执行指定的tags任务
#给指定的tasks打标签,以供调用
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml 
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: install httpd
      yum: name=httpd
    - name: config httpd service
      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
      notify: restart httpd service        
      tags: config                         #新行
    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html
    - name: manage httpd service
      service: name=httpd state=started enabled=yes
  handlers:                                
    - name: restart httpd service          
      service: name=httpd state=restarted  

#修改httpd 端口
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd.conf
#Listen 80
Listen 8888

#列出playbook中所有的tags
[root@C7 ~]# ansible-playbook --list-tags /etc/ansible/roles/playbook/httpd_install.yml 

playbook: /etc/ansible/roles/playbook/httpd_install.yml

  play #1 (srvs): srvs	TAGS: []
      TASK TAGS: [config]

#用ansible-playbook 仅执行指定的tags 任务
[root@C7 ~]# ansible-playbook -t config /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [config httpd service] ********************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

RUNNING HANDLER [restart httpd service] ********************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#查看远程被控主机httpd 监听端口
[root@C7 ~]# ansible all -a "ss -ntul"
192.168.124.14 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      128    [::]:8888               [::]:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      128       *:8888                  *:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  

#访问
[root@C7 ~]# curl C7-3:8888
If you can see,that's good!
[root@C7 ~]# curl C7-4:8888
If you can see,that's good!

变量使用

#接下来,让我们初步了解ansible-playbook的变量如何使用
#变量仅由字母、数字和下划线组成,且只能以数字开头
#变量可在/etc/ansible/hosts 中定义,或者在独立的变量YAML文件中定义
#变量调用方式:通过 {{ variable_name }} 调用变量,且变量名前后必须有空格
#有时用 "{{ variable_name }}" 才会生效

#实际应用一下,编写一个简单的yml文件测试
[root@C7 ~]# vim /etc/ansible/roles/playbook/vartest.yml
---
- hosts: srvs
  tasks:
    - name: playbook var test
      shell: /bin/echo "laowang is pig {{ ansible_distribution_major_version }}" > /data/vartest.txt

#日常测试干跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/vartest.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [playbook var test] ***********************************************************************************************************
skipping: [192.168.124.13]
skipping: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   


#测试无误,进行执行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/vartest.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [playbook var test] ***********************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#查看远程被控主机文件内容
[root@C7 ~]# ansible all -a "cat /data/vartest.txt"
192.168.124.14 | CHANGED | rc=0 >>
laowang is pig 7
192.168.124.13 | CHANGED | rc=0 >>
laowang is pig 7

#除了使用setup 模块提供的远程主机变量还可以在ansible 的hosts 文件中自定义变量
[root@C7 ~]# vim /etc/ansible/hosts 
[srvs]    # []中的英文尽量写的好记一点
192.168.124.13    name=zhangsan course=linux #被控主机IP
192.168.124.14    name=lisi course=centos #被控主机IP

#修改之前的yml文件
[root@C7 ~]# vim /etc/ansible/roles/playbook/vartest.yml
---
- hosts: srvs
  tasks:
    - name: playbook var test
      shell: /bin/echo "Hi,my name is {{ name }},and I like study {{ course }}." > /data/vartest.txt

#日常测试干跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/vartest.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [playbook var test] ***********************************************************************************************************
skipping: [192.168.124.14]
skipping: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=1    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   

#运行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/vartest.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [playbook var test] ***********************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看
[root@C7 ~]# ansible all -a "cat /data/vartest.txt"
192.168.124.14 | CHANGED | rc=0 >>
Hi,my name is lisi,and I like study centos.
192.168.124.13 | CHANGED | rc=0 >>
Hi,my name is zhangsan,and I like study linux.


#尝试在playbook文件中直接定义变量使用
[root@C7 ~]# vim /etc/ansible/roles/playbook/useradd.yml 
---
- hosts: srvs
  vars:
    - username: zhangsan
    - usergroup: studylinux
  tasks:
    - name: create group
      group: name={{ usergroup }} state=present
    - name: create user
      user: name={{ username }} group={{ usergroup }} state=present

#测试干跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/useradd.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [create group] ****************************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [create user] *****************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#运行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/useradd.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [create group] ****************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [create user] *****************************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看远程被控主机中 zhangsan 的用户信息
[root@C7 ~]# ansible all -a "id zhangsan"
192.168.124.14 | CHANGED | rc=0 >>
uid=1001(zhangsan) gid=1001(studylinux) groups=1001(studylinux)
192.168.124.13 | CHANGED | rc=0 >>
uid=1001(zhangsan) gid=1001(studylinux) groups=1001(studylinux)

#当我们不断的定义变量,随着时间累积其数量将会变得愈来愈多,编辑和管理也随着变得繁琐
#因此,我们可以单独创建定义变量的yml文件,再在playbook中引用即可
[root@C7 ~]# vim /etc/ansible/roles/playbook/vars.yml
usergroup: teachers
username: lisi

[root@C7 ~]# vim /etc/ansible/roles/playbook/useradd.yml 
---
- hosts: srvs
  vars_files:    #新行
    - vars.yml   #新行
#  vars:
#    - username: zhangsan
#    - usergroup: studylinux
  tasks:
    - name: create group
      group: name={{ usergroup }} state=present
    - name: create user
      user: name={{ username }} group={{ usergroup }} state=present


#测试干跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/useradd.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [create group] ****************************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [create user] *****************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#运行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/useradd.yml 

PLAY [srvs] *************************************************************************************************************************

TASK [Gathering Facts] *************************************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [create group] ****************************************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [create user] *****************************************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP *************************************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


查看远程被控主机中 lisi 的用户信息
[root@C7 ~]# ansible all -a "id lisi"
192.168.124.13 | CHANGED | rc=0 >>
uid=1002(lisi) gid=1002(teachers) groups=1002(teachers)
192.168.124.14 | CHANGED | rc=0 >>
uid=1002(lisi) gid=1002(teachers) groups=1002(teachers)

条件判断

#除此之外,我们还可以在ansible-playbook中使用条件判断when
#为了展示实验效果,我们临时添加一台虚拟机

主机版本 主/被 主机IP 主机名
CentOS 6 被控端 192.168.124.20 C6
#将免密验证执行完成
[root@C7 ~]# scp /root/.ssh/authorized_keys 192.168.124.20:/root/.ssh/
[email protected]‘s password: 
authorized_keys                                           100%  395   229.9KB/s   00:00    
[root@C7 ~]# ssh 192.168.124.20
Last login: Mon Mar 30 08:49:10 2020 from 192.168.124.1
[root@C6 ~]# exit
logout
Connection to 192.168.124.20 closed.

#添加hosts被控主机清单
[root@C7 ~]# vim /etc/ansible/hosts
[srvs]
192.168.124.13    
192.168.124.14    
192.168.124.20    #新行

#查看一下,确实已被添加进去
[root@C7 ~]# ansible all --list
  hosts (3):
    192.168.124.13
    192.168.124.14
    192.168.124.20

#编写yml文件
[root@C7 ~]# vim /etc/ansible/roles/playbook/dbserver.yml
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: Install DBserver software in CentOS6
      yum: name=mysql-server
      when: ansible_distribution_major_version=="6"
    - name: Install DBserver software in CentOS7
      yum: name=mariadb-server
      when: ansible_distribution_major_version=="7"

#测试
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/dbserver.yml 

PLAY [srvs] ********************************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [192.168.124.20]
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [Install DBserver software in CentOS6] ************************************************
skipping: [192.168.124.14]
skipping: [192.168.124.13]
changed: [192.168.124.20]

TASK [Install DBserver software in CentOS7] ************************************************
skipping: [192.168.124.20]
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *********************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.20             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   


[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/dbserver.yml 

PLAY [srvs] ********************************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [192.168.124.20]
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [Install DBserver software in CentOS6] ************************************************
skipping: [192.168.124.13]
skipping: [192.168.124.14]
fatal: [192.168.124.20]: FAILED! => {"changed": false, "changes": {"installed": ["mysql-server"]}, 
……………………..#报错
\nInstall       4 Package(s)\n\nTotal download size: 10 M\nInstalled size: 29 M\nDownloading Packages:\n"]}

TASK [Install DBserver software in CentOS7] ************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP *********************************************************************************
192.168.124.13             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.20             : ok=1    changed=0    unreachable=0    failed=1    skipped=0    rescued=0    ignored=0   
#CentOS6主机出现报错,经过我检查排错确认是由于该主机网关不通导致无法进行软件包安装
#解决方法:在CentOS6主机上添加网管并ping测试
[root@C6 ~]# vim /etc/resolv.conf 
#添加一条或多条
nameserver 192.168.124.10    #此IP是我个人虚拟机的网关
nameserver 114.114.114.114    #通用网关

[root@C6 ~]# ping www.baidu.com
PING www.a.shifen.com (61.135.169.125) 56(84) bytes of data.
64 bytes from 61.135.169.125: icmp_seq=1 ttl=128 time=7.43 ms
64 bytes from 61.135.169.125: icmp_seq=2 ttl=128 time=6.12 ms
^C
--- www.a.shifen.com ping statistics ---
3 packets transmitted, 3 received, 0% packet loss, time 2715ms
rtt min/avg/max/mdev = 6.129/7.320/8.395/0.934 ms


#在主控端重新执行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/dbserver.yml 

PLAY [srvs] ********************************************************************************

TASK [Gathering Facts] *********************************************************************
ok: [192.168.124.20]
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [Install DBserver software in CentOS6] ************************************************
skipping: [192.168.124.13]
skipping: [192.168.124.14]
changed: [192.168.124.20]

TASK [Install DBserver software in CentOS7] ************************************************
skipping: [192.168.124.20]
ok: [192.168.124.13]
ok: [192.168.124.14]

PLAY RECAP *********************************************************************************
192.168.124.13             : ok=2    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.14             : ok=2    changed=0    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   
192.168.124.20             : ok=2    changed=1    unreachable=0    failed=0    skipped=1    rescued=0    ignored=0   


#查看远程被控主机安装包信息,忽略WARNING警告信息
[root@C7 ~]# ansible all -a "rpm -q mariadb"
[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'.  If you
need to use command because yum, dnf or zypper is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this
message.
192.168.124.14 | CHANGED | rc=0 >>
mariadb-5.5.65-1.el7.x86_64
192.168.124.13 | CHANGED | rc=0 >>
mariadb-5.5.65-1.el7.x86_64
192.168.124.20 | FAILED | rc=1 >>
package mariadb is not installednon-zero return code

[root@C7 ~]# ansible all -a "rpm -q mysql"
[WARNING]: Consider using the yum, dnf or zypper module rather than running 'rpm'.  If you
need to use command because yum, dnf or zypper is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this
message.
192.168.124.20 | CHANGED | rc=0 >>
mysql-5.1.73-8.el6_8.x86_64
192.168.124.13 | FAILED | rc=1 >>
package mysql is not installednon-zero return code
192.168.124.14 | FAILED | rc=1 >>
package mysql is not installednon-zero return code

#CentOS6的使命暂时结束,从hosts文件中移除
[root@C7 ~]# vim /etc/ansible/hosts
[srvs] 
192.168.124.13
192.168.124.14 
#192.168.124.20    #注释
#ansible-playbook 使用循环 with_items
#使用循环结构多次执行同一个task任务


[root@C7 ~]# vim /etc/ansible/roles/playbook/addusers.yml
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: add more group
      group: name={{ item }} state=present
      with_items:
      - group1
      - group2
      - group3
    - name: add more user
      user: name={{ item.username }} group={{ item.usergroup }} state=present
      with_items:
        - { username: 'user1', usergroup: 'group1' }
        - { username: 'user2', usergroup: 'group2' }
        - { username: 'user3', usergroup: 'group3' }


#测试
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/addusers.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [add more group] *********************************************************************************************
changed: [192.168.124.14] => (item=group1)
changed: [192.168.124.13] => (item=group1)
changed: [192.168.124.14] => (item=group2)
changed: [192.168.124.13] => (item=group2)
changed: [192.168.124.14] => (item=group3)
changed: [192.168.124.13] => (item=group3)

TASK [add more user] **********************************************************************************************
changed: [192.168.124.14] => (item={u'username': u'user1', u'usergroup': u'group1'})
changed: [192.168.124.13] => (item={u'username': u'user1', u'usergroup': u'group1'})
changed: [192.168.124.14] => (item={u'username': u'user2', u'usergroup': u'group2'})
changed: [192.168.124.13] => (item={u'username': u'user2', u'usergroup': u'group2'})
changed: [192.168.124.14] => (item={u'username': u'user3', u'usergroup': u'group3'})
changed: [192.168.124.13] => (item={u'username': u'user3', u'usergroup': u'group3'})

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#运行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/addusers.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [add more group] *********************************************************************************************
changed: [192.168.124.14] => (item=group1)
changed: [192.168.124.13] => (item=group1)
changed: [192.168.124.14] => (item=group2)
changed: [192.168.124.13] => (item=group2)
changed: [192.168.124.14] => (item=group3)
changed: [192.168.124.13] => (item=group3)

TASK [add more user] **********************************************************************************************
changed: [192.168.124.14] => (item={u'username': u'user1', u'usergroup': u'group1'})
changed: [192.168.124.13] => (item={u'username': u'user1', u'usergroup': u'group1'})
changed: [192.168.124.14] => (item={u'username': u'user2', u'usergroup': u'group2'})
changed: [192.168.124.13] => (item={u'username': u'user2', u'usergroup': u'group2'})
changed: [192.168.124.14] => (item={u'username': u'user3', u'usergroup': u'group3'})
changed: [192.168.124.13] => (item={u'username': u'user3', u'usergroup': u'group3'})

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=3    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看用户信息
[root@C7 ~]# ansible all -m shell -a "cat /etc/passwd|grep user"
192.168.124.14 | CHANGED | rc=0 >>
user1:x:1003:1003::/home/user1:/bin/bash
user2:x:1004:1004::/home/user2:/bin/bash
user3:x:1005:1005::/home/user3:/bin/bash
192.168.124.13 | CHANGED | rc=0 >>
user1:x:1003:1003::/home/user1:/bin/bash
user2:x:1004:1004::/home/user2:/bin/bash
user3:x:1005:1005::/home/user3:/bin/bash

#ansible-playbook 使用模板
#templates 可以使用ansible-playbook 中定义的变量用以生成指定的文件
#下面我以httpd_install.yml 文件进行演示
[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml 
---
- hosts: srvs
  remote_user: root
  tasks:
    - name: install httpd
      yum: name=httpd
    - name: config httpd service
#      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
      template: src=httpd.conf.j2 dest=/etc/httpd/conf/httpd.conf  #新行
      notify: restart httpd service
      tags: config
    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html
    - name: manage httpd service
      service: name=httpd state=started enabled=yes
  handlers:
    - name: restart httpd service
      service: name=httpd state=restarted

[root@C7 ~]# mkdir /etc/ansible/roles/playbook/templates
[root@C7 ~]# cp /etc/ansible/roles/playbook/httpd.conf /etc/ansible/roles/playbook/templates/httpd.conf.j2

[root@C7 ~]# vim !$
#Listen 8888
Listen {{httpd_port}}

#也许有人看不明白 vim !$ 是什么意思,!$表示的是调用上一次执行的命令行中最后一个参数
#对于这里而言,执行 vim !$ 等同于 vim /etc/ansible/roles/playbook/templates/httpd.conf.j2
#掌握技巧能够使我们工作效率大大增加
[root@C7 ~]# ansible-playbook -e httpd_port=10086 /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [install httpd] **********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ***************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [copy default index.html] ************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [manage httpd service] ***************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

RUNNING HANDLER [restart httpd service] ***************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

#查看端口
[root@C7 ~]# ansible all -a "ss -ntul"
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:10086              [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  
192.168.124.14 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:10086              [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  


[root@C7 ~]# ansible all -m shell -a "cat /etc/httpd/conf/httpd.conf|grep ^Listen"
192.168.124.14 | CHANGED | rc=0 >>
Listen 10086
192.168.124.13 | CHANGED | rc=0 >>
Listen 10086

#变量除了可以直接引用之外,还可以进行变量运算
[root@C7 ~]# vim /etc/ansible/hosts 
[srvs] 
192.168.124.13 httpd_port=110 
192.168.124.14 httpd_port=150 

[root@C7 ~]# vim /etc/ansible/roles/playbook/templates/httpd.conf.j2
#Listen {{httpd_port}}
Listen {{httpd_port*2}}


[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [install httpd] **********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ***************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [copy default index.html] ************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [manage httpd service] ***************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

RUNNING HANDLER [restart httpd service] ***************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


[root@C7 ~]# ansible all -a "ss -ntul"
192.168.124.14 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:300                [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:220                [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  


[root@C7 ~]# ansible all -m shell -a "cat /etc/httpd/conf/httpd.conf|grep ^Listen"
192.168.124.14 | CHANGED | rc=0 >>
Listen 300
192.168.124.13 | CHANGED | rc=0 >>
Listen 220


#模板中还可以使用循环结构动态生成内容
[root@C7 ~]# vim /etc/ansible/hosts 
[srvs] 
192.168.124.13
192.168.124.14

[root@C7 ~]# vim /etc/ansible/roles/playbook/httpd_install.yml
---
- hosts: srvs
  remote_user: root
  vars:
    httpd_vhosts:
      - web01:
        listen: 8001
        documentroot: '/data/web01'

      - web02:
        listen: 8002
        documentroot: '/data/web02'

  tasks:
    - name: install httpd
      yum: name=httpd

    - name: config httpd service
#      copy: src=/etc/ansible/roles/playbook/httpd.conf dest=/etc/httpd/conf/httpd.conf
      template: src=vhostport.conf.j2 dest=/etc/httpd/conf.d/vhostport.conf
      notify: restart httpd service
      tags: config

    - name: copy default index.html
      copy: src=/etc/ansible/roles/playbook/index.html dest=/usr/share/httpd/noindex/index.html

    - name: manage httpd service
      service: name=httpd state=started enabled=yes

  handlers:
    - name: restart httpd service
      service: name=httpd state=restarted

[root@C7 ~]# vim /etc/ansible/roles/playbook/vhostport.conf.j2
{% for vhost in httpd_vhosts %}
listen {{vhost.listen}}
{% endfor %}

{% for vhost in httpd_vhosts %}
<virtualhost *.{{vhost.listen}}>
        documentroot {{vhost.documentroot}}
        <directory {vhost.documentroot}>
                require all granted
        </directory>
</virtualhost>
{% endfor %}

#测试干跑
[root@C7 ~]# ansible-playbook -C /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [install httpd] **********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ***************************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

TASK [copy default index.html] ************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [manage httpd service] ***************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

RUNNING HANDLER [restart httpd service] ***************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#运行
[root@C7 ~]# ansible-playbook /etc/ansible/roles/playbook/httpd_install.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

TASK [install httpd] **********************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [config httpd service] ***************************************************************************************
changed: [192.168.124.13]
changed: [192.168.124.14]

TASK [copy default index.html] ************************************************************************************
ok: [192.168.124.13]
ok: [192.168.124.14]

TASK [manage httpd service] ***************************************************************************************
ok: [192.168.124.14]
ok: [192.168.124.13]

RUNNING HANDLER [restart httpd service] ***************************************************************************
changed: [192.168.124.14]
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.124.14             : ok=6    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


[root@C7 ~]# ansible all -a "ss -ntul"
192.168.124.14 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:8001               [::]:*                  
tcp    LISTEN     0      128    [::]:8002               [::]:*                  
tcp    LISTEN     0      128    [::]:300                [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:220                [::]:*                  
tcp    LISTEN     0      128    [::]:8001               [::]:*                  
tcp    LISTEN     0      128    [::]:8002               [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  


[root@C7 ~]# curl C7-3:8001
If you can see,that's good!
[root@C7 ~]# curl C7-3:8002
If you can see,that's good!
[root@C7 ~]# curl C7-4:8002
If you can see,that's good!
[root@C7 ~]# curl C7-4:8001
If you can see,that's good!

模块化安装httpd

#让我们稍微升级一下,以模块化的方式安装httpd服务
#将所有主机还原到刚刚配置完成免密钥登录远程被控主机的状态,并且只保留C7 与C7-3 两台虚拟机
#使用时间管理技能:时光回溯……….完成

#配置远程被控主机清单
[root@C7 ~]# vim /etc/ansible/hosts
[srvs]
192.168.124.13

#测试能否ping通
[root@C7 ~]# ansible all -m ping
192.168.124.13 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}


[root@C7 ~]# mkdir -p /etc/ansible/roles/playbook/httpd/{tasks,handlers,files,templates,vars}
[root@C7 ~]# tree /etc/ansible/ -d
/etc/ansible/
└── roles
    └── playbook
        └── httpd
            ├── files
            ├── handlers
            ├── tasks
            ├── templates
            └── vars

[root@C7 ~]# cd /etc/ansible/roles/playbook/httpd/tasks/
[root@C7 tasks]# vim main.yml
- include: install.yml
- include: config.yml
- include: index.yml
- include: service.yml


[root@C7 tasks]# vim install.yml
- name: Install httpd package
  yum: name=httpd


[root@C7 tasks]# vim index.yml
- name: index.html
  copy: src=index.html dest=/var/www/html/


[root@C7 tasks]# vim config.yml
- name: config file
  copy: src=httpd.conf dest=/etc/httpd/conf/ backup=yes
  notify: restart


[root@C7 tasks]# vim service.yml
- name: start service
  service: name=httpd state=started enabled=yes


[root@C7 tasks]# vim /etc/ansible/roles/playbook/httpd/handlers/main.yml
- name: restart
  service: name=httpd state=restarted

[root@C7 tasks]# yum install httpd -y

[root@C7 tasks]# cp /etc/httpd/conf/httpd.conf /etc/ansible/roles/playbook/httpd/files/
[root@C7 tasks]# vim /etc/ansible/roles/playbook/httpd/files/index.html
<html>
<head>
<meta http-equiv=Content-Type content="text/html;charset=utf-8">
<title>HTML语言</title>
</head>
<body>
<a href=https://blog.csdn.net/dushansao>
<img src="https://profile.csdnimg.cn/7/0/B/1_dushansao" /img></a>
<a href=https://blog.csdn.net/dushansao>
<h1 style="color:red">欢迎来到我的博客</h1></a>
<p><a href=https://blog.csdn.net/dushansao>点我,让你好看!</a> 不点必将后悔!</p>
</body>
</html>

[root@C7 tasks]# vim /etc/ansible/roles/playbook/role_httpd.yml
---
- hosts: srvs
  remote_user: root
  roles:
    - role: /etc/ansible/roles/playbook/httpd


[root@C7 tasks]# tree /etc/ansible/
/etc/ansible/
├── ansible.cfg
├── hosts
└── roles
    └── playbook
        ├── httpd
        │   ├── files
        │   │   ├── httpd.conf
        │   │   └── index.html
        │   ├── handlers
        │   │   └── main.yml
        │   ├── tasks
        │   │   ├── config.yml
        │   │   ├── index.yml
        │   │   ├── install.yml
        │   │   ├── main.yml
        │   │   └── service.yml
        │   ├── templates
        │   └── vars
        └── role_httpd.yml


#测试
[root@C7 tasks]# ansible-playbook -C /etc/ansible/roles/playbook/role_httpd.yml

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : Install httpd package] **************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : config file] ************************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : index.html] *************************************************************
changed: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : start service] **********************************************************
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#运行
[root@C7 tasks]# ansible-playbook /etc/ansible/roles/playbook/role_httpd.yml 

PLAY [srvs] *******************************************************************************************************

TASK [Gathering Facts] ********************************************************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : Install httpd package] **************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : config file] ************************************************************
ok: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : index.html] *************************************************************
changed: [192.168.124.13]

TASK [/etc/ansible/roles/playbook/httpd : start service] **********************************************************
changed: [192.168.124.13]

PLAY RECAP ********************************************************************************************************
192.168.124.13             : ok=5    changed=2    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   


#查看远程被控主机端口
[root@C7 tasks]# ansible all -a "ss -ntul"
192.168.124.13 | CHANGED | rc=0 >>
Netid  State      Recv-Q Send-Q Local Address:Port               Peer Address:Port              
udp    UNCONN     0      0      127.0.0.1:323                   *:*                  
udp    UNCONN     0      0         [::1]:323                [::]:*                  
tcp    LISTEN     0      100    127.0.0.1:25                    *:*                  
tcp    LISTEN     0      128       *:22                    *:*                  
tcp    LISTEN     0      100       [::1]:25                 [::]:*                  
tcp    LISTEN     0      128    [::]:80                 [::]:*                  
tcp    LISTEN     0      128    [::]:22                 [::]:*                  


#网页打开

68-ansible实验总结_第1张图片

点击跳至文章末尾

你可能感兴趣的:(68-ansible实验总结)