ansible自动化运维入门

1.ansible的安装

1)使用源码安装Python3.5

安装支持包

yum -y install lrzsz vim net-tools gcc gcc-c++ ncurses ncurses-devel unzip zlib-devel zlib openssl-devel openssl

tar xf Python-3.5.2.tgz -C /usr/src/

./configure --prefix=/usr/local/python/

make && make install

ln -s /usr/local/python/bin/python3 /usr/bin/python3

2)使用pip3安装ansible

/usr/local/python/bin/pip3 install ansible

ln -s /usr/local/python/bin/ansible /usr/local/bin/

2.模块简单使用

1)ansible的配置文件

vim /etc/ansible/hosts

机器1 ansible_ssh_host=ip ansible_ssh_port=22 ansible_ssh_user=root

机器2 ansible_ssh_host=ip ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=666666

  1. ansible_ssh_host ===>主机IP
  2. ansible_ssh_port ===>ssh的默认端口
  3. ansible_ssh_user ===>ssh的用户名
  4. ansible_ssh_pass ===>ssh的用户的连接密码

如果我们已经设置了ssh免密钥了。那么就不需要写密码了。例如:webA

  我们要是没有设置免密钥,那么就需要安装sshpass工具,并在/etc/ansible/hosts文件里写上主机的连接密码。

wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo

yum -y install sshpass

2)进行ansible远程执行命令测试

ansible -i /etc/ansible/hosts 主机或主机组 -m 指定模块 -a 命令

使用ping模块用来查看服务器是否连接正常,ping模块不需要-a指定参数

ansible 主机1    -m ping

  1. [root@ansible .ssh]# ansible all -m ping
  2. webA | SUCCESS => {
  3.     "changed": false,
  4.     "ping": "pong"
  5. }
  6. webB | SUCCESS => {
  7.     "changed": false,
  8.     "ping": "pong"
  9. }

3)ansible模块command(不支持管道,不建议使用)

 ansible all -m command -a "pwd"

ansible all -m command -a "echo bb >> /tmp/testansible"

-a 'name= state={present(创建)|absent(删除)} force=(是否强制操作删除家目录) system= uid= shell= home='

4)ansible模块shell(支持管道,支持重定向)

 ansible all -m shell -a "echo testansible | grep a"

 ansible all -m shell -a "echo bb >> /tmp/testansible"

 ansible all -m shell -a "cat /etc/passwd | awk -F":" '{print $1}'"

 5)ansible的copy模块批量下发文件或文件夹

 ansible all -m copy -a "src=/service/scripts/test.txt dest=/service/scripts/"

 ansible webB -m copy -a "src=/service/scripts/test.txt dest=/service/scripts/"

copy模块拷贝文件夹,如果目标路径里有与我拷贝的文件同名文件的话,会直接覆盖目标路径下的文件

参数:backup=yes ===>意思是,如果目标路径下,有与我同名但不同内容的文件时,在覆盖前,对目标文件先进行备份。

ansible webB -m copy -a "src=/service/scripts/ dest=/service/scripts/ backup=yes"

6)ansible的script模块批量运行脚本

ansible all   -m script -a "/root/service/mysql/auto_mysql.sh"

在指定的机器上执行本地脚本

7)service:

-a 'name= state={started|stopped|restarted} enabled=(是否开机自动启动) runlevel=' [root@localhost ~]# ansible all -m service -a 'name=httpd state=started'

3.变量种类:

1)facts:由远程主机发回的主机特有的属性信息,这些信息被保存在ansible变量中;无须声明,可直接调用;

2)自定义变量: 通过命令行传递:ansible-playbook test.yml --extra-vars "host=www user=test" 通过roles传递

3)主机变量:定义在inventory中的主机之后的变量;直接传递给单个主机的变量

例子:

[root@localhost~]# vim useradd.yml
- hosts: websrvs
remote_user: root
vars:
username: testuser
password: xuding
tasks:
-name: add user
user: name={{ username }} state=present
-name: set password
shell: /bin/echo {{ password }} |/usr/bin/passwd --stdin {{ username }}

|--extra-vars=VARS} 变量的重新赋值调用方法

ansible-playbookuseradd.yml --extra-vars "username=ubuntu"

4)playbook--- tasks

条件测试:

在某task后面添加when子句即可实现条件测试功能;when语句支持Jinja2语法; 实例:当时RedHat系列系统时候调用yum安装

例子:

-name: install web server package
yum: name=httpd state=present
when: ansible_os_family == "RedHat"

 item

在task中调用内置的item变量;在某task后面使用with_items语句来定义元素列表;

-name: add four users

user: name={{ item }} state=present

with_items:

-testuser1

-testuser2

-testuser3

-testuser4

注意:迭代中,列表中的每个元素可以为字典格式;

实例:

-name: add two users
user: name={{ item.name }} state=present groups={{ item.groups }}
with_items:
- { name: 'testuser5', groups: 'wheel' }
- { name: 'testuser6', groups: 'root' }
5)handlers:处理器;触发器

只有其关注的条件满足时,才会被触发执行的任务; 实例:配置文件发生改变触发重启服务

-hosts: websrvs
remote_user: root
tasks:
-name: install httpd
yum:name=httpd state=present
-name: install config file
copy: src=/root/httpd.conf   dest=/etc/httpd/conf/httpd.conf
notify: restart httpd
-name: start httpd service
service: name=httpd state=started
handlers:
-name: restart httpd
service: name=httpd state=restarted

4.ansible-playbook的初步使用

核心元素

Tasks任务、Variables变量、Templates模板、Handlers处理器、Roles角色

playbook的使用,playbook可以把ansible的模块进行组合

cat test_shell.yaml  #playbook的执行模板

  1. ---         #开头三个小-开头
  2. - hosts: webB  
  3.   tasks:       
  4.   - name: test
  5.     shell: echo "welcome to yunjisaun" >> /tmp/username
  6.   - name: test2
  7.     shell: echo "welcome to yunjisuan" >> /tmp/username
  8.      - name: install httpd
  9.        yum:  name=httpd state=present
  10.      - name: start httpd
  11.        service: name=httpd  state=started enable=true
  12. 模板说明:
  13. ---  #开头必须有三个小-,顶格写
  14. - hosts   #正文配置代码的第一级,必须有两个空格(-占一个空格位)
  15. - host: webB   #webB是host参数的值,值和hosts:之间要有一个空格
  16.   tasks:        #tasks:表示接下来要执行的具体任务
  17.   - name:     #相对于tasks再多缩进两个格(-占一个空格位),表示属于tasks的下一级
  18.   - name: test  #test只是要执行的具体命令的名字可以随便写。name:后还是有一个空格要注意
  19.     shell:  #表示调用shell模块执行命令相对于tasks仍旧要多缩进两个空格
  20.     shell: echo "xxx" >> xxx     #shell:后边还是要有个空格,需要注意。

执行playbook配置文件,ansible-playbook test_shell.yaml #执行playbook配置文件

实例:用ansible-playbook,在两台机器上自动化部署mysql 数据库

1)准备三台Linux,其中一台安装好ansible,三台机器互相连通

2)准备.yaml文件,setup.yaml

---
  - hosts: all                                                                               #hosts文件中全部主机
    vars:                                                                                      #定义变量
    - dst: "/service/"                                                                     #变量名为dst
    tasks:                                                                                    # 任务
    - name: cp cmake mysql                                                       #第一个任务名
      copy: src=/root/service/mysql/  dest={{ dst }}                      #拷贝MySQL下的文件到变量dst中

      notify:  # 如果copy执行完之后~/hosts.dest文件发送了变化,则执行

      - clear copy  # 调用handler
      handlers:
      - name: clear copy
        shell: 'mv ~/hosts.dest hosts.del'  # 假装删除
    - name: install mysql                                                             #第二个任务名
      script: /root/service/mysql/auto_mysql.sh                           #执行脚本模块, 后边跟脚本路径
      register: print_result                                                            #打印执行结果
    - debug: var=print_result

3)准备脚本文件auto_mysql.sh 

#!/bin/bash
#in ansible use
#install myysql
#20180731
mysql_tar="mysql-5.6.40.tar.gz"
mysql_dir="mysql-5.6.40"
cmake_tar="cmake-2.8.6.tar.gz"
cmake_dir="cmake-2.8.6"
dest="/service/"

#删旧版本
rpm -e mariadb-libs  --nodeps &>/dev/null
rpm -e mysql mysql-server --nodeps &>/dev/null
#关防火墙
rpm -q make gcc gcc-c++ &>/dev/null
if [ $? -ne 0 ];then
 yum -y install  make gcc gcc-c++ &>/dev/null
fi
#安装cmake

cd $dest
tar xf $cmake_tar -C /usr/src/ &>/dev/null
cd /usr/src/$cmake_dir
./configure &>/dev/null && make &>/dev/null  && make install &>/dev/null
#删除包
rm -fr /usr/src/$cmake_dir &>/dev/null
cd $dest
rm -fr $cmake_tar
#安装依赖
yum -y install ncurses ncurses-devel &>/dev/null
groupadd mysql &>/dev/null
useradd -M -s /sbin/nologin  -g mysql mysql &>/dev/null
#解压源码包

tar xf $mysql_tar -C /usr/src/ &>/dev/null
#安装
cd /usr/src/$mysql_dir
cmake -DCMAKE_INSTALL_PREFIX=/usr/local/mysql  -DDEFAULT_CHARSET=utf8  -DDEFAULT_COLLATION=utf8_general_ci -DWITH_EXTRA_CHARSETS=all  -DSYSCONFDIR=/etc &>/dev/null &&make &>/dev/null &&make install &>/dev/null
#优化
cd /usr/local/mysql
cp support-files/my-default.cnf  /etc/my.cnf &>/dev/null
#安装数据

yum -y install autoconf &>/dev/null && /usr/local/mysql/scripts/mysql_install_db  --basedir=/usr/local/mysql  --datadir=/usr/local/mysql/data  --user=mysql &>/dev/null
echo "PATH=$PATH:/usr/local/mysql/bin">>/etc/profile
source  /etc/profile &>/dev/null
chown -R mysql:mysql /usr/local/mysql/ &>/dev/null
cp support-files/mysql.server  /etc/init.d/mysqld &>/dev/null
chmod +x /etc/init.d/mysqld
sed -i -e '1a #chkconfig: 35 50 45' /etc/init.d/mysqld
cd $dest
rm -fr /usr/src/$mysql_dir &>/dev/null
rm -fr $mysql_tar

#启动服务

/usr/sbin/chkconfig --add mysqld
/etc/init.d/mysqld start

3)准备好安装包

cmake-2.8.6.tar.gz    mysql-5.6.40.tar.gz放到与脚本同一目录下

4)ansible-playbook setup.yaml

剩下的时间,你可以喝杯茶了,休息一下。两台机器部署完成,登录下机器看是否服务启动

mysql -uroot  -p123456  -h ip

成功登录。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/mushou/p/9398405.html