接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..tar.xz -C /usr/local/src/
[root@ansible ~]# cd /usr/local/src/Python-3.6./
[root@ansible ~]# cd /usr/local/src/Python-3.6./
[root@ansible Python-3.6.]# ./configure --prefix=/usr/local/ --with-ensurepip=install --enable-shared LDFLAGS="-Wl,-rpath /usr/local/lib"
#竟然报错
configure: error: in `/usr/local/src/Python-3.6.':
configure: error: no acceptable C compiler found in $PATH
See `config.log' for more details
# 根据报错信息,需要安装GCC套件
[root@ansible Python-3.6.]# yum install -y gcc
# 然后再次执行编译操作,完事执行安装
[root@ansible Python-3.6.]# make && make altinstall
# 然而又报错了
....
import pip
zipimport.ZipImportError: can't decompress data; zlib not available
make: *** [altinstall] Error
# 提示很明显了直接执行
[root@ansible Python-3.6.]# yum install zlib*
# 然后再吃运行安装命令即可
[root@ansible Python-3.6.]# make && make altinstall
# 当看到
.....
Collecting setuptools
Collecting pip
Installing collected packages: setuptools, pip
Successfully installed pip-9.0. setuptools-39.0.
# 表明安装成功
# 接着安装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=, 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=, 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=, 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=, 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=, 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=, 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=, 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=, 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=, 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=, 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.
/usr/lib/python2./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. .py3-a2.-env
Already using interpreter /usr/local/bin/python3.
Using base prefix '/usr/local'
New python executable in /home/deploy/.py3-a2.-env/bin/python3.
Also creating executable in /home/deploy/.py3-a2.-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.-env目录下
[deploy@ansible ~]$ cd /home/deploy/.py3-a2.-env/
[deploy@ansible .py3-a2.-env]$ git clone https://github.com/ansible/ansible.git

4. 加载python3.6.5 virtualenv环境

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

5. 安装ansible依赖包

# 安装依赖包
(.py3-a2.-env) [deploy@ansible .py3-a2.-env]$ pip install paramiko PyYAML jinja2
(.py3-a2.-env) [deploy@ansible .py3-a2.-env]$ ll
total
drwxrwxr-x. deploy deploy Jan : ansible
drwxrwxr-x. deploy deploy Jan : bin
drwxrwxr-x. deploy deploy Jan : include
drwxrwxr-x. deploy deploy Jan : lib
(.py3-a2.-env) [deploy@ansible .py3-a2.-env]$ pwd
/home/deploy/.py3-a2.-env

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

# 确认ansible源码包在.py3-a2.-env目录下
# 进入ansible目录
(.py3-a2.-env) [deploy@ansible .py3-a2.-env]$ cd ansible/
(.py3-a2.-env) [deploy@ansible ansible]$ pwd
/home/deploy/.py3-a2.-env/ansible
(.py3-a2.-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.-env) [deploy@ansible ansible]$ source /home/deploy/.py3-a2.-env/ansible/hacking/env-setup -q #在此虚拟环境下加载ansible2.5版本

7.验证ansible版本

(.py3-a2.-env) [deploy@ansible ansible]$ ansible --version
ansible 2.5. (stable-2.5 6548b7a558) last updated // :: (GMT +)
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.-env/ansible/lib/ansible
executable location = /home/deploy/.py3-a2.-env/ansible/bin/ansible
python version = 3.6. (default, Jan , ::) [GCC 4.8. (Red Hat 4.8.-)]
# 至此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 :: CST on pts/
[deploy@ansible ~]$ source .py3-a2.-env/bin/activate
(.py3-a2.-env) [deploy@ansible ~]$ source .py3-a2.-env/ansible/hacking/env-setup -q
(.py3-a2.-env) [deploy@ansible ~]$ ansible-playbook --version
ansible-playbook 2.5. (stable-2.5 6548b7a558) last updated // :: (GMT +)
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.-env/ansible/lib/ansible
executable location = /home/deploy/.py3-a2.-env/ansible/bin/ansible-playbook
python version = 3.6. (default, Jan , ::) [GCC 4.8. (Red Hat 4.8.-)]

开始编写playbooks

(.py3-a2.-env) [deploy@ansible ~]$ mkdir test-playbooks
(.py3-a2.-env) [deploy@ansible ~]$ cd test-playbooks/
(.py3-a2.-env) [deploy@ansible test-playbooks]$ mkdir inventory
(.py3-a2.-env) [deploy@ansible test-playbooks]$ mkdir roles
(.py3-a2.-env) [deploy@ansible test-playbooks]$ cd inventory
(.py3-a2.-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.-env) [deploy@ansible inventory]$ cd ..
(.py3-a2.-env) [deploy@ansible test-playbooks]$ ls
inventory roles
(.py3-a2.-env) [deploy@ansible test-playbooks]$ cd roles/
(.py3-a2.-env) [deploy@ansible roles]$ mkdir testbox
(.py3-a2.-env) [deploy@ansible roles]$ cd testbox/
(.py3-a2.-env) [deploy@ansible testbox]$ mkdir tasks
(.py3-a2.-env) [deploy@ansible testbox]$ cd tasks/
(.py3-a2.-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.-env) [deploy@ansible tasks]$ cd ../../..
(.py3-a2.-env) [deploy@ansible test-playbooks]$ pwd
/home/deploy/test-playbooks
(.py3-a2.-env) [deploy@ansible tasks]$ cd ../../..
(.py3-a2.-env) [deploy@ansible test-playbooks]$ pwd
/home/deploy/test-playbooks
(.py3-a2.-env) [deploy@ansible test-playbooks]$ vim deploy.yml - hosts: "testservers"
gather_facts: true
remote_user: root
   
   
  roles:
- testbox

查看test_playbooxs目录结构

(.py3-a2.-env) [deploy@ansible test-playbooks]$ tree .
.
├── deploy.yml
├── inventory
│?? └── testenv
└── roles
└── testbox
└── tasks
└── main.yml directories, 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.-env) [deploy@ansible test-playbooks]$ su - root
Password:
Last login: Mon Jan :: CST from 192.168.244.1 on pts/
[root@ansible ~]# vim /etc/hosts
....
192.168.244.133 test.example.com
[root@ansible ~]# exit
logout
(.py3-a2.-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 deploy@ansible.example.com
The key's randomart image is:
+---[RSA ]----+
| .. .. |
| o+o=.. . . |
| oo.o.+..o + o .|
|.. .o... o o .o.|
|. .+ S. . oE|
| ooo + +|
| + . %o|
| . +o@|
| oB@|
+----[SHA256]-----+
(.py3-a2.-env) [deploy@ansible test-playbooks]$ ssh-copy-id -i /home/deploy/.ssh/id_rsa.pub root@test.example.com
/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::0d::d8::6d::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: key(s) remain to be installed -- if you are prompted now it is to install the new keys
root@test.example.com's password: Number of key(s) added: Now try logging into the machine, with: "ssh 'root@test.example.com'"
and check to make sure that only the key(s) you wanted were added.
(.py3-a2.-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com
Last login: Mon Jan :: from 192.168.244.1
[root@test ~]# whoami
root
[root@test ~]# hostname
test.example.com

测试部署

(.py3-a2.-env) [deploy@ansible ~]$ cd test-playbooks/
(.py3-a2.-env) [deploy@ansible test-playbooks]$ ls
deploy.yml inventory roles
(.py3-a2.-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= changed= unreachable= failed=
# 以下内容可以看出已经成功在远程被部署主机test.example.com上创建一个test.txt文件,且文件内容与预先设置的一致
(.py3-a2.-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com
Last login: Mon Jan :: 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.-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com
Last login: Mon Jan :: 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... (%################################# [%]
Updating / installing...
:nginx-release-centos--.el7.ngx ( %################################# [%]

退出被部署主机

[root@test ~]# exit
logout
Connection to test.example.com closed.
(.py3-a2.-env) [deploy@ansible test-playbooks]$ pwd
/home/deploy/test-playbooks
(.py3-a2.-env) [deploy@ansible test-playbooks]$ ls
deploy.yml inventory roles
(.py3-a2.-env) [deploy@ansible test-playbooks]$
(.py3-a2.-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.-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= changed= unreachable= failed=

登录到远程主机查看

(.py3-a2.-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com
Last login: Mon Jan :: from 192.168.244.132
[root@test ~]# ls -l
total
-rw-------. root root Dec : anaconda-ks.cfg
-rwxr-xr-x. god god Jan : god.txt #已经成功创建并赋予文件权限
-rw-r--r--. root root Jan : test.txt

或者直接

(.py3-a2.-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com ls -l  /root/god.txt
-rwxr-xr-x. god god Jan : /root/god.txt

创建god.sh

(.py3-a2.-env) [deploy@ansible test-playbooks]$ mkdir roles/testbox/files
(.py3-a2.-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.-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.-env) [deploy@ansible test-playbooks]$ ansible-playbook -i inventory/testenv ./deploy.yml

验证并查看

(.py3-a2.-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com ls -l /root/god.sh
-rw-r--r--. root root Jan : /root/god.sh

演示stat与debug模块

(.py3-a2.-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.-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= changed= unreachable= failed= (.py3-a2.-env) [deploy@ansible test-playbooks]$

演示command模块

(.py3-a2.-env) [deploy@ansible test-playbooks]$ vim roles/testbox/tasks/main.yml
# 末尾添加以下内容
- name: run the script
command: 'sh /root/god.sh'
(.py3-a2.-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= changed= unreachable= failed=

template模块演示

(.py3-a2.-env) [deploy@ansible test-playbooks]$ vim inventory/testenv
# 末尾添加以下内容
server_name=test.example.com
port=
user=deploy
worker_processes=
max_open_file=
root=/www
(.py3-a2.5-env) [deploy@ansible test-playbooks]$ mkdir roles/testbox/templates
(.py3-a2.-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 ;
keepalive_timeout ; #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.-env) [deploy@ansible test-playbooks]$ ssh root@test.example.com cat /etc/nginx/nginx.conf
# For more information on configuration, see:
user deploy;
worker_processes ; error_log /var/log/nginx/error.log; pid /var/run/nginx.pid; events {
worker_connections ;
} 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 ;
keepalive_timeout ; #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 root@test.example.com 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的安装、配置与演示已全部完成。

Jenkins+Gitlab+Ansible自动化部署(二)的更多相关文章

  1. Jenkins+Gitlab+Ansible自动化部署(一)

    首先准备实验环境 虚拟机 主机名 IP地址 服务 系统版本 内核版本 Vmware Workstation 14 gitlab.example.com 192.168.244.130 gitlab  ...

  2. Jenkins+Gitlab+Ansible自动化部署(三)

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

  3. Jenkins+Gitlab+Ansible自动化部署(五)

    Freestyle Job实现静态网站部署交付(接Jenkins+Gitlab+Ansible自动化部署(四)https://www.cnblogs.com/zd520pyx1314/p/102445 ...

  4. Jenkins+Gitlab+Ansible自动化部署(六)

    Pipeline Job实现Nginix+MySQL+PHP+Wordpress实现自动化部署交付(Jenkins+Gitlab+Ansible自动化部署(五)https://www.cnblogs. ...

  5. Jenkins+Gitlab+Ansible自动化部署(四)

    接Jenkins+Gitlab+Ansible自动化部署(三)https://www.cnblogs.com/zd520pyx1314/p/10235394.html Jenkins应用 Jenkin ...

  6. 【开发工具】Jenkins+Gitlab实现自动化部署

    我在尝试在容器中安装Jenkins时,初衷是希望使用docker in docker 的模式来实现Jenkins slave容器按需创建.在实现的时候需要在Jenkins 中安装Kubernetes插 ...

  7. 基于Jenkins+Gitlab的自动化部署实战

    故事背景 一个中小型企业,是典型的互联网公司,当初期的时候可能运维只能标配到2~3人,此时随着公司的发展,项目会逐渐增多.前期部署项目可能都是手动的, 俗称“人肉部署”,这简直是无比的痛苦,不能忍受的 ...

  8. jenkins +gitlab +docker 自动化部署tomcat 项目

    实验环境 实验设备 三台服务器 centos 7.X 以上 内存 2-3G左右 192.168.1.195 (jenkins最新+ git 2.8+maven 3.5 +tomcat 8+java1. ...

  9. 从Docker 到Jenkins 到Ansible的部署经验

    从Docker 到Jenkins 到Ansible的部署经验 工作中,除了开发功能,还负责系统的部署工作.我从频繁的部署工作中,逐渐找到了一些偷懒的方法.从传统的Java -jar命令启动服务,到通过 ...

随机推荐

  1. listen 60

    Barbie Exposure May Limit Girls' Career Imagination The ubiquitous Barbie doll: she's been everythin ...

  2. leetcode 191 Number of 1 Bits(位运算)

    Write a function that takes an unsigned integer and returns the number of ’1' bits it has (also know ...

  3. ACM学习历程—HDU 5317 RGCDQ (数论)

    Problem Description Mr. Hdu is interested in Greatest Common Divisor (GCD). He wants to find more an ...

  4. C++正确的cin输入

    void test1(void) { int number; cout << ">> pls input a integer number:"; while ...

  5. printf函数指向串口的方法

    简单地说:想在mdk 中用printf,需要同时重定义fputc函数和避免使用semihosting(半主机模式),标准库函数的默认输出设备是显示器,要实现在串口或LCD输出,必须重定义标准库函数里调 ...

  6. Getting Started with OpenMP

    Getting Started with OpenMP* Abstract As you probably know by now, to get the maximum performance be ...

  7. lwip 分析一

    一.接收端 1.通过ehternetif_input void ethernetif_input(struct netif *netif) {   struct ethernetif *etherne ...

  8. KMP匹配

    字符串匹配是计算机的基本任务之一. 举例来说,有一个字符串"BBC ABCDAB ABCDABCDABDE",我想知道,里面是否包含另一个字符串"ABCDABD" ...

  9. maven变量说明

    Maven内置变量说明: ${basedir} 项目根目录 ${project.build.directory} 构建目录,缺省为target ${project.build.outputDirect ...

  10. [转]C/C++获取当前系统时间

    原文转自:http://www.cnblogs.com/mfryf/archive/2012/02/13/2349360.html 个人觉得第二种还是比较实用的,而且也是最常用的~ 不过当计算算法耗时 ...