Linux自动运维工具Ansible的使用

Linux自动运维工具Ansible的使用

我们熟悉这个工具后, 可以很轻松的安装k8s.

一.介绍

ansible - run a task on a target host(s)

Ansible是一个用Python开发的运维工具, 可以在本地让远程主机执行命令, 项目地址: Github源码, 中文文档

二.安装

简单上阵, 我们的主机都是ubuntu, 请使用root用户:

sudo su
apt install ansible
ansible --version

配置文件:

ls /etc/ansible

ansible.cfg  hosts

三.使用

请建一台虚拟机, IP: 192.168.119.3, 虚拟机安装请查看VMware Workstation虚拟机安装

首先生成ssh密钥:

ssh-keygen -t rsa -P ""
cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys

之后scp公钥到远程主机, 使得主机间能够互访: scp ~/.ssh/authorized_keys root@192.168.119.3:/root/.ssh.

编辑/etc/ansible/hosts:

[jj]
192.168.119.3

开始测试:

root@xxxxxx:/etc/ansible# ansible jj -m ping
172.16.13.127 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

如果失败, 是因为远程主机没有安装python2:

ansible all -m raw -a "wget http://mirrors.163.com/.help/sources.list.trusty && mv -f sources.list.trusty /etc/apt/sources.list"


ansible all -m raw -a  "apt update && apt install -y python2.7 python-simplejson"

接着同步时间之后, 我们再来进行进一步使用:

ansible all -a 'apt install ntpdate'
ansible all -a 'ntpdate time.windows.com'

配置文件和秘钥可额外指定:

ansible autopush -i myansible.ini --private-key m.pem -m ping

四.深入使用

ansible基本有两种: -m后接模块名, -a后接命令参数.

ansible jj -m ping
ansible all -a 'curl www.baidu.com' 

如果获取模块列表:ansible-doc -l, 获取指定模块的使用帮助:ansible-doc -s ping

4.1.模块:command

一般命令操作:

ansible all -m command -a 'curl www.baidu.com' 

等同于:

ansible all -a 'curl www.baidu.com' 

command不支持管道, 请使用shell模块.

4.2.模块:shell

ansible all -m shell -a 'ls / | cat'

脚本传入:

ansible all -m shell -a "$1"

支持管道!

4.3.模块:copy

从本地复制文件到远程

(1) 复制文件

-a "src=  dest=  "

(2) 给定内容生成文件

-a "content=  dest=  "

从本地移动文件在远程:

ansible all -m copy -a 'src=/a.txt dest=/a/a.txt  mode=600'

4.4.模块:file

file模块:设置文件的属性. 此处指远程机器的文件.

(1) 创建目录:

-a "path=  state=directory"

ansible all -m file -a 'path=/test/a  state=directory'

(2) 创建链接文件:

-a "path=  src=  state=link"

ansible all -m file -a 'src=/test/a  path=/test/b state=link'

(3) 删除文件:

-a "path=  state=absent“

ansible all -m file -a 'path=/test/b state=absent'

4.5.模块:fetch

从远程拿文件:

 ansible all -m fetch -a 'src=/test/a.txt dest=/test'
ansible all -m fetch -a "src=$1 dest=/home/chenjh/log/$2"

不能从远程拿目录!

4.6.模块:cron

定制远程定时服务:

-a "minute=
hour=
day=
month=
weekday=
job=
name=
user=
state={present|absent}

absent是删除!

参考: 这篇文章

原文地址:https://www.cnblogs.com/nima/p/11751266.html