Linux Centos下Nginx反向代理教程

主机要求:Centos系统,内存64MB及以上、80端口没有被占用

1、升级系统、卸载Apache释放80端口

Yum update -y
Yum remove httpd -y

2、安装EPEL repo

rpm -Uvh http://mirror.ancl.hawaii.edu/linux/epel/6/i386/epel-release-6-8.noarch.rpm

EPEL repo下载地址:https://fedoraproject.org/wiki/EPEL

3、安装Nginx,并设置

安装Nginx

yum install nginx -y

调整Nginx配置

cd /etc/nginx/conf.d
mv default.conf default.conf.disabled

4、创建Nginx反代配置文件

cd /etc/nginx/conf.d
vi yourdomain.com                 

粘贴以下内容:

server {
      listen 80;
      server_name yourdomain.com;   
      access_log off;
      error_log off;
      location / {
      proxy_pass http://需要反代的服务器IP/;
      proxy_redirect off;
      proxy_set_header Host $host;
      proxy_set_header X-Real-IP $remote_addr;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_max_temp_file_size 0;
      client_max_body_size 10m;
      client_body_buffer_size 128k;
      proxy_connect_timeout 90;
      proxy_send_timeout 90;
      proxy_read_timeout 90;
      proxy_buffer_size 4k;
      proxy_buffers 4 32k;
      proxy_busy_buffers_size 64k;
      proxy_temp_file_write_size 64k;
   }
} 

然后保存。

5、设置防火墙,允许80端口访问

iptables -I INPUT 5 -m state --state NEW -p tcp --dport 80 -j ACCEPT 
service iptables save 
service iptables restart

6、启动Nginx

service nginx start

将Centos的yum源更换为国内的阿里云源

由于centos默认的Yum源速度太慢,在使用的时候不方便,于是将yum源改成阿里的源。

备份

mv /etc/yum.repos.d/CentOS-Base.repo /etc/yum.repos.d/CentOS-Base.repo.backup

下载新的CentOS-Base.repo 到/etc/yum.repos.d/

  • CentOS 5
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-5.repo

或者

curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-5.repo
  • CentOS 6
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo

或者

curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-6.repo
  • CentOS 7
wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

或者

curl -o /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo

生成yum缓存

yum clean all
yum makecache

添加其他源

添加EPEL源

  • Centos6
wget -O /etc/yum.repos.d/epel-6.repo http://mirrors.aliyun.com/repo/epel-6.repo
  • Centos7
wget -O /etc/yum.repos.d/epel-7.repo http://mirrors.aliyun.com/repo/epel-7.repo `
  • 清理缓存并生成新的缓存
yum clean all  
yum makecache 

CentOS 中用 Split 命令分割文件的方法

CentOS 里切割大文件的命令如下:

NAME
split – split a file into pieces
SYNOPSIS
split [OPTION]… [INPUT [PREFIX]]
DESCRIPTION
Output  fixed-size pieces of INPUT to PREFIXaa, PREFIXab, …; default size is 1000 lines, and default PREFIX is ‘x’.  With no INPUT, or when INPUT is -, read standard input.
Mandatory arguments to long options are mandatory for short options too.
-a, –suffix-length=N
generate suffixes of length N (default 2)
–additional-suffix=SUFFIX
append an additional SUFFIX to file names
-b, –bytes=SIZE
put SIZE bytes per output file
-C, –line-bytes=SIZE
put at most SIZE bytes of lines per output file
-d, –numeric-suffixes[=FROM]
use numeric suffixes instead of alphabetic; FROM changes the start value (default 0)
-e, –elide-empty-files
do not generate empty output files with ‘-n’
–filter=COMMAND
write to shell COMMAND; file name is $FILE
-l, –lines=NUMBER
put NUMBER lines per output file
-n, –number=CHUNKS
generate CHUNKS output files; see explanation below
-u, –unbuffered
immediately copy input to output with ‘-n r/…’
–verbose
print a diagnostic just before each output file is opened
–help display this help and exit
–version
output version information and exit

常用选项说明如下:

-a : 指定后缀长度
-b : 每个文件多少字节
-d : 使用数字后缀而不是字母
-l : 指定每个文件的行数
比如我想让后缀长度为 2,即 -a 2。用数字后缀 -d。每个文件 10M,即 -b 10m。命令可以设计如下:

split -a 2 -d -b 10m /var/lib/mysql/general.log nowamagic

会在 /root 文件夹下生成下面的切割文件:

nowamagic00
nowamagic01
nowamagic02
nowamagic03
nowamagic04
nowamagic05
nowamagic06
nowamagic07
nowamagic08
nowamagic09

除了最后一个文件不是10M(有可能恰好10M,不过几率很小),其它都是。

Centos 单用户模式修改忘记的Root密码

由于疏忽,Centos的密码给忘记了,也没有备份,无奈只好使用单用户模式修改Root密码了。

Centos启动时,按E键进入编辑模式,

未分类

找到Linux 16开头的内容,定位到ro 修改为rw 并且在后面添加命令init=/sysroot/bin/sh 添加以后按Ctrl+X键启动。

未分类

启动后会进入单用户模式,

未分类

使用命令ls可以查看当前目录的文件,其中sysroot就是系统的文件,接下来就是要可以修改Root密码了

未分类

使用chroot /sysroot/ 命令进入到正常系统 中去。passwd root修改密码。

如果乱码(白点),使用 “#LANG=en” 修改成英文就可以了。

注意一定要在修改完密码后,输入

#touch /.autorelabel

CentOS 7安装pip3

首先要确保在CentOS 7上已经安装了EPEL仓库。如果没有安装,执行以下命令安装:

yum install -y epel-release

安装后,安装pip3

$sudo yum install python34-pip
$pip3.4 install foo

Centos 禁止ROOT远程登录

1、建立一个普通用户

#useradd -G root zhj001
#passwd zhj001 修改用户密码

2、修改/etc/ssh/sshd_config

#vi /etc/ssh/sshd_config

PermitRootLogin yes

改为

PermitRootLogin no

3、重启sshd服务

#service sshd restart

远程治理用普通用户uploader登录,然后用 su root 切换到root用户拿到最高权限。

Ansible+Jenkins+Svn实现自动化部署

  • 实验平台:CentOS6.8
  • 主机使用IP: 10.113.128.120
  • Jenkins版本:2.46.3

一、安装ansible

1. yum安装

yum -y install ansible

如果yum安装没有找到ansible包
使用阿里云的源

http://mirrors.aliyun.com/repo/epel-6.repo
cd /etc/yum.repo.d/
wget http://mirrors.aliyun.com/repo/epel-6.repo  #下载源

2. 配置文件

cd /etc/ansible/
ll

total 28
-rw-r--r-- 1 root root 18066 Jun  2 05:49 ansible.cfg       #ansible主配置文件
-rw-r--r-- 1 root root  1016 Jun  2 05:49 hosts             #定义主机组
drwxr-xr-x 2 root root  4096 Jun  2 05:49 roles             #定义规则

二、配置ansible

1. 为远程连接主机生成公/私钥

ssh-keygen -t rsa -P ''       #-t生成密钥类似(rsa/dsa) -P提供旧密码,'' 表示没有

Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
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:
5b:9e:3b:b7:04:47:e8:b3:28:cd:5a:ff:5e:a3:ae:b2 root@TLCUM01
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|           .     |
|          . .    |
|         . .     |
|        S = .    |
|       o = *     |
|      . * + . o  |
|       +...o.o . |
|      . Eo+B*.   |
+-----------------+
cd /root/.ssh/
ll

total 8
-rw------- 1 root root 1675 Jul  4 08:34 id_rsa         #私钥
-rw-r--r-- 1 root root  394 Jul  4 08:34 id_rsa.pub     #公钥

2. 写入信任文件

cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys   #将公钥导入authorized_keys并分发到需远程控制的服务器/root/.ssh/目录内(需新建改目录)

完成上步后:

ssh + 远程服务器IP  #即可实现免密钥登入(ansible主机必须与其互通)

3.定义主机

vim /etc/ansible/hosts

[bs]
10.113.128.28
[yy]
10.113.128.196
[bb]
10.113.128.34

4. 测试

ansible 0BS -m command -a pwd
10.113.128.28 | SUCCESS | rc=0 >>
/root

ansible命令详解

ansible
Usage: ansible <host-pattern> [options]

Options:
  -a MODULE_ARGS, --args=MODULE_ARGS        #模块的参数,如果执行默认COMMAND的模块,即是命令参数,如:“date”,"pwd"等等
                        module arguments    #模块参数
  --ask-vault-pass      ask for vault password
  -B SECONDS, --background=SECONDS          #后台运行超时时间
                        run asynchronously, failing after X seconds
                        (default=N/A)
  -C, --check           don't make any changes; instead, try to predict some
                        of the changes that may occur   #只是测试一下会改变什么内容,不会真正去执行;相反,试图预测一些可能发生的变化
  -D, --diff            when changing (small) files and templates, show the
                        differences in those files; works great with --check    
  -e EXTRA_VARS, --extra-vars=EXTRA_VARS
                        set additional variables as key=value or YAML/JSON
  -f FORKS, --forks=FORKS                                   #并行任务数。NUM被指定为一个整数,默认是5
                        specify number of parallel processes to use
                        (default=5)
  -h, --help            show this help message and exit     #打开帮助文档API
  -i INVENTORY, --inventory-file=INVENTORY                  #指定库存主机文件的路径,默认为/etc/ansible/hosts
                        specify inventory host path
                        (default=/etc/ansible/hosts) or comma separated host
                        list.
  -l SUBSET, --limit=SUBSET                                 #进一步限制所选主机/组模式  --limit=192.168.91.135 只对这个ip执行
                        further limit selected hosts to an additional pattern
  --list-hosts          outputs a list of matching hosts; does not execute
                        anything else
  -m MODULE_NAME, --module-name=MODULE_NAME                 #执行模块的名字,默认使用 command 模块,所以如果是只执行单一命令可以不用 -m参数
                        module name to execute (default=command)
  -M MODULE_PATH, --module-path=MODULE_PATH                 #要执行的模块的路径,默认为/usr/share/ansible/
                        specify path(s) to module library (default=None)
  --new-vault-password-file=NEW_VAULT_PASSWORD_FILE
                        new vault password file for rekey
  -o, --one-line        condense output                     #压缩输出,摘要输出.尝试一切都在一行上输出。
  --output=OUTPUT_FILE  output file name for encrypt or decrypt; use - for
                        stdout
  -P POLL_INTERVAL, --poll=POLL_INTERVAL                    #调查背景工作每隔数秒。需要-b
                        set the poll interval if using -B (default=15)
  --syntax-check        perform a syntax check on the playbook, but do not
                        execute it
  -t TREE, --tree=TREE  log output to this directory                #将日志内容保存在该输出目录,结果保存在一个文件中在每台主机上。
  --vault-password-file=VAULT_PASSWORD_FILE
                        vault password file
  -v, --verbose         verbose mode (-vvv for more, -vvvv to enable
                        connection debugging)                       #详细信息
  --version             show program's version number and exit      #输出ansible的版本

  Connection Options:
    control as whom and how to connect to hosts

    -k, --ask-pass      ask for connection password     #登录密码,提示输入SSH密码而不是假设基于密钥的验证
    --private-key=PRIVATE_KEY_FILE, --key-file=PRIVATE_KEY_FILE
                        use this file to authenticate the connection
    -u REMOTE_USER, --user=REMOTE_USER
                        connect as this user (default=None)
    -c CONNECTION, --con=CONNECTION              #连接类型使用。可能的选项是paramiko(SSH),SSH和地方。当地主要是用于crontab或启动。
                        connection type to use (default=smart)
    -T TIMEOUT, --timeout=TIMEOUT       #指定SSH默认超时时间,  默认是10S
                        override the connection timeout in seconds
                        (default=10)
    --ssh-common-args=SSH_COMMON_ARGS
                        specify common arguments to pass to sftp/scp/ssh (e.g.
                        ProxyCommand)
    --sftp-extra-args=SFTP_EXTRA_ARGS
                        specify extra arguments to pass to sftp only (e.g. -f,
                        -l)
    --scp-extra-args=SCP_EXTRA_ARGS
                        specify extra arguments to pass to scp only (e.g. -l)
    --ssh-extra-args=SSH_EXTRA_ARGS
                        specify extra arguments to pass to ssh only (e.g. -R)

  Privilege Escalation Options:
    control how and which user you become as on target hosts

    -s, --sudo          run operations with sudo (nopasswd) (deprecated, use
                        become)
    -U SUDO_USER, --sudo-user=SUDO_USER
                        desired sudo user (default=root) (deprecated, use
                        become)     #远程用户, 默认是root用户
    -S, --su            run operations with su (deprecated, use become)
    -R SU_USER, --su-user=SU_USER   #指定SU的用户,默认是root用户
                        run operations with su as this user (default=root)
                        (deprecated, use become)
    -b, --become        run operations with become (does not imply password
                        prompting)
    --become-method=BECOME_METHOD
                        privilege escalation method to use (default=sudo),
                        valid choices: [ sudo | su | pbrun | pfexec | doas |
                        dzdo | ksu | runas ]
    --become-user=BECOME_USER
                        run operations as this user (default=root)
    --ask-sudo-pass     ask for sudo password (deprecated, use become)
    --ask-su-pass       ask for su password (deprecated, use become)
    -K, --ask-become-pass           #提示密码使用sudo,sudo表示提权操作
                        ask for privilege escalation password
</host-pattern>

三、Jenkins

1. 官网下载jenkins

https://jenkins.io/download/                     #这里我下载通用war包(在此我下的2.46.3版本2.60.1版本在tomcat下跑不起来,报错是版本有问题~)
http://mirrors.jenkins.io/war-stable/2.46.3/     #2.46.3版本的下载地址
还可以直接跑(建议使用Tomcat的方式):
改变端口再次执行,
java -jar jenkins.war --httpPort=$HTTP_PORT, 例如java -jar jenkins.war --httpPort=1080

2. 访问测试

10.113.128.120:8080/jenkins   #或localhost:8080/jenkins

四.配置Jenkins

1. 配置登录

将/root/.jenkins/secrets/initialAdminPassword里的密码文件拷贝进去

未分类

2. 选择第一个

未分类

3. 开始安装

未分类

4. 配置用户信息

未分类

5. 安装完成

未分类

6. 测试(10.113.128.120:8080/jenkins)

未分类

五、搭建svn

1. 安装

sudo yum -y install subversion  #安装svn
mkdir /ane/svn/tl -p            #创建选择在var路径下创建版本库
svnadmin create /ane/svn/tl/    #在第二步建立的路径基础上,创建版本库
cd /ane/svn/tl/conf             #进入配置目录
ll

authz:                          #负责账号权限的管理,控制账号是否读写权限
passwd:                         #负责账号和密码的用户名单管理
svnserve.conf:                  #svn服务器配置文件
vim authz                       #编辑

[aliases]
# joe = /C=XZ/ST=Dessert/L=Snake City/O=Snake Oil, Ltd./OU=Research Institute/CN=Joe Average

[groups]
# harry_and_sally = harry,sally
# harry_sally_and_joe = harry,sally,&joe

# [/foo/bar]
# harry = rw
# &joe = r
# * =

# [repository:/baz/fuz]
# @harry_and_sally = rw
# * = r

[]
ane = rw                            #新增(ane用户读写权限)
vim passwd                          #编辑

[users]
# harry = harryssecret
# sally = sallyssecret
ane = redhat                        #给ane用户密码为redhat

vim svnserve.conf                   #编辑


[general]

anon-access = read
auth-access = write

password-db = /ane/svn/tl/conf/passwd   #使用paswwd文件里的配置;这里要给绝对路径

authz-db = /ane/svn/tl/conf/authz       #使用authz文件里的配置;这里要给绝对路径

realm = My First Repository             #Svn讲解

六、构建

1. 首先配置好ansible里的规则(playbook) 进入roles

pwd
/etc/ansible/roles
mkdir tlsit             #创建palybook目录(tlsit项目名称)
cd /etc/ansible/roles/tlsit/
vim bs.yml

-hosts: bs             #这个是你选择的主机
 roles:
 -bs                   #这个是你下步创建的目录
NullCopy

再在bs.yml同级下创建bs文件为其添加远程构建步骤

mkdir bs
cd bs
mkdir tasks
vim main.yml

- name: del
  shell: rm -rf /ane/update/*
- name: copy
  copy: src=/root/.jenkins/workspace/sit-0BS/ROOT/ROOT.war  dest=/ane/update/
- name: update
  shell: sh /ane/script/startApp.sh

2. 进入Jenkins的主界面

点击系统管理->选择管理插件->安装Ansible plugin插件(右上角搜索),点击直接安装

3. 进入Jenkins的主界面点击新建或创建一个新任务

4. 输入项目的名字选择第一个点击OK

未分类

5. 选择源码管理中的Subversion(SVN) 填写第五步搭建SVN的地址(里面需要有代码)

未分类

6. 选择构建 增加构建步骤 选择 Execute shell

未分类

7. 配置

未分类

8. 选择构建 增加构建步骤 选择 lnvoke Ansible Playbook

未分类

9. 配置

未分类

10. 点击立即构建。

蓝色–>成功
红色–>失败
白色–>为构建或取消构建

Ansible入门与Playbook实战

一、简要

1、关于Ansible

Ansible是一个部署一群远程主机的工具;Ansible通过SSH协议实现远程节点和管理节点之间的通信。理论上说,只要管理员通过ssh登录到一台远程主机上能做的操作,Ansible都可以做到。Ansible是python开发的,故依赖一些python库和组件,如:paramiko,PyYaml和jinja三个关键组件;

2、ansible架构

Ansible入门与playbook实战
右边绿色部分是被管理的主机(虚拟机,物理机,云主机等)从以上架构图中可以看出
ansible是由主机清单(配置),playbook(配置),以及各模块插件组成;
简单的说就是,用户(管理员)通过ansible的主机清单配置或Playbook配置(一组任务),调用ansible的各种模块及参数来对清单中的主机进行统一管理;

3、测试环境

本次测试环境:

  • ansible: CentOS7.4_x64 172.16.3.167 epel yum安装ansible
  • node1: 172.16.3.152 CenOS7.2_x64
  • node2: 172.16.3.216 CentOS7.2_x64

从ansible上生成ssh私钥同步到两台node主机上,实现无密钥登录管理(推荐)

[root@ansible ~]# ssh-keygen -t rsa

直接回车生成私钥;
同步到到两台node上

[root@ansible ~]# ssh-copy-id -i ~/.ssh/id_rsa 172.16.3.216
[root@ansible ~]# ssh-copy-id -i ~/.ssh/id_rsa 172.16.3.152

注意同步过程需要输入yes和各自的root密码即可;此进可直接ssh [email protected] 就无密码登录上去啦!
配置ansible的主机清单,即把node1与node2主机添加到管理清单中

[root@ansible ~]# egrep -v '(^$|^#)' /etc/ansible/hosts
[websrvs]
172.16.3.152
172.16.3.216

到此处配置的环境完成!

4、安装

目前,只要机器上安装了 Python 2.6 或 Python 2.7 (windows系统不可以做控制主机),都可以运行Ansible.
安装ansible很简单,可通过git从githu上直接获取代码,也可以像redhat/CentOS上通过yum进行安装,

[root@ansible ~]# yum install epel-release -y
[root@ansible ~]# yum install ansible -y
#查看版本
[root@ansible ~]# ansible --version
ansible 2.4.2.0
config file = /etc/ansible/ansible.cfg
configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
ansible python module location = /usr/lib/python2.7/site-packages/ansible
executable location = /usr/bin/ansible
python version = 2.7.5 (default, Nov 20 2015, 02:00:19) [GCC 4.8.5 20150623 (Red Hat 4.8.5-4)]

二、配置及获取帮助说明

通过rpm -ql ansible可以看到有很多文件,主要是配置文件和和可执行文件,以及所依赖的python库文件

1、配置与执行文件说明

ansible的主配置文件

/etc/ansible/ansible.cfg

这个文件主要定义了roles_path路径,主机清单路径,连接清单中的主机方式等配置,这些大部的默认配置已经足够我们平时使用,如需要特别配置可以自行去修改;

/etc/ansible/hosts

这个配置文件就是默认主机清单配置文件,可通过ansible.cfg重新定义的;
如定义一组主机:

[root@ansible ~]# egrep -v '(^$|^#)' /etc/ansible/hosts

[websrvs]
172.16.3.152
172.16.3.216

除了以上两个重要的配置文件还有三个重要的可执行文件分别是:
ansible 主执行程序,一般用于命令行下执行
ansible-playbook 执行playbook中的任务
ansible-doc 获取各模块的帮助信息

2、ansible 使用格式

ansible

HOST-PATTERN #匹配主机模式,如all表示所有主机
-m MOD_NAME #模块名 如:ping
-a MOD_ARGS #模块执行的参数
-f FORKS #生成几个子进行程执行
-C #(不执行,模拟跑)
-u Username #某主机的用户名
-c CONNection #连接方式(default smart)

完整示例:
[root@ansible ~]# ansible all -m shell -a "ifconfig|grep enp0s3"
172.16.3.152 | SUCCESS | rc=0 &gt;&gt;
enp0s3: flags=4163&lt;UP,BROADCAST,RUNNING,MULTICAST&gt; mtu 1500

172.16.3.216 | SUCCESS | rc=0 &gt;&gt;
enp0s3: flags=4163&lt;UP,BROADCAST,RUNNING,MULTICAST&gt; mtu 1500

3、ansible-doc 获取帮助信息

ansible模块比较多,可以通过ansible-doc –help 显示帮助信息
ansible doc -l 获取所有当前版本下的可用模块及简要信息
ansible-doc -s 模块名 获取指定模块帮助信息说明“

三、Ansible常用模块

1、copy模块

从本地copy文件分发到目录主机路径
参数说明:
src= 源文件路径
dest= 目标路径
注意src= 路径后面带/ 表示带里面的所有内容复制到目标目录下,不带/是目录递归复制过去
content= 自行填充的文件内容
owner 属主
group 属组
mode权限
示例:

ansible all -m copy -a "src=/etc/fstab dest=/tmp/fstab.ansible mode=600"
ansible all -m copy -a "content='hi theren' dest=/tmp/hi.txt"
到node1上查看
[root@node1 tmp]# ll
-rw------- 1 root root 465 2月 9 14:59 fstab.ansible
-rw-r--r-- 1 root root 9 2月 9 14:58 hi.txt

2、fetch模块

从远程主机拉取文件到本地
示例

[root@ansible ~]# ansible all -m fetch -a "src=/tmp/hi.txt dest=/tmp"
172.16.3.152 | SUCCESS =&gt; {
"changed": true,
"checksum": "279d9035886d4c0427549863c4c2101e4a63e041",
"dest": "/tmp/172.16.3.152/tmp/hi.txt",
"md5sum": "12f6bb1941df66b8f138a446d4e8670c",
"remote_checksum": "279d9035886d4c0427549863c4c2101e4a63e041",
"remote_md5sum": null
}
.......省略

说明:fetch使用很简单,src和dest,dest只要指定一个接收目录,默认会在后面加上远程主机及src的路径

3、command模块

在远程主机上执行命令,属于裸执行,非键值对显示;不进行shell解析;
示例1:

[root@ansible ~]# ansible all -m command -a "ifconfig"
172.16.3.152 | SUCCESS | rc=0 &gt;&gt;
enp0s3: flags=4163&lt;UP,BROADCAST,RUNNING,MULTICAST&gt; mtu 1500
inet 172.16.3.152 netmask 255.255.255.0 broadcast 172.16.3.255
.....省略.....
172.16.3.216 | SUCCESS | rc=0 &gt;&gt;
enp0s3: flags=4163&lt;UP,BROADCAST,RUNNING,MULTICAST&gt; mtu 1500
inet 172.16.3.216 netmask 255.255.255.0 broadcast 172.16.3.255
.....省略.....

示例2:

[root@ansible ~]# ansible all -m command -a "ifconfig|grep lo"
172.16.3.152 | FAILED | rc=2 &gt;&gt;
[Errno 2] 没有那个文件或目录

172.16.3.216 | FAILED | rc=2 &gt;&gt;
[Errno 2] 没有那个文件或目录

这就是因为command模块不是shell解析属于裸执行导致的
为了能达成以上类似shell中的解析,ansible有一个shell模块;

4、shell模块

由于commnad只能执行裸命令(即系统环境中有支持的命令),至于管道之类的功能不支持,
shell模块可以做到
示例:

[root@ansible ~]# ansible all -m shell -a "ifconfig|grep lo"
172.16.3.152 | SUCCESS | rc=0 &gt;&gt;
lo: flags=73&lt;UP,LOOPBACK,RUNNING&gt; mtu 65536
loop txqueuelen 0 (Local Loopback)

172.16.3.216 | SUCCESS | rc=0 &gt;&gt;
lo: flags=73&lt;UP,LOOPBACK,RUNNING&gt; mtu 65536
loop txqueuelen 0 (Local Loopback)

5、file模块

设置文件属性(创建文件)
常用参数:
path目标路径
state directory为目录,link为软件链接
group 目录属组
owner 属主
等,其他参数通过ansible-doc -s file 获取
示例1:创建目录

[root@ansible ~]# ansible all -m file -a "path=/var/tmp/hello.dir state=directory"
172.16.3.152 | SUCCESS =&gt; {
"changed": true,
"gid": 0,
"group": "root",
"mode": "0755",
"owner": "root",
"path": "/var/tmp/hello.dir",
"size": 6,
"state": "directory",
"uid": 0
}
172.16.3.216 | SUCCESS =&gt; {
"changed": true,
.....省略.....

示例2:创建软件链接

[root@ansible ~]# ansible all -m file -a "src=/tmp/hi.txt path=/var/tmp/hi.link state=link"
172.16.3.152 | SUCCESS =&gt; {
"changed": true,
"dest": "/var/tmp/hi.link",
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"size": 11,
"src": "/tmp/hi.txt",
"state": "link",
"uid": 0
}
172.16.3.216 | SUCCESS =&gt; {
"changed": true,
.....省略.....

6、cron模块

通过cron模块对目标主机生成计划任务
常用参数:
除了分(minute)时(hour)日(day)月(month)周(week)外
name: 本次计划任务的名称
state: present 生成(默认) |absent 删除 (基于name)

示例:对各主机添加每隔3分钟从time.windows.com同步时间

[root@ansible ~]# ansible all -m cron -a "minute=*/3 job='/usr/sbin/update time.windows.com &amp;&gt;/dev/null' name=update_time"
172.16.3.152 | SUCCESS =&gt; {
"changed": true,
"envs": [],
"jobs": [
"update_time"
]
}
172.16.3.216 | SUCCESS =&gt; {
"changed": true,
"envs": [],
"jobs": [
"update_time"
]
}

#到node1上查看
[root@node1 tmp]# crontab -l
#Ansible: update_time
*/3 * * * * /usr/sbin/update time.windows.com &amp;&gt;/dev/null

示例2:删除计划任务

[root@ansible ~]# ansible all -m cron -a "name=update_time state=absent"
172.16.3.152 | SUCCESS =&gt; {
"changed": true,
"envs": [],
"jobs": []
}
172.16.3.216 | SUCCESS =&gt; {
"changed": true,
"envs": [],
"jobs": []
}
#node1上查看
[root@node1 tmp]# crontab -l
会发现已经被删除了

7、yum模块

故名思义就是yum安装软件包的模块;
常用参数说明:
enablerepo,disablerepo表示启用与禁用某repo库
name 安装包名
state (present’ orinstalled’, latest’)表示安装, (absent’ or `removed’) 表示删除
示例:通过安装epel扩展源并安装nginx

[root@ansible ~]# ansible all -m yum -a "name=epel-release state=installed"
[root@ansible ~]# ansible all -m yum -a "name=nginx state=installed"

8、service模块

服务管理模块
常用参数:
name:服务名
state:服务状态
enabled: 是否开机启动 true|false
runlevel: 启动级别 (systemed方式忽略)

示例:

[root@ansible ~]# ansible all -m service -a "name=nginx state=started enabled=true"
到node1上查看
[root@node1 tmp]# systemctl status nginx
● nginx.service - The nginx HTTP and reverse proxy server
Loaded: loaded (/usr/lib/systemd/system/nginx.service; enabled; vendor preset: disabled)
Active: active (running) since 五 2018-02-09 15:54:29 CST; 1min 49s ago
Main PID: 10462 (nginx)
CGroup: /system.slice/nginx.service
├─10462 nginx: master process /usr/sbin/nginx
└─10463 nginx: worker process
......省略......

9、script模块

把本地的脚本传到远端执行;前提是到远端可以执行,不要把Linux下的脚本同步到windows下执行;
直接上示例:
本地ansible上的脚本:

[root@ansible ~]# cat test.sh
#!/bin/bash
echo "ansible script test!" &gt; /tmp/ansible.txt
[root@ansible ~]# ansible all -m script -a "/root/test.sh"
172.16.3.152 | SUCCESS =&gt; {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 172.16.3.152 closed.rn",
"stdout": "",
"stdout_lines": []
}
172.16.3.216 | SUCCESS =&gt; {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 172.16.3.216 closed.rn",
"stdout": "",
"stdout_lines": []
}
到node1上查看
[root@node1 tmp]# ls
ansible.txt fstab.ansible hi.txt
[root@node1 tmp]# cat ansible.txt
ansible script test!

script模块这个功能可以做很多事,就看你怎么用了~
以上是常用模块,至于其他模块的使用可通过官方模块列表获得~

四、Playbook实战

playbook是Ansible的配置,部署和编排的语言。他们可以描述你所希望的远程系统强制执行的政策,或者在一般的IT流程的一组步骤;形象点的说就是:如果ansible的各模块(能实现各种功能)是车间里的各工具;playbook就是指导手册,目标远程主机就是库存和原料对象.
playbook是基于YAML语言格式配置,关于YAML
更多playbook官方说明参考http://docs.ansible.com/ansible/latest/playbooks_intro.html

1、playbook的核心元素

hosts : playbook配置文件作用的主机
tasks: 任务列表
variables: 变量
templates:包含模板语法的文本文件
handlers :由特定条件触发的任务
roles :用于层次性、结构化地组织playbook。roles 能够根据层次型结构自动装载变量文件、tasks以及handlers等

2、playbook运行方式

ansible-playbook –check 只检测可能会发生的改变,但不真执行操作
ansible-playbook –list-hosts 列出运行任务的主机
ansible-playbook –syntax-check playbook.yaml 语法检测
ansible-playbook -t TAGS_NAME playbook.yaml 只执行TAGS_NAME任务
ansible-playbook playbook.yaml 运行

3、通过playbook安装管理redis服务

#在家目录下创建playbooks
[root@ansible ~]# mkidr playbooks
[root@ansible ~]# cd playbooks
[root@ansible playbooks]# cat redis_first.yaml
- hosts: all
remote_user: root
tasks:
- name: install redis
yum: name=redis state=latest

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

语法检测:

[root@ansible playbooks]# ansible-playbook --syntax-check redis_first.yaml

playbook: redis_first.yaml

说明语法没有 问题
将要执行的主机:

[root@ansible playbooks]# ansible-playbook --list-hosts redis_first.yaml
playbook: redis_first.yaml
play #1 (all): all TAGS: []
pattern: [u'all']
hosts (2):
172.16.3.216
172.16.3.152

执行

[root@ansible playbooks]# ansible-playbook redis_first.yaml
PLAY [all] *****************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************
ok: [172.16.3.216]
ok: [172.16.3.152]
TASK [install redis] *******************************************************************************************************
changed: [172.16.3.216]
changed: [172.16.3.152]
TASK [start redis] *********************************************************************************************************
changed: [172.16.3.152]
changed: [172.16.3.216]
PLAY RECAP *****************************************************************************************************************
172.16.3.152 : ok=3 changed=2 unreachable=0 failed=0
172.16.3.216 : ok=3 changed=2 unreachable=0 failed=0

说明:
自上而下列出了三个任务,分别是[Gathering Facts] , [install redis], [start redis],其中各主机上成功为ok=3,有两项任务执行结果是changed
不可达 和失败的任务均为0;

由于上面的操作是直接安装redis服务并启动,并没有配置文件,这还不能往生产环境中使用,生产环境中的redis肯定有不同的配置项,因此需要在安装时提供配置文件

4、带配置文件的安装管理redis

首先复制一个redis.conf到本地并进行修改

[root@ansible ~]# ansible 172.16.3.152 -m fetch -a "src=/etc/redis.conf dest=./"
[root@ansible ~]# mv /root/172.16.3.152/etc/redis.conf /root/playbooks/redis.conf
修改bind 0.0.0.0

cat redis_second.yaml
- hosts: all #所有远程主机
remote_user: root #以远程主机上root用户执行
tasks: #任务
- name: install redis #任务之安装
yum: name=redis state=latest #动作调用yum模块安装
- name: copy config file #任务之复制同步配置文件到远程目标主机
copy: src=/root/playbooks/redis.conf dest=/etc/redis.conf owner=redis #动作copy模块执行
notify: restart redis #触发的动作
tags: configfile #任务标记名configfile
- name: start redis #任务之启动redis
service: name=redis state=started #动作调用sevice模块
handlers: #特定情况下,接收到其他任务的通知时被触发
- name: restart redis
service: name=redis state=restarted

再次测试并执行

[root@ansible playbooks]# ansible-playbook redis_second.yaml

PLAY [all] ****************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************
ok: [172.16.3.152]
ok: [172.16.3.216]
TASK [install redis] ******************************************************************************************************
ok: [172.16.3.216]
ok: [172.16.3.152]
TASK [copy config file] ***************************************************************************************************
changed: [172.16.3.152]
changed: [172.16.3.216]
TASK [start redis] ********************************************************************************************************
ok: [172.16.3.152]
ok: [172.16.3.216]
RUNNING HANDLER [restart redis] *******************************************************************************************
changed: [172.16.3.152]
changed: [172.16.3.216]
PLAY RECAP ****************************************************************************************************************
172.16.3.152 : ok=5 changed=2 unreachable=0 failed=0
172.16.3.216 : ok=5 changed=2 unreachable=0 failed=0

可以发现只是加了一个配置文件,所有的任务都执行了,可否只应用新添加的任务?当然可以
这里就要通过
ansible-playbook -t TAGS_NAME 来执行了
可以把redis.conf中添加一个登录密码再执行测试下:

[root@ansible playbooks]# ansible-playbook -t configfile redis_second.yaml
PLAY [all] ****************************************************************************************************************
TASK [Gathering Facts] ****************************************************************************************************
ok: [172.16.3.152]
ok: [172.16.3.216]
TASK [copy config file] ***************************************************************************************************
changed: [172.16.3.216]
changed: [172.16.3.152]
RUNNING HANDLER [restart redis] *******************************************************************************************
changed: [172.16.3.152]
changed: [172.16.3.216]
PLAY RECAP ****************************************************************************************************************
172.16.3.152 : ok=3 changed=2 unreachable=0 failed=0
172.16.3.216 : ok=3 changed=2 unreachable=0 failed=0

以上执行结果就没有 了安装与启动的步骤~只有更新和重启!
更多playbook使用示例请添加链接描述https://github.com/ansible/ansible-examples

总结

ansible通过常用模块在命令行就可以针对主机清单来管理配置远程主机,无需要代理客户端程序,但需要目标主机有ssh和python2.4+;基于
ssh协议既可以通过用户名和密码,也可以通过私钥,推荐使用私钥;
windows上需要安装powershell及winrm服务也可以做到,关于这方面 可以参考我之前的博客http://blog.51cto.com/dyc2005/2064746
通过ansib-doc来获取模块信息及指定模块帮助信息;
ansible-playbook 基于YAML语法配置;可以对playbook文件进行测试,解析并执行应用于指定无端主机;非常方便我们统一编排分发管理远程主机;
本文旨在入门;后续会针对playbook的roles角色及其他更多强大功能再进行详细说明;如有不当之处欢迎留言交流!

//下面这个css和插件后台设置的主题有关系,如果需要换样式,则需要修改以下CSS名称

Ansible 的 command 和 shell 模块

ansible 的 command 和 shell 模块都可以执行命令,例如:

➜  www ansible k8s-master -m command  -a 'pwd'
kubernetes-1 | SUCCESS | rc=0 >>
/root

➜  www ansible k8s-master -m shell  -a 'pwd'
kubernetes-1 | SUCCESS | rc=0 >>
/root

但是如果你使用 command 运行一些包含特殊符号的命令,比如“|” “<” “>” 之类的命令就无法执行,原因我们通过

ansible-doc command    

查看

Notes:
  * If you want to run a command through the shell (say you are using `<', `>', `|', etc), you actually want the [shell]
        module instead. The `command' module is much more secure as it's not affected by the user's environment.
  *  `creates', `removes', and `chdir' can be specified after the command. For instance, if you only want to run a
        command if a certain file does not exist, use this.

因此在使用的时候需要注意了。