Ansible自动化运维-配置与安装

1.Ansible安装

环境准备
在两台机器上关闭防火墙和SELinux,并修改/etc/hosts文件。(两台主机)

[root@localhost]#hostnamectl set-hostname ansible-test1
[root@ansible-test1 ~]# systemctl stop firewalld
[root@ansible-test1 ~]# systemctl disable firewalld
Removed symlink /etc/systemd/system/dbus-org.fedoraproject.FirewallD1.service.
Removed symlink /etc/systemd/system/basic.target.wants/firewalld.service.
[root@ansible-test1 ~]# setenforce 0
[root@ansible-test1 ~]# cat /etc/selinux/config #     disabled - No SELinux policy is loaded.
SELINUX=disabled	//将此处改为disabled
# SELINUXTYPE= can take one of three two values:[root@ansible-test1 ~]# cat /etc/hosts
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
10.30.59.204 ansible-test1	//添加两台主机的IP和主机名
10.30.59.206 ansible-test2

安装Ansible
准备两台机器anisble-test1和anisble-test2,只需要在anisble-test1上安装Ansible,先安装epel仓库。

[root@ansible-test1 ~]# yum install epel-release -y 
[root@ansible-test1 ~]# yum install -y ansible
[root@ansible-test1 ~]# ansible --version  
//查看版本

免密配置
anisble-test1上生成密钥对ssh-keygen -t rsa,把公钥放到anisble-test2上,设置密钥认证。
注意:需要将本机也配置免密(选项默认回车,设置无密钥登陆ansible-test1)
在这里插入图片描述
添加anaible-test2的密钥
在这里插入图片描述
添加ansible-test1的密钥

[root@ansible-test1 ~]# ssh-copy-id 127.0.0.1

无密钥登陆
在这里插入图片描述
主机组设置
在/etc/ansible/hosts文件中添加本机和另一台机器的IP:

[root@ansible-test1 ~] vi /etc/ansible/hosts
//添加
[testhost]
127.0.0.1
10.30.59.206
//说明:testhost为自定义的主机组名字,下面两个IP为组内的机器IP。

2.Ansible远程执行命令

批量执行命令。这里的testhost为主机组名,-m后边是模块名字,-a后面是命令。当然我们也可以直接写一个IP,针对某一台机器来执行命令。

[root@ansible-test1~]# ansible testhost -m command -a "hostname"
[root@ansible-test1~]# ansible 10.30.59.206 -m command -a "hostname"

在这里插入图片描述

3.Ansible拷贝文件或目录

源目录会放到目标目录下面去,如果目标指定的目录不存在,它会自动创建。如果拷贝的是文件,如果dest指定的名字和源不同,并且它不是已经存在的目录,相当于拷贝过去后又重命名。但相反,如果dest是目标机器上已经存在的目录,则会直接把文件拷贝到该目录下面。

[root@ansible-test1 ~] ansible 10.30.59.206 -m copy -a "src=/etc/passwd dest=/tmp/123"

这里的/tmp/123和源机器上的/etc/passwd是一致的,但如果目标机器上已经有/tmp/123目录,则会再/tmp/123目录下面建立passwd文件。

查看目标端口是否拷贝成功
在这里插入图片描述

4.Ansible远程执行脚本

首先创建一个shell脚本
在这里插入图片描述
然后把该脚本分发到各个机器上

[root@ansible-test1 ~] ansible testhost -m copy -a "src=/tmp/test.sh dest=/tmp/test.sh mode=0755"

最后是批量执行该shell脚本

[root@ansible-test1 ~]# ansible testhost -m shell -a "/tmp/test.sh"

在这里插入图片描述
shell模块,还支持远程执行命令并且带管道

[root@ansible-test1 ~] ansible testhost -m shell -a "cat /etc/passwd |wc -l "

在这里插入图片描述

5.Ansible管理任务计划

创建任务计划,命名并定义工作。

 ansible testhost -m cron -a "name='test cron' job='/bin/bash'"

在这里插入图片描述
若要删除该cron只需要加一个字段state=absent

 ansible testhost -m cron -a "name='test cron' job='/bin/bash' state=absent"

在这里插入图片描述

6.Ansible安装RPM包/管理服务

使用Yum模块安装httpd服务

ansible testhost -m yum -a "name=httpd"

在这里插入图片描述
在name后面还可以加上state=installed/removed。
设置服务状态,这里的name是CentOS系统里的服务名,可以通过chkconfig –list命令查到。

ansible testhost -m service -a "name=httpd state=started enabled=yes"

在这里插入图片描述
Ansible文档的使用:

[root@ansible-test1 ~] ansible-doc -l	//列出所有模块

在这里插入图片描述
q退出查看模板
查看指定模块的文档

[root@ansible-test1 ~] ansible-doc yum	//查看指定模块的文档

在这里插入图片描述

7.Ansible playbook使用

相当于把模块写入到配置文件里面

[root@ansible-test1 ansible]cat /etc/ansible/test.yml
---
- hosts: 10.30.59.206
  remote_user: root
  tasks:
    - name: test_playbook
      shell: touch /tmp/playbook_test.txt

在这里插入图片描述
再来一个创建用户的例子

 [root@ansible-test1 ansible]# cat create_user.yml 
---
- name: create_user
  hosts: 10.30.59.206
  user: root
  gather_facts: false
  vars:
    - user: "test"
  tasks:
    - name: create user
      user: name="{{ user }}"

在这里插入图片描述

(1)ansible playbook中的循环

创建while.yml文件

[root@ansible-test1 ansible]# cat while.yml 
---
- hosts: testhost
  user: root
  tasks:
    - name: change mode for files
      file: path=/tmp/{{ item }} mode=600
      with_items:
        - 1.txt
        - 2.txt
        - 3.txt 

说明: with_items为循环的对象

/两台主机都需要创建
[root@ansible-test1 ansible] cd /tmp/
[root@ansible-test1 tmp] touch 1.txt 2.txt 3.txt

执行while.yml。
在这里插入图片描述

(2)ansible playbook中的条件判断

创建when.yml文件

[root@ansible-test1 ansible]# cat when.yml 
---
- hosts: testhost
  user: root
  gather_facts: True
  tasks:
    - name: use when
      shell: touch /tmp/when.txt
      when: ansible_eno16777736.ipv4.address == "10.30.59.206"

说明:ansible anisble-test2 -m setup 可以查看到所有的facter信息
执行when.yml。

在这里插入图片描述

(3)ansible playbook中的handlers

说明,只有copy模块真正执行后,才会去调用下面的handlers相关的操作。也就是说如果1.txt和2.txt内容是一样的,并不会去执行handlers里面的shell相关命令。 这种比较适合配置文件发生更改后,重启服务的操作

[root@ansible-test1 ansible]# cat handlers.yml 
---
- name: handlers test
  hosts: 10.30.59.206
  user: root
  tasks:
    - name: copy file
      copy: src=/etc/passwd dest=/tmp/aaa.txt
      notify: test handlers
  handlers:
    - name: test handlers
      shell: echo "111111" >> /tmp/aaa.txt 

在这里插入图片描述

8.Ansible playbook实战

1.ansible自动化安装nginx
编译安装nginx
1)使用wget下载nginx包,下载地址:
http://mirrors.sohu.com/nginx/nginx-1.9.6.tar.gz

wget http://mirrors.sohu.com/nginx/nginx-1.9.6.tar.gz
mv nginx-1.9.6.tar.gz /usr/local/

2)解压下载的nginx包

tar -zxf nginx-1.9.6.tar.gz
cd nginx-1.9.6
yum install -y gcc gcc-c++ pcre-devel openssl-devel //安装依赖库
./configure --prefix=/usr/local/nginx
make && make install

编写/etc/init.d/nginx文件
内容如下

vi /etc/init.d/nginx
#!/bin/bash
# chkconfig: - 30 21
# description: http service.
# Source Function Library
. /etc/init.d/functions
# Nginx Settings
NGINX_SBIN="/usr/local/nginx/sbin/nginx"
NGINX_CONF="/usr/local/nginx/conf/nginx.conf"
NGINX_PID="/usx/local/nginx/logs/nginx.pid"
RETVAL=0
prog="Nginx"

start()
{
        echo -n $"Starting $prog: "
        mkdir -p /dev/shm/nginx_temp
        daemon $NGINX_SBIN -c $NGINX_CONF
        RETVAL=$?
        echo
        return $RETVAL
}
stop()
{
        echo -n $"Stopping $prog: "
        killproc -p $NGINX_PID $NGINX_SBIN -TERM
        rm -rf /dev/shm/nginx_temp
        RETVAL=$?
        echo
        return $RETVAL
}
reload()
{
        echo -n $"Reloading $prog: "
        killproc -p $NGINX_PID $NGINX_SBIN -HUP
        RETVAL=$?
        echo
        return $RETVAL
}
restart()
{
        stop
        start
}
configtest()
{
        $NGINX_SBIN -c $NGINX_CONF -t
        return 0
}
case "$1" in
        start)
                start
                ;;
        stop)
                stop
                ;;
        reload)
                reload
                ;;
        restart)
                restart
                ;;
        configtest)
                configtest
                ;;
        *)
                echo $"Usage: $0 {start|stop|reload|restart|configtest}"
                RETVAL=1
esac
exit $RETVAL

chmod 755 /etc/init.d/nginx //设置权限

清空配置文件并重新编写

 > /usr/local/nginx/conf/nginx.conf
 vi  /usr/local/nginx/conf/nginx.conf

重新编写内容

user nobody nobody;		//定义nginx运行的用户和用户组
worker_processes 2;		//nginx进程数,一般为CPU总核心数
error_log /usr/local/nginx/logs/nginx_error.log crit;	//全局错误日志定义类型
pid /usr/local/nginx/logs/nginx.pid;	//进程文件
worker_rlimit_nofile 51200;
events		//工作模式与连接数上限
{
use epoll;
worker_connections 6000;
}
http		//http下的一些配置
{
include mime.types;		//文件扩展名与文件类型映射表
default_type application/octet-stream;		//默认文件类型
server_names_hash_bucket_size 3526;
server_names_hash_max_size 4096;
log_format combined_realip '$remote_addr $http_x_forwarded_for [$time_local]'
'$host "$request_uri" $status'
'"$http_referer" "$http_user_agent"';
sendfile on;		//开启高效文件传输模式
tcp_nopush on;		//防止网络阻塞
keepalive_timeout 30;		//长连接超时时间,单位为秒
client_header_timeout 3m;
client_body_timeout 3m;
send_timeout 3m;
connection_pool_size 256;
client_header_buffer_size 1k;
large_client_header_buffers 8 4k;
request_pool_size 4k;
output_buffers 4 32k;
postpone_output 1460;
client_max_body_size 10m;
client_body_buffer_size 256k;
client_body_temp_path /usr/local/nginx/client_body_temp;
proxy_temp_path /usr/local/nginx/proxy_temp;
fastcgi_temp_path /usr/local/nginx/fastcgi_temp;
fastcgi_intercept_errors on;
tcp_nodelay on;		//防止网络阻塞
gzip on;		//开启gzip压缩输出
gzip_min_length 1k;
gzip_buffers 4 8k;
gzip_comp_level 5;
gzip_http_version 1.1;
gzip_types text/plain application/x-javascript text/css text/htm
application/xml;
server		//虚拟主机配置
{
listen 80;
server_name localhost;
index index.html index.htm index.php;
root /usr/local/nginx/html;
location ~ \.php$
{
include fastcgi_params;
fastcgi_pass unix:/tmp/php-fcgi.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME /usr/1ocal/nginx/html$fastcgi_script_name;
}
}
}

编写完成后可以检查一下

 /usr/local/nginx/sbin/nginx -t

启动nginx

service nginx start

在这里插入图片描述
编译安装完成
环境准备
1)将nginx.tar.gz复制到/etc/ansible/nginx_install/roles/install/files下
启动脚本和配置文件都放到/etc/ansible/nginx_install/roles/install/template下

[root@ansible-test1 ~] cd /usr/local/
[root@ansible-test1 local] tar -zcf nginx.tar.gz nginx
[root@ansible-test1 local] mkdir -p /etc/ansible/nginx_install/roles/{common,install}/{handlers,files,meta,tasks,templates,vars}
[root@ansible-test1 local] mv nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
[root@ansible-test1 local] cp nginx/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/
[root@ansible-test1 local] cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/templates/

2)编写需要的yml文件

cd /etc/ansible/nginx_install
[root@ansible-test1 nginx_install]# vi install.yml 
---
- hosts: 10.30.59.206		//入口文件
  remote_user: root
  gather_facts: True
  roles:
    - common
    - install
[root@ansible-test1 nginx_install]# vi roles/common/tasks/main.yml 
- name: install initialization require software  //安装需要的依赖
  yum: name={{ item }} state=installed
  with_items:
    - zlib-devel
    - pcre-devel
    - gcc

[root@ansible-test1 nginx_install]# vi roles/install/vars/main.yml 
nginx_user: www		//定义所需变量
nginx_port: 80
nginx_basedir: /usr/local/nginx

[root@ansible-test1 nginx_install]# cat roles/install/tasks/copy.yml 
- name: Copy Nginx Software	//复制压缩包
  copy: src=nginx.tar.gz dest=/tmp/nginx.tar.gz owner=root group=root
- name: Uncompression Nginx Software	//解压压缩包
  shell: tar zxf /tmp/nginx.tar.gz -C /usr/local/
- name: Copy Nginx Start Script		//复制启动脚本
  template: src=nginx dest=/etc/init.d/nginx owner=root group=root mode=0755
- name: Copy Nginx Config		//复制nginx配置文件
  template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644

[root@ansible-test1 nginx_install]# vi roles/install/tasks/install.yml 
- name: create nginx user	//创建用户
  user: name={{ nginx_user }} state=present createhome=no shell=/sbin/nologin
- name: start nginx service	//开启服务
  shell: /etc/init.d/nginx start
- name: add boot start nginx service	//加入开机启动
  shell: chkconfig --level 345 nginx on
- name: delete nginx compression files	//删除压缩包
  shell: rm -rf /tmp/nginx.tar.gz

[root@ansible-test1 nginx_install]# vi roles/install/tasks/main.yml 
- include: copy.yml	//调用copy.yml和install.yml
- include: install.yml

3)执行文件
运行install.yml文件

[root@ansible-test1 ~] ansible-playbook /etc/ansible/nginx_install/install.yml 

在这里插入图片描述

管理配置文件

生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面我们来写个管理nginx配置文件的playbook。

mkdir  -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}
[root@ansible-test1 nginx_config] vi /etc/ansible/nginx_config/roles/new/handlers/main.yml 
- name: restart nginx	//用于重新加载nginx服务
  shell: /etc/init.d/nginx reload
[root@ansible-test1 nginx_config]# vi /etc/ansible/nginx_config/roles/new/tasks/main.yml 
- name: copy conf file	//复制.conf和hosts文件
  copy: src={{ item.src }} dest={{ nginx_basedir }}/{{ item.dest }} backup=yes owner=root group=root mode=0644
  with_items: 
    - { src: nginx.conf, dest: conf/nginx.conf }
    - { src: vhosts, dest: conf/ }
  notify: restart nginx
[root@ansible-test1 nginx_config] vi /etc/ansible/nginx_config/roles/new/vars/main.yml 
nginx_basedir: /usr/local/nginx	//定义变量
[root@ansible-test1 nginx_config] vi update.yml 
---
- hosts: testhost	
  user: root
  roles:
  - new		//这里只有new

old目录中的yml文件与new目录中的相同,files中的配置文件不同。
其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令
在执行update.yml前,应备份当前配置文件,当执行之后发现错误,则进行回滚操作。关于回滚,需要在执行playbook之前先备份一下旧的配置,所以对于老配置文件的管理一定要严格,千万不能随便去修改线上机器的配置,并且要保证new/files下面的配置和线上的配置一致,命令如下:(yum install -y rsync)

rsync -av /etc/ansible/nginx_config/roles/new/ /etc/ansible/nginx_config/roles/old/

关于更新

先把nginx.conf和vhosts目录放到files目录下面

 cd /usr/local/nginx/conf/
[root@ansible-test1 conf] mkdir vhosts
[root@ansible-test1 conf] cd vhosts 
[root@ansible-test1 vhosts] touch 1.conf
[root@ansible-test1 conf] cd ..
[root@ansible-test1 conf] cp -r nginx.conf vhosts  /etc/ansible/nginx_config/roles/new/files/

修改配置文件

[root@ansible-test1 conf] vi nginx_conf

在配置文件中添加倒数第二个中括号下
include /usr/local/nginx/conf/vhosts/*.conf;
在这里插入图片描述

[root@ansible-test1 nginx_config] ansible-playbook /etc/ansible/nginx_config/update.yml 

在这里插入图片描述

回滚操作就是把旧的配置覆盖,然后重新加载nginx服务, 每次改动nginx配置文件之前先备份到old里,对应目录为/etc/ansible/nginx_config/roles/old/files

 vim /etc/ansible/nginx_config/rollback.yml // 最后是定义总入口配置
---
- hosts: testhost
  user: root
  roles:
  - old 

[root@ansible-test1 nginx_config] ansible-playbook /etc/ansible/nginx_config/rollback.yml 

本次实验并未改变配置文件,故changed为0

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值