Jenkins+Gitlab+Ansible自动化部署(二)

Jenkins+Gitlab+Ansible自动化部署(二)

接Jenkins+Gitlab+Ansbile自动化部署(一):https://www.cnblogs.com/zd520pyx1314/p/10210727.html

Ansible的配置与部署

工具名称 介绍
Chef 采用Ruby编写,C/S架构,配置需要Git依赖,Recipe脚本编写规范,需要良好的编程经验。
Ansible

采用Python编写,无Client,模块化配置管理,Playbook脚本编写规范,易于上手,

适合中小规模快速部署。

Saltstack

采用Python编写,C/S架构,模块化配置管理,YAML脚本编写规范,内置

异步文件服务器可以为客户端文件加快服务速度,适合大规模集群部署,但是需要安装客户端。

 

 

 

 

 

 

Ansible的优势和应用场景

优势:

  • 轻量级无客户端(Agentless);
  • 开源免费,学习成本低,快速上手;
  • 使用playbook作为核心配置架构,同意的脚本格式批量化部署;
  • 完善的模块化扩展,支持目前主流的开发环境;
  • 强大的稳定性和兼容性;
  • 活跃的官方社区问题讨论,方便troubleshooting与debug问题;

Ansible配合virtualenv安装配置

使用python自带的python virtualenv工具隔离Python3.6、Ansible2.5和系统其他python依赖环境。

Ansible安装方式

1.yum一键安装(不推荐) 

[root@ansible ~]# yum install -y ansible
# 虽然简单,但是会带来一系列的依赖和模块混乱

2.Git源码安装(推荐)

[root@ansible ~]# yum install -y git      #如果系统中没有git的话,使用这条命令安装即可
[root@ansible ~]# git clone https://github.com/ansible/ansible.git

Ansible2.5+Python3.6安装步骤

1.安装python3.6.5和virtualenv工具

[root@ansible ~]# wget http://www.python.org/ftp/python/3.6.5/Python-3.6.5.tar.xz
[root@ansible ~]# tar -xf Python-3.6.5.tar.xz -C /usr/local/src/
[root@ansible ~]# cd /usr/local/src/Python-3.6.5/
[root@ansible ~]# cd /usr/local/src/Python-3.6.5/
[root@ansible Python-3.6.5]# ./configure --prefix=/usr/local/ --with-ensurepip=install --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
#竟然报错
configure: error: in `/usr/local/src/Python-3.6.5':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details
# 根据报错信息,需要安装GCC套件
[root@ansible Python-3.6.5]# yum install -y gcc 
# 然后再次执行编译操作,完事执行安装
[root@ansible Python-3.6.5]# make && make altinstall
# 然而又报错了
....
    import pip
zipimport.ZipImportError: can't decompress data; zlib not available
make: *** [altinstall] Error 1
# 提示很明显了直接执行
[root@ansible Python-3.6.5]# yum install zlib*
# 然后再吃运行安装命令即可
[root@ansible Python-3.6.5]# make && make altinstall
# 当看到
.....
Collecting setuptools
Collecting pip
Installing collected packages: setuptools, pip
Successfully installed pip-9.0.3 setuptools-39.0.1
# 表明安装成功
# 接着安装virtualenv,然而并不顺利
[root@ansible bin]# pwd
/usr/local/bin
[root@ansible bin]# ./pip --trusted-host pypi.python.org install virtualenv
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting virtualenv
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Could not fetch URL https://pypi.python.org/simple/virtualenv/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/virtualenv/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping
  Could not find a version that satisfies the requirement virtualenv (from versions: )
No matching distribution found for virtualenv
# 使用网友提供的方法  加上--trusted-host参数,哦...依然不行
[root@ansible bin]# ./pip --trusted-host pypi.python.org install virtualenv
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available.
Collecting virtualenv
  Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)': /simple/virtualenv/
  Could not fetch URL https://pypi.python.org/simple/virtualenv/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.python.org', port=443): Max retries exceeded with url: /simple/virtualenv/ (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.",)) - skipping
  Could not find a version that satisfies the requirement virtualenv (from versions: )
No matching distribution found for virtualenv
# 根据第一行报错提示
pip is configured with locations that require TLS/SSL, however the ssl module in Python is not available
# 需要安装openssl相关软件包
[root@ansible bin]# yum install -y openssl*
#除此之外,卸载掉python2.7安装的pip防止干扰
[root@ansible bin]# python -m pip uninstall pip
Uninstalling pip-18.1:
  Would remove:
    /usr/bin/pip
    /usr/bin/pip2
    /usr/bin/pip2.7
    /usr/lib/python2.7/site-packages/pip-18.1.dist-info/*
    /usr/lib/python2.7/site-packages/pip/*
Proceed (y/n)? y
  Successfully uninstalled pip-18.1
# 然后回到解压包里,重新运行编译安装过程
[root@ansible Python-3.6.5]# ./configure --prefix=/usr/local/ --with-ensurepip=install --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
[root@ansible Python-3.6.5]# make && make altinstall 
.......
Requirement already satisfied: setuptools in /usr/local/lib/python3.6/site-packages
Requirement already satisfied: pip in /usr/local/lib/python3.6/site-packages
[root@ansible Python-3.6.5]# cd ../../bin/
[root@ansible bin]# ll
total 68
-rwxr-xr-x. 1 root root   101 Jan  7 11:42 2to3-3.6
-rwxr-xr-x. 1 root root   242 Jan  7 11:00 easy_install-3.6
-rwxr-xr-x. 1 root root    99 Jan  7 11:42 idle3.6
lrwxrwxrwx. 1 root root    21 Jan  7 11:03 pip -> /usr/local/bin/pip3.6
-rwxr-xr-x. 1 root root   214 Jan  7 11:00 pip3.6
-rwxr-xr-x. 1 root root    84 Jan  7 11:42 pydoc3.6
-rwxr-xr-x. 2 root root 17712 Jan  7 11:41 python3.6
-rwxr-xr-x. 2 root root 17712 Jan  7 11:41 python3.6m
-rwxr-xr-x. 1 root root  3109 Jan  7 11:42 python3.6m-config
-rwxr-xr-x. 1 root root   441 Jan  7 11:42 pyvenv-3.6
[root@ansible bin]# ln -s /usr/local/bin/pip3.6 /usr/local/bin/pip
# 再次使用pip安装virtualenv
[root@ansible bin]# pip install virtualenv
Collecting virtualenv
  Cache entry deserialization failed, entry ignored
  Cache entry deserialization failed, entry ignored
  Downloading https://files.pythonhosted.org/packages/6a/d1/e0d142ce7b8a5c76adbfad01d853bca84c7c0240e35577498e20bc2ade7d/virtualenv-16.2.0-py2.py3-none-any.whl (1.9MB)
    100% |████████████████████████████████| 1.9MB 64kB/s
Requirement already satisfied: setuptools>=18.0.0 in /usr/local/lib/python3.6/site-packages (from virtualenv)
Installing collected packages: virtualenv
Successfully installed virtualenv-16.2.0
You are using pip version 9.0.3, however version 18.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
# 安装成功

2.创建ansible账户并安装python3.6.5版本virtualenv实例

[root@ansible ~]# useradd deploy && su - deploy
[deploy@ansible ~]$ virtualenv -p /usr/local/bin/python3.6 .py3-a2.5-env
Already using interpreter /usr/local/bin/python3.6
Using base prefix '/usr/local'
New python executable in /home/deploy/.py3-a2.5-env/bin/python3.6
Also creating executable in /home/deploy/.py3-a2.5-env/bin/python
Installing setuptools, pip, wheel...
done.
[deploy@ansible ~]$

3.Git源码安装ansible2.5

# 首先使用root账户确保git nss curl命令已经安装
[root@ansible ~]# yum install -y git nss curl
# 然后切到deploy用户,进入之前创建的.py3-a2.5-env目录下
[deploy@ansible ~]$ cd /home/deploy/.py3-a2.5-env/
[deploy@ansible .py3-a2.5-env]$ git clone https://github.com/ansible/ansible.git

4. 加载python3.6.5 virtualenv环境

[deploy@ansible .py3-a2.5-env]$ source /home/deploy/.py3-a2.5-env/bin/activate
(.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$

5. 安装ansible依赖包

# 安装依赖包
(.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ pip install paramiko PyYAML jinja2
(.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ ll
total 8
drwxrwxr-x. 14 deploy deploy 4096 Jan  7 13:31 ansible
drwxrwxr-x.  2 deploy deploy 4096 Jan  7 11:52 bin
drwxrwxr-x.  2 deploy deploy   24 Jan  7 11:52 include
drwxrwxr-x.  3 deploy deploy   23 Jan  7 11:52 lib
(.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ pwd
/home/deploy/.py3-a2.5-env

6. 在python3.6.5虚拟环境下加载ansible2.5

# 确认ansible源码包在.py3-a2.5-env目录下
# 进入ansible目录
(.py3-a2.5-env) [deploy@ansible .py3-a2.5-env]$ cd ansible/
(.py3-a2.5-env) [deploy@ansible ansible]$ pwd
/home/deploy/.py3-a2.5-env/ansible
(.py3-a2.5-env) [deploy@ansible ansible]$ git checkout stable-2.5  #将ansible切换到2.5版本
Branch stable-2.5 set up to track remote branch stable-2.5 from origin.
Switched to a new branch 'stable-2.5'
(.py3-a2.5-env) [deploy@ansible ansible]$ source /home/deploy/.py3-a2.5-env/ansible/hacking/env-setup -q  #在此虚拟环境下加载ansible2.5版本

7.验证ansible版本

(.py3-a2.5-env) [deploy@ansible ansible]$ ansible --version
ansible 2.5.14 (stable-2.5 6548b7a558) last updated 2019/01/07 13:56:01 (GMT +800)
  config file = None
  configured module search path = ['/home/deploy/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/deploy/.py3-a2.5-env/ansible/lib/ansible
  executable location = /home/deploy/.py3-a2.5-env/ansible/bin/ansible
  python version = 3.6.5 (default, Jan  7 2019, 11:40:52) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
# 至此ansible2.5在虚拟环境下安装加载完成

Playbooks框架与格式

父目录 1级子目录 2级子目录  
inventory/ Server详细清单目录 用来保存主机域名、IP地址和相关参数  
  testenv 具体清单与变量声明文件  
roles/ roles任务列表 可以存放一个或多个role  
  testbox/  testbox详细任务  
    tasks/  
    main.yml testbox主任务文件
deploy.yml Playbook任务入口文件    

 

 

 

 

 

 

 

 

 

 

格式说明

testenv文件 说明
[testservers] Server组列表
test.example.com 目标部署服务器主机名
[testservers:vars] Server组列表参数
server_name=test,example.com 目标主机Key/Value参数
user=root
output=/root/test.txt

 

 

 

 

 

 

 

 

 

主任务文件main.yml

文件内容 说明
- name:Print Server name and user to remote testbox 任务名称
    shell:"echo 'Currently{{user}} is logining {{server_name}}' > {{output}}" shell:使用shell模块执行命令
inventory/testenv文件[testservers:vars]

server_name=test.example.com

user=root

output=/root/test.txt

 

 

 

 

 

 

 

 

 

任务入口文件deploy.yml

- hosts:"testservers"      #Server列表
  gather_facts:true         #获取Server基本信息   
   remote_user:root        # 目标服务器系统用户指定
   roles:
   - testbox                      #进入roles/testbox任务目录

登录ansible主机,加载之前配置好的python3.6.5和ansible2.5环境,并验证

[root@ansible ~]# su - deploy
Last login: Mon Jan  7 11:51:41 CST 2019 on pts/1
[deploy@ansible ~]$ source .py3-a2.5-env/bin/activate
(.py3-a2.5-env) [deploy@ansible ~]$ source .py3-a2.5-env/ansible/hacking/env-setup -q
(.py3-a2.5-env) [deploy@ansible ~]$ ansible-playbook --version
ansible-playbook 2.5.14 (stable-2.5 6548b7a558) last updated 2019/01/07 13:56:01 (GMT +800)
  config file = None
  configured module search path = ['/home/deploy/.ansible/plugins/modules', '/usr/share/ansible/plugins/modules']
  ansible python module location = /home/deploy/.py3-a2.5-env/ansible/lib/ansible
  executable location = /home/deploy/.py3-a2.5-env/ansible/bin/ansible-playbook
  python version = 3.6.5 (default, Jan  7 2019, 11:40:52) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]

开始编写playbooks

(.py3-a2.5-env) [deploy@ansible ~]$ mkdir test-playbooks
(.py3-a2.5-env) [deploy@ansible ~]$ cd test-playbooks/
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir inventory
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ cd inventory
(.py3-a2.5-env) [deploy@ansible inventory]$ vim testenv
[testservers]
test.example.com

[testservers:vars]
server_name=test.example.com
user=root
output=/root/test.txt
(.py3-a2.5-env) [deploy@ansible inventory]$ cd ..
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ls
inventory  roles
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ cd roles/
(.py3-a2.5-env) [deploy@ansible roles]$ mkdir testbox
(.py3-a2.5-env) [deploy@ansible roles]$ cd testbox/
(.py3-a2.5-env) [deploy@ansible testbox]$ mkdir tasks
(.py3-a2.5-env) [deploy@ansible testbox]$ cd tasks/
(.py3-a2.5-env) [deploy@ansible tasks]$ vim main.yml
- name: Print server name and user to remote testbox
  shell:"echo 'Currently {{ user }} is loggging {{ server_name }}' > {{ output }}"
(.py3-a2.5-env) [deploy@ansible tasks]$ cd ../../..
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ pwd
/home/deploy/test-playbooks
(.py3-a2.5-env) [deploy@ansible tasks]$ cd ../../..
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ pwd
/home/deploy/test-playbooks
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim deploy.yml

- hosts: "testservers"
  gather_facts: true
  remote_user: root
   
   
  roles:
    - testbox

查看test_playbooxs目录结构

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ tree .
.
├── deploy.yml
├── inventory
│?? └── testenv
└── roles
    └── testbox
        └── tasks
            └── main.yml

4 directories, 3 files

这里需要另外一台测试被部署机器test.example.com

系统版本 主机名 IP地址
CentOS  Linux release 7.5.1804 (core) test.example.com 192.168.244.133

 

 

被部署的机器test.example.com与其他三台主机实验环境一致。

配置SSH免秘钥认证

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ su - root
Password:
Last login: Mon Jan  7 10:05:23 CST 2019 from 192.168.244.1 on pts/1
[root@ansible ~]# vim /etc/hosts
....
192.168.244.133 test.example.com
[root@ansible ~]# exit
logout
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/home/deploy/.ssh/id_rsa):
Created directory '/home/deploy/.ssh'.
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /home/deploy/.ssh/id_rsa.
Your public key has been saved in /home/deploy/.ssh/id_rsa.pub.
The key fingerprint is:
SHA256:Aj+FzKSwqZS19eI/3EQt13L78+u3vjMtseX8YXNFnnY [email protected]
The key's randomart image is:
+---[RSA 2048]----+
|  .. ..          |
|  o+o=..  . .    |
| oo.o.+..o + o  .|
|..  .o... o o .o.|
|.    .+ S.   . oE|
|      ooo     + +|
|       + .     %o|
|        .     +o@|
|              oB@|
+----[SHA256]-----+
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh-copy-id -i /home/deploy/.ssh/id_rsa.pub [email protected]
/bin/ssh-copy-id: INFO: Source of key(s) to be installed: "/home/deploy/.ssh/id_rsa.pub"
The authenticity of host 'test.example.com (192.168.244.133)' can't be established.
ECDSA key fingerprint is SHA256:66hu+WU6R2SL4+7r/WYk2kjrGi7IwjuJieTrdMhwLc0.
ECDSA key fingerprint is MD5:af:c7:bd:88:0d:40:d8:19:6d:28:7f:dd:af:aa:3a:c9.
Are you sure you want to continue connecting (yes/no)? yes
/bin/ssh-copy-id: INFO: attempting to log in with the new key(s), to filter out any that are already installed
/bin/ssh-copy-id: INFO: 1 key(s) remain to be installed -- if you are prompted now it is to install the new keys
[email protected]'s password:

Number of key(s) added: 1

Now try logging into the machine, with:   "ssh '[email protected]'"
and check to make sure that only the key(s) you wanted were added.
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected]
Last login: Mon Jan  7 17:35:38 2019 from 192.168.244.1
[root@test ~]# whoami
root
[root@test ~]# hostname
test.example.com

测试部署

(.py3-a2.5-env) [deploy@ansible ~]$ cd test-playbooks/
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ls
deploy.yml  inventory  roles
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml

PLAY [testservers] *************************************************************

TASK [Gathering Facts] *********************************************************
ok: [test.example.com]

TASK [testbox : Print server name and user to remote testbox] ******************
changed: [test.example.com]

PLAY RECAP *********************************************************************
test.example.com           : ok=2    changed=1    unreachable=0    failed=0  
# 以下内容可以看出已经成功在远程被部署主机test.example.com上创建一个test.txt文件,且文件内容与预先设置的一致
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected]
Last login: Mon Jan  7 17:42:57 2019 from 192.168.244.132
[root@test ~]# ls
anaconda-ks.cfg  test.txt
[root@test ~]# cat test.txt
Currently root is loggging test.example.com

Ansible Playbooks常用模块

File模块:

在目标主机创建文件或目录,并赋予其系统权限,如:

- name: create a file   # 任务名称
  file: 'path=/root/a.txt state=touch mode=0755 owner=sishen group=sishen'
# 任务内容

Copy模块:

实现Ansible服务端到目标主机的文件传送,如:

- name: copy a file   #任务名称 复制一个文件
  copy: 'remote_src=no src=roles/testbox/files/test.sh dest=/root/test.sh mode=0644 force=yes'

# 说明
remote_src:声明将ansible服务端文件传送到目标主机当中
src:源文件的路径
dest:目标文件的路径
mode:赋予的文件权限
force:强制执行

Stat模块:

获取远程文件状态信息,如:

- name: check if test.sh exists
  stat: 'path=/root/test.sh'   #需要获取的文件路径
  register: script_stat           #将stat变量获取到的信息传递给script_stat

Debug模块:

打印语句到Ansible执行输出:

- debug: msf=test.sh exists
  when:script_stat.stat.exists

Command/Shell模块

用来执行Linux目标主机命令行

- name: run the script
  command: "sh /root/test.sh"

- name: run the script
  shell: "echo 'test' > /root/test.txt" (推荐)

Template模块

实现Ansible服务端到目标主机的jinja2模板传送

- name: write the nginx config file
  template: src=roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.conf

Packaging模块

调用目标主机系统包管理工具(yum,apt)进行安装

- name: ensure nginx is at the latest version
  yum: pkg=nginx state=latest  #(CentOS/RHEL)

- name: ensure nginx is at the latest version
  apt: pkg=nginx state=latest    #(Debian/Ubuntu)

Service模块

管理目标主机系统服务

- name: start nginx service
  service: name=nginx state=started

登录被部署主机,创建测试用户

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected]
Last login: Mon Jan  7 17:44:56 2019 from 192.168.244.132
[root@test ~]# useradd sishen
useradd: user 'sishen' already exists
[root@test ~]# useradd god
[root@test ~]# useradd deploy
[root@test ~]# mkdir /etc/nginx
[root@test ~]# rpm -Uvh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
Retrieving http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
warning: /var/tmp/rpm-tmp.i5SPeu: Header V4 RSA/SHA1 Signature, key ID 7bd9bf62: NOKEY
Preparing...                                                            (100%################################# [100%]
Updating / installing...
   1:nginx-release-centos-7-0.el7.ngx                                   ( 81%################################# [100%]

退出被部署主机

[root@test ~]# exit
logout
Connection to test.example.com closed.
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ pwd
/home/deploy/test-playbooks
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ls
deploy.yml  inventory  roles
(.py3-a2.5-env) [deploy@ansible test-playbooks]$
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml
- name: Print server name and user to remote testbox
  shell: "echo 'Currently {{ user }} is loggging {{ server_name }}' > {{ output }}"
#添加以下内容
- name: create a file
  file: 'path=/root/god.txt state=touch mode=0755 owner=god group=god'
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml

PLAY [testservers] *************************************************************

TASK [Gathering Facts] *********************************************************
ok: [test.example.com]

TASK [testbox : Print server name and user to remote testbox] ******************
changed: [test.example.com]

TASK [testbox : create a file] *************************************************
changed: [test.example.com]

PLAY RECAP *********************************************************************
test.example.com           : ok=3    changed=2    unreachable=0    failed=0  

登录到远程主机查看

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected]
Last login: Mon Jan  7 19:05:41 2019 from 192.168.244.132
[root@test ~]# ls -l
total 8
-rw-------. 1 root root 1732 Dec 26 20:03 anaconda-ks.cfg
-rwxr-xr-x. 1 god  god     0 Jan  7 19:05 god.txt  #已经成功创建并赋予文件权限
-rw-r--r--. 1 root root   44 Jan  7 19:05 test.txt

或者直接

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected] ls -l  /root/god.txt
-rwxr-xr-x. 1 god god 0 Jan  7 19:05 /root/god.txt

创建god.sh

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles/testbox/files
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/files/god.sh
echo "this is a test script"
echo "If you see this message, the script is executed successfully."
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml
- name: Print server name and user to remote testbox
  shell: "echo 'Currently {{ user }} is loggging {{ server_name }}' > {{ output }}"
- name: create a file
  file: 'path=/root/god.txt state=touch mode=0755 owner=god group=god'
#添加以下内容
- name: copy a file
  copy: 'remote_src=no src=roles/testbox/files/god.sh dest=/root/god.sh mode=0644 force=yes'
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml

验证并查看

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected] ls -l /root/god.sh
-rw-r--r--. 1 root root 99 Jan  7 19:19 /root/god.sh

演示stat与debug模块

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml
....
# 文件末尾添加以下内容
- name: check if god.sh exists
  stat: 'path=/root/gid.sh'
  register: script_stat

- debug: msg="god.sh exists"
  when: script_stat.stat.exists
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml

PLAY [testservers] *************************************************************

TASK [Gathering Facts] *********************************************************
ok: [test.example.com]

TASK [testbox : Print server name and user to remote testbox] ******************
changed: [test.example.com]

TASK [testbox : create a file] *************************************************
changed: [test.example.com]

TASK [testbox : copy a file] ***************************************************
ok: [test.example.com]

TASK [testbox : check if god.sh exists] ****************************************
ok: [test.example.com]

TASK [testbox : debug] *********************************************************
ok: [test.example.com] => {
    "msg": "god.sh exists"
}

PLAY RECAP *********************************************************************
test.example.com           : ok=6    changed=2    unreachable=0    failed=0  

(.py3-a2.5-env) [deploy@ansible test-playbooks]$

演示command模块

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml
# 末尾添加以下内容
- name: run the script
  command: 'sh /root/god.sh'
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml

PLAY [testservers] *************************************************************

TASK [Gathering Facts] *********************************************************
ok: [test.example.com]

TASK [testbox : Print server name and user to remote testbox] ******************
changed: [test.example.com]

TASK [testbox : create a file] *************************************************
changed: [test.example.com]

TASK [testbox : copy a file] ***************************************************
ok: [test.example.com]

TASK [testbox : check if god.sh exists] ****************************************
ok: [test.example.com]

TASK [testbox : debug] *********************************************************
ok: [test.example.com] => {
    "msg": "god.sh exists"
}

TASK [testbox : run the script] ************************************************
changed: [test.example.com]

PLAY RECAP *********************************************************************
test.example.com           : ok=7    changed=3    unreachable=0    failed=0  

template模块演示

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim inventory/testenv
# 末尾添加以下内容
server_name=test.example.com
port=80
user=deploy
worker_processes=4
max_open_file=65505
root=/www
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles/testbox/templates (.py3
-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/templates/nginx.conf.j2 # For more information on configuration, see: user {{ user }}; worker_processes {{ worker_processes }}; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events { worker_connections {{ max_open_file }}; } 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; #keepalive_timeout 0; keepalive_timeout 65; #gzip on; # Load config files from the /etc/nginx/conf.d directory # The default server is in conf.d/default.conf #include /etc/nginx/conf.d/*.conf; server { listen {{ port }} default_server; server_name {{ server_name }}; #charset koi8-r; #access_log logs/host.access.log main; location / { root {{ root }}; index index.html index.htm; } error_page 404 /404.html; location = /404.html { root /usr/share/nginx/html; } # redirect server error pages to the static page /50x.html # error_page 500 502 503 504 /50x.html; location = /50x.html { root /usr/share/nginx/html; } } } 配置main.yml文件 (.py3-a2.5-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml # 末尾添加如下内容 - name: write the nginx config file template: src=roles/testbox/templates/nginx.conf.j2 dest=/etc/nginx/nginx.c onf - name: ensure nginx is at the latest version yum: pkg=nginx state=latest - name: start nginx service service: name=nginx state=started (.py3-a2.5-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml PLAY [testservers] ************************************************************* TASK [Gathering Facts] ********************************************************* ok: [test.example.com] TASK [testbox : Print server name and user to remote testbox] ****************** changed: [test.example.com] TASK [testbox : create a file] ************************************************* changed: [test.example.com] TASK [testbox : copy a file] *************************************************** ok: [test.example.com] TASK [testbox : check if god.sh exists] **************************************** ok: [test.example.com] TASK [testbox : debug] ********************************************************* ok: [test.example.com] => { "msg": "god.sh exists" } TASK [testbox : run the script] ************************************************ changed: [test.example.com] TASK [testbox : write the nginx config file] *********************************** changed: [test.example.com] TASK [testbox : ensure nginx is at the latest version] ************************* changed: [test.example.com] TASK [testbox : start nginx service] ******************************************* changed: [test.example.com] PLAY RECAP ********************************************************************* test.example.com : ok=10 changed=6 unreachable=0 failed=0 (.py3-a2.5-env) [deploy@ansible test-playbooks]$

查看并验证

(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected] cat /etc/nginx/nginx.conf
# For more information on configuration, see:
user              deploy;
worker_processes  4;

error_log  /var/log/nginx/error.log;

pid        /var/run/nginx.pid;

events {
    worker_connections  65505;
}


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;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    # Load config files from the /etc/nginx/conf.d directory
    # The default server is in conf.d/default.conf
    #include /etc/nginx/conf.d/*.conf;
    server {
        listen       80 default_server;
        server_name  test.example.com;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        location / {
            root   /www;
            index  index.html index.htm;
        }

        error_page  404              /404.html;
        location = /404.html {
            root   /usr/share/nginx/html;
        }

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   /usr/share/nginx/html;
        }

    }

}
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ ssh [email protected] ps -ef | grep nginx
root       5047      1  0 19:49 ?        00:00:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
deploy     5048   5047  0 19:49 ?        00:00:00 nginx: worker process
deploy     5049   5047  0 19:49 ?        00:00:00 nginx: worker process
deploy     5050   5047  0 19:49 ?        00:00:00 nginx: worker process
deploy     5051   5047  0 19:49 ?        00:00:00 nginx: worker process

至此ansible的安装、配置与演示已全部完成。

 

posted on 2019-01-10 19:58 Lucky_7 阅读(...) 评论(...) 编辑 收藏

你可能感兴趣的:(Jenkins+Gitlab+Ansible自动化部署(二))