目录

ansible

安装

使用ansible执行远程命令

Ansible拷贝文件或者目录

Ansible远程执行脚本

Ansible管理任务计划

Ansible安装rpm包/管理服务

playbook

playbook实战--nginx安装

playbook实战-管理配置文件


ansible

安装

ansible可直接通过yum安装

[root@shuai-01 ~]# yum install -y ansible.noarch

安装完成后,需要在机器上设置秘钥,将安装ansible机器上的公钥分发到其他机器

机器一
[root@shuai-01 ~]# cat ./.ssh/id_rsa.pub 
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCyjV0iSmwCvC8pHTEmzNKKSX3hLNgiEVZU3BKL+3t6cShUwzKOq+xRWSf4Ii5P+Wdg/ttQWkEBXEOgOQyYAbvJ9VKTj0WnAzdiRP4tE1rxCDtzodrCG1yOYG1ICTkzHL0akL0BDLMBtC+57Q8sFd+hQVJ965RBbZIsBpsw4BLuzdnNmNC6X24IcMXM5DS7mYmEanKZgmEJYmfnItBoA44lwtM1SJ2HQLfMDqM1h5UneJqYVw/LHprlm4yhOmq9q3kWCbec3qyndpxa58ULLYE4kZvltHZfPfBAjdWGnRxAO0piuEcuDAdaW7IQFrNWTpc/iup7332MzhkmbUBlHEQz root@shuai-01

[root@shuai-01 ~]# vim /etc/hosts
192.168.176.134 shuai-02


机器二,将机器二的公钥写入
[root@shuai-02 ~]# vim .ssh/authorized_keys 

然后连接

[root@shuai-01 ~]# ssh shuai-02
The authenticity of host 'shuai-02 (192.168.176.134)' can't be established.
ECDSA key fingerprint is ec:cf:5c:e7:1b:4e:1a:ba:ef:0b:20:06:dc:f0:b4:0e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'shuai-02' (ECDSA) to the list of known hosts.
Last login: Mon Aug 12 14:31:46 2019 from 192.168.176.1

完成后在配置主机组,主机组是一群机器

机器一:
[root@shuai-01 ~]# vim /etc/ansible/hosts 

[testhost]
shuai-02
localhost

使用ansible执行远程命令

[root@shuai-01 ~]# ansible testhost -m command -a 'w'
192.168.176.134 | CHANGED | rc=0 >>
 14:46:46 up 16 min,  2 users,  load average: 0.08, 0.06, 0.10
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    192.168.176.1    14:31   11:58   0.01s  0.01s -bash
root     pts/1    192.168.176.135  14:46    1.00s  0.20s  0.00s w

127.0.0.1 | CHANGED | rc=0 >>
 14:46:48 up  2:27,  2 users,  load average: 1.01, 0.31, 0.14
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
root     pts/0    192.168.176.1    12:20   48.00s 24.06s  0.00s ssh -C -o ControlMaster=auto -o ControlPersist=60s -o KbdInteractiveAuthentication=no -o PreferredAuthentications=gssapi-with-mic,gssapi-keyex,hostbased,publickey -o PasswordAuthentication=no -o ConnectTimeout=10 -o ControlPath=/root/.ansible/cp/21f0e6a9ae -tt 127.0.0.1 /bin/sh -c '/usr/bin/python /root/.ansible/tmp/ansible-tmp-1565592395.48-59550864680989/AnsiballZ_command.py && sleep 0'
root     pts/2    localhost        14:46    2.00s  0.25s  0.10s w


testhost------主机组
- m command -----命令模式

Ansible拷贝文件或者目录

拷贝目录
[root@shuai-01 ~]# ansible shuai-02 -m copy -a "src=/etc/ansible dest=/tmp/ansible owner=root group=root mode=0755"
shuai-02 | CHANGED => {
    "changed": true, 
    "dest": "/tmp/ansible/", 
    "src": "/etc/ansible"
}


shuai-02  --------  指定主机名或主机组
-m copy   --------  拷贝模块
src=/etc/ansible --- 源目录
dest=/tmp/ansible --目标目录,如果没有,会自行创建,拷贝的目录会在这个目录的下面
owner=root group=root mode=0755 --- 所属主,所属组,权限 没指定用户,默认是root:root 755

拷贝文件

[root@shuai-01 ~]# ansible shuai-02 -m copy -a "src=/root/4.txt dest=/tmp/shuai owner=root group=root mode=0755 "
shuai-02  --------  指定主机名或主机组
-m copy   --------  拷贝模块
src=/etc/ansible --- 源目录
dest=/tmp/ansible --目标目录,如果没有,会自行创建,拷贝的目录会在这个目录的下面,如果是一个有文件后缀名,他会存到这个文件中
owner=root group=root mode=0755 --- 所属主,所属组,权限 没指定用户,默认是root:root 755

Ansible远程执行脚本

需要先将脚本分发拷贝到各台机器上,然后在批量执行脚本

ansible testhost -m copy -a "src=/tmp/1.sh dest=/tmp/test.sh mode=0755"


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

Ansible管理任务计划

 



ansible testhost -m cron -a "name='test cron' job='/bin/touch /tmp/1212.txt' weekday=6"


[root@shuai-01 ~]# crontab -l
#Ansible: test cron
* * * * 6 /bin/touch /tmp/1212.txt


testhost  ----- 主机组
-m cron  ------ cron模块
name='test cron ---- 定义的名字
job='/bin/touch /tmp/1212.txt' -- 任务
weekday=6  ------ 时间  分钟 minute 小时 hour 日期 day 月份 month


若要删除该cron 只需要加一个字段 state=absent 
 ansible testhost -m cron -a "name='test cron' state=absent"

Ansible安装rpm包/管理服务

安装包

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

testhost --------- 主机组
-m yum  ---------- yum模块
name=httpd ------- 服务名   chkconfig --list查到
state=installed -- 安装   state=installed/removed

服务管理

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

testhost --------- 主机组
-m service ------- 服务
name=httpd ------- 服务名
state=started ---- 状态:启动  state=started/stoped
enabled=yes ------ 是否加入开机自启动

通过ansible-doc cron  具体的模块名,来看详细的使用方式

playbook

语法:

vim create_user.yml

---
- name: create_user
  hosts: shuai-02
  user: root
  gather_facts: false
  vars:
  - user: "test"
  tasks:
  - name: create user
    user: name="{{ user }}"


---      这是一个雷打不动的开头
-        每个-下面表示是这个-的范围,每一个顶级的-表示一个play,每个play中必须包含host task
通过key-value来表示值,通过: 来分割键值


循环

vi /etc/ansible/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为循环的对象
 执行 ansible-playbook while.yml

条件判断

vi /etc/ansible/when.yml 

---
- hosts: testhost
  user: root
  gather_facts: True
  tasks:
    - name: use when
      shell: touch /tmp/when.txt
      when: ansible_ens33.ipv4.address == "172.7.15.114“
 说明:ansible aming-02 -m setup 可以查看到所有的facter信息

handler

执行task之后,服务器发生变化之后要执行的一些操作,比如我们修改了配置文件后,需要重启一下服务

vi /etc/ansible/handlers.yml//加入如下内容


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

playbook实战--nginx安装

思路:先在一台机器上编译安装好nginx、打包,然后再用ansible去下发  cd /etc/ansible   进入ansible配置文件目录  mkdir  nginx_install   创建一个nginx_install的目录,方便管理  cd nginx_install  mkdir -p roles/{common,install}/{handlers,files,meta,tasks,templates,vars}  说明:roles目录下有两个角色,common为一些准备操作,install为安装nginx的操作。每个角色下面又有几个目录,handlers下面是当发生改变时要执行的操作,通常用在配置文件发生改变,重启服务。files为安装时用到的一些文件,meta为说明信息,说明角色依赖等信息,tasks里面是核心的配置文件,templates通常存一些配置文件,启动脚本等模板文件,vars下为定义的变量

 需要事先准备好安装用到的文件,具体如下:  在一台机器上事先编译安装好nginx,配置好启动脚本,配置好配置文件  安装好后,我们需要把nginx目录打包,并放到/etc/ansible/nginx_install/roles/install/files/下面,名字为nginx.tar.gz  启动脚本、配置文件都要放到/etc/ansible/nginx_install/roles/install/templates下面  cd  /etc/ansible/nginx_install/roles  定义common的tasks,nginx是需要一些依赖包的 vim  ./common/tasks/main.yml //内容如下 - name: Install initializtion require software   yum: name={{ item }} state=installed   with_items:     - zlib-devel     - pcre-devel

创建文件

[root@shuai-01 ansible]# mkdir nginx_install
[root@shuai-01 ansible]# cd nginx_install/
[root@shuai-01 nginx_install]# mkdir -p roles/{common,install}/{files,handles,mate,tasks,templates,vars}
[root@shuai-01 nginx_install]# ls
roles
[root@shuai-01 nginx_install]# ls roles/
common  install
[root@shuai-01 nginx_install]# ls roles/install/
files  handles  mate  tasks  templates  vars
[root@shuai-01 nginx_install]# ls roles/common/
files  handles  mate  tasks  templates  vars


将Nginx打包,配置文件复制到相应的目录下

[root@shuai-01 local]# tar czvf nginx.tar.gz --exclude "nginx.conf" --exclude "vhost" /usr/local/nginx
[root@shuai-01 local]# mv nginx.tar.gz /etc/ansible/nginx_install/roles/install/files/
[root@shuai-01 local]# cp nginx/conf/nginx.conf /etc/ansible/nginx_install/roles/install/templates/
[root@shuai-01 local]# cp /etc/init.d/nginx /etc/ansible/nginx_install/roles/install/templates/


common目录下编辑一个安装依赖包的task

[root@shuai-01 common]# vim tasks/main.yml
- name: Install initializtion require software
  yum: name="zlib-devel,pcre-devel" state=installed


定义需要的变量

[root@shuai-01 install]# vim vars/main.yml
nginx_user: www
nginx_port: 80
nginx_basedir: /usr/local/nginx


写拷贝的yml

[root@shuai-01 install]# vim 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
  template: src=nginx.conf dest={{ nginx_basedir }}/conf/ owner=root group=root mode=0644


写建立用户,启动,服务管理的yml

[root@shuai-01 install]# vim 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


一个yml将copy.yml,install.yml包含进去

[root@shuai-01 install]# vim tasks/main.yml
- include: copy.yml
- include: install.yml


一个调用的主yml

[root@shuai-01 install]# vim /etc/ansible/nginx_install/install.yml
---
- hosts: testhost
  remote_user: root
  gather_facts: True
  roles:
    - common
    - install


[root@shuai-01 common]# ansible-playbook /etc/ansible/nginx_install/install.yml 



执行结果
[root@shuai-01 common]# ansible-playbook /etc/ansible/nginx_install/install.yml 

PLAY [shuai-02] *************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [shuai-02]

TASK [common : Install initializtion require software] **********************************
ok: [shuai-02]

TASK [install : Copy Nginx Software] ****************************************************
changed: [shuai-02]

TASK [install : Uncompression Nginx Software] *******************************************
 [WARNING]: Consider using the unarchive module rather than running 'tar'.  If you need
to use command because unarchive is insufficient you can add 'warn: false' to this
command task or set 'command_warnings=False' in ansible.cfg to get rid of this message.

changed: [shuai-02]

TASK [install : Copy Nginx Start Script] ************************************************
changed: [shuai-02]

TASK [install : Copy Nginx Config] ******************************************************
changed: [shuai-02]

TASK [install : Create Nginx User] ******************************************************
changed: [shuai-02]

TASK [install : Start Nginx Service] ****************************************************
changed: [shuai-02]

TASK [install : Add Boot Start Nginx Service] *******************************************
changed: [shuai-02]

TASK [install : Delete Nginx compression files] *****************************************
 [WARNING]: Consider using the file module with state=absent rather than running 'rm'.
If you need to use command because file is insufficient you can add 'warn: false' to
this command task or set 'command_warnings=False' in ansible.cfg to get rid of this
message.

changed: [shuai-02]

PLAY RECAP ******************************************************************************
shuai-02                   : ok=10   changed=8    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   



[root@shuai-02 ~]# ps aux |grep nginx
root       3051  0.0  0.0  46312   952 ?        Ss   17:58   0:00 nginx: master process /usr/sbin/nginx -c /etc/nginx/nginx.conf
nginx      3052  0.0  0.1  46696  1912 ?        S    17:58   0:00 nginx: worker process
root       3181  0.0  0.0 112680   976 pts/0    R+   18:00   0:00 grep --color=auto ngin


 

playbook实战-管理配置文件

 

 生产环境中大多时候是需要管理配置文件的,安装软件包只是在初始化环境的时候用一下。下面我们来写个管理nginx配置文件的playbook  mkdir  -p /etc/ansible/nginx_config/roles/{new,old}/{files,handlers,vars,tasks}  其中new为更新时用到的,old为回滚时用到的,files下面为nginx.conf和vhosts目录,handlers为重启nginx服务的命令  关于回滚,需要在执行playbook之前先备份一下旧的配置,所以对于老配置文件的管理一定要严格,千万不能随便去修改线上机器的配置,并且要保证new/files下面的配置和线上的配置一致

创建目录

[root@shuai-01 common]# mkdir -p /etc/ansible/nginx_config/roles/{new,old}/{files,handles,vars,tasks}
[root@shuai-01 common]# ls
files  handles  mate  tasks  templates  vars
[root@shuai-01 common]# cd /etc/ansible/nginx_config/



将上传的配置文件上传到对应的files目录

[root@shuai-01 nginx_config]# cp -r /usr/local/nginx/conf/nginx.conf /usr/local/nginx/conf/vhost /etc/ansible/nginx_config/roles/new/files/


定义变量yml

[root@shuai-01 nginx_config]# vim /etc/ansible/nginx_config/roles/new/vars/main.yml
nginx_basedir: /usr/local/nginx


定义重新加载yml

[root@shuai-01 nginx_config]# vim /etc/ansible/nginx_config/roles/new/handles/main.yml
- name: restart nginx
  shell: /etc/init.d/nginx reload


定义tasks的yml

[root@shuai-01 nginx_config]# vim /etc/ansible/nginx_config/roles/new/tasks/main.yml
- name: copy conf file
  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: vhost, dest: conf/ }
  notify: restart nginx



定义更新的入口

[root@shuai-01 nginx_config]# vim /etc/ansible/nginx_config/update.yml
---
- hosts: testhost
  user: root
  roles:
  - new



定义回滚的入口

[root@shuai-01 nginx_config]# vim /etc/ansible/nginx_config/rollback.yml
---
- hosts: testhost
  user: root
  roles:
  - old


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



更新使用update.yml

[root@shuai-01 nginx_config]# ansible-playbook /etc/ansible/nginx_config/update.yml 

PLAY [shuai-02] *************************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [shuai-02]

TASK [new : copy conf file] *************************************************************
ok: [shuai-02] => (item={u'dest': u'conf/nginx.conf', u'src': u'nginx.conf'})
ok: [shuai-02] => (item={u'dest': u'conf/', u'src': u'vhost'})

PLAY RECAP ******************************************************************************
shuai-02                   : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   

 

 

Logo

更多推荐