设为首页 收藏本站
查看: 1493|回复: 0

[经验分享] ansible 常用模块

[复制链接]

尚未签到

发表于 2017-11-27 14:15:02 | 显示全部楼层 |阅读模式
                                               

执行前设定

它的Config文件呢,默认在/etc/ansible/ansible.cfg

第一步,就是我们的ansible的机器,需要链接上被它控制的机器。因为ansible的ssh是默认有个检查key的设置,我们第一次使用它,肯定对面机器没有Public key啊,所以我们要关闭配置文件内的private key的检查:

host_key_checking = False

生成ssh-key

生成ssh-key这部分,就不再多说了。

创建你的hosts

设置控制的主机清单在/etc/ansible/hosts下

然后就是要把你想控制的机器的ip\域名等等按照ansible的格式写进去:

如:

[webservers]
foo.example.com
bar.example.com

什么意思呢?我把域名为foo.example.com和bar.example.com的2个机器,分给了webservers组。  

除了域名也可以这样:

[dbservers]
192.168.10.12
127.152.112.13

如果某些主机的SSH运行在自定义的端口上,但是如果修改   ansible使用openssh进行ssh连接时将会使用:
    192.168.1.1:3091
假如你想要为某些静态IP设置一些别名,可以这样做:
    web1 ansible_ssh_port = 3333 ansible_ssh_host = 192.168.1.2
上面的 web1别名就指代了IP为192.168.1.2,ssh连接端口为3333的主机。

  [webservers]
   www[01:50].yanruogu.com
   [databases]
   db-[a:f].yanruogu.com
上面指定了从web1到web50,webservers组共计50台主机;databases组有db-a到db-f共6台主机。

这时候,有经验的运维人员,肯定纳闷,又没配好ssh,又没地方写密码用户,怎么连过去?

这里ansible是准备好了答案的(主机变量),它支持在ssh配好以前,使用用户名密码登录远程机器

[webservers]
192.168.10.12  ansible_ssh_pass=123456 ansible_ssh_user=root
127.152.112.13 ansible_ssh_pass=123567 ansible_ssh_user=root

这么一设置,能理解了吧?那么我们本次第一次运行ansible的准备工作也差不多了。

示例

[iyunv@node1 .ssh]#vim /etc/ansible/hosts  

[websrvs]
172.18.21.100
172.18.21.200
[dbsrvs]
172.18.21.100
172.18.21.7
[iyunv@node1 .ssh]#ansible all --list-hosts
   hosts (3):
     172.18.21.100
     172.18.21.7
     172.18.21.200
[iyunv@node1 .ssh]#ansible websrvs --list-hosts
   hosts (2):
     172.18.21.100
     172.18.21.200
[iyunv@node1 .ssh]#ansible dbsrvs --list-hosts
   hosts (2):
     172.18.21.100
     172.18.21.7
这里执行了ansible的最简单的模块ping,让它对所有在Hosts里的机器进行ping.探测远程主机网络是否畅通
[iyunv@node1 .ssh]#ansible all -m ping
172.18.21.7 | SUCCESS => {
     "changed": false,
     "ping": "pong"
}
172.18.21.200 | SUCCESS => {
     "changed": false,
     "ping": "pong"
}
172.18.21.100 | SUCCESS => {
     "changed": false,
     "ping": "pong"
}

Ansible的安装、初始化、第一个ping,我们也搞定了。

那么我们可以继续说下,Ansible的常用命令了,不过这个部分我们只需要知道下就行了。

重点是后面的playbook。

这里需要说明下的就是,ansible本身是没有部署能力的,它只是个框架,它的模块才有真正的部署能力。

Command 模块

在远程主机运行命令

常用参数:

chdir   运行command命令前先cd到这个目录

creates  如果这个参数对应的文件存在,就不运行command

executable   将shell切换为command执行,这里的所有命令需要使用绝对路径

removes  如果这个参数对应的文件不存在,就不运行command,存在运行

示例:

ansible-doc -s command   [url=]\\可以查看这个模块的帮助信息[/url]
ansible 172.18.21.100 -m command -a "pwd chdir=/tmp"   [url=]\\在172.18.21.10主机切换到/tmp目录执行pwd命令[/url]
ansible 172.18.21.100 -m command -a "mkdir mydir chdir=/app" [url=]\\在远程主机创建目录[/url]
ansible 172.18.21.100 -m command -a "mkdir mydir chdir=/app creates=mydir"  [url=]\\creates表示此文件或者目录如果存在就不执行[/url]
172.18.21.100 | SUCCESS | rc=0 >>
skipped, since mydir exists
ansible 172.18.21.100 -m command -a "touch f1 chdir=/app removes=f1"

172.18.21.100 | SUCCESS | rc=0 >>
skipped, since f1 does not exist

shell 模块

这个是一个很神奇的模块,它也是ansible的核心模块之一。它跟command模块一样负责在被ansible控制的节点(服务器)执行命令行。它与command模块有着相似的地方,也有不同的地方如在远程主机的shell进程下运行命令,支持shell特性,如管道等

常用参数


chdir   运行command命令前先cd到这个目录

creates  如果这个参数对应的文件存在,就不运行command

removes  如果这个参数对应的文件不存在,就不运行command,存在运行

案例1:

让所有节点运行somescript.sh并把log输出到somelog.txt。

ansible websrvs -m shell -a "/usr/bin/sh  somescript.sh >> somelog.txt"

案例2:

先进入somedir/ ,再在somedir/目录下让所有节点运行somescript.sh并把log输出到somelog.txt。

ansible websrvs -m shell -a "somescript.sh >> somelog.txt" chdir=somedir/

案例3:

体验shell和command的区别,先cd到某个需要编译的目录,执行condifgure然后,编译,然后安装。

ansible websrvs -m shell -a "./configure && make && make insatll" chdir=/xxx/yyy/

案例4:

ansible-doc -s shell
ansible websrvs -m command -a "useradd user1"  [url=]\\在远程的两个主机上创建一个用户[/url]
ansible websrvs -m shell -a "echo magedu|passwd --stdin user1"  [url=]\\创建一个密码[/url]
ansible websrvs -m shell -a "echo magedu|passwd --stdin user1 executable=/bin/tcsh" [url=]\\也可以指定其他的shell类型,这要这个shell类型可以解析里面的命令即可[/url]


user模块

用户管理

     state={present|absent}   #present表示创建,absent表示删除。

force=yes          #强制删除用户。 一般情况下用户在已登录状态下是不能删除的。相当于userdel -f

remove=yes     #在删除用户的时候,同时删除家目录与mail spool。相当于userdel -r   

system=yes   #创建的系统用户   

uid                #指定uid

shell             #指定shell

password       #用来指定密码,要用已加密的密码。

示例

ansible websrvs -m user -a "name=tom groups=haproxy state=present uid=3000 shell=/usr/bin/sh"

[url=]\\!/usr/bin/sh用途就是指出本脚本是用的哪种shell写的,执行时系统应该用哪种shell来解释执行它[/url]

ansible websrvs -m user -a "name=tom groups=haproxy state=present uid=3000 shell=/usr/bin/sh  generate_ssh_key=true"   [url=]\\创建用户并生产公钥私钥对[/url]

ansible websrvs -m user -a "name=test01 state=absent remove=yes"  [url=]\\删除用户[/url]

group模块

组管理

      gid        # Optional `GID' to set for the group.

      name       # Name of the group to manage.

      state     # Whether the group should be present or not on the remote host.

      system   # If `yes', indicates that the group created is a system group.

跟user差不多

示例

ansible websrvs -C -m group -a "name=haproxy system=no state=present" [url=]\\先测试跑一遍看有没有错误[/url]
ansible websrvs -m group -a "name=haproxy system=no state=present" [url=]\\state为状态,指明是创建还是删除,创建用present,删除用absent,不是系统组[/url]

ansible websrvs -m group -a "name=haproxy system=no state=absent"   [url=]\\---删除组[/url]


copy模块

复制文件到远程主机

content          #代替src,可以直接设定指定文件的内容 。

src                    #要复制到远程主机的文件在本地的地址,可以是绝对路径,也可以是相对路径。如果路径是一个目录,它将递归复制。在这种情况下,如果路径使用"/"来结尾,则只复制目录里的内容,如果没有使用"/"来结尾,则包含目录在内的整个内容全部复制,类似于rsync。。

owner                 #属主。

group                 #属组。

mode                   #权限。   

dest         #必选项。要将源文件复制到的远程主机的绝对路径,如果源文件是一个目录,那么该路径也必须是个目录

backup       #覆盖文件之前,先备份。 yes/no

others       #所有的file模块里的选项都可以在这里使用

force        #如果目标主机包含该文件,但内容不同,如果设置为yes,则强制覆盖,如果为no,则只有当目标主机的目标位置不存在该文件时,才复制。默认为yes

vim /app/test.txt
hello magedu
welcome
ansible all -m copy -a "src=/app/test.txt dest=/app/ owner=daemon group=nobody mode=664"
ansible all -m copy -a "content='hello true\n how are you\n' dest=/app/test2.txt"  [url=]\\也可以复制一个内容到一个文件中[/url]
fetch模块

从远程主机取文件
ansible 172.18.21.7 -m fetch -a "src=/etc/fstab dest=/app/fstab" [url=]\\注意这里只能有一台主机上去取[/url]
file模块

设置文件的属性、创建空文件和目录软连接等

file模块主要用于远程主机上的文件操作,file模块包含如下选项:

force:需要在两种情况下强制创建软链接,一种是源文件不存在但之后会建立的情况下;另一种是目标软链接已存在,需要先取消之前的软链,然后创建新的软链,有两个选项:yes|no

group:定义文件/目录的属组

mode:定义文件/目录的权限

owner:定义文件/目录的属主

path:必选项,定义文件/目录的路径

recurse:递归的设置文件的属性,只对目录有效

src:要被链接的源文件的路径,只应用于state=link的情况

state:  

directory:如果目录不存在,创建目录

file:即使文件不存在,也不会被创建,用于修改已存在文件的权限

link:创建软链接   src=源文件   path=链接文件

hard:创建硬链接

touch:如果文件不存在,则会创建一个新的文件,如果文件或目录已存在,则更新其最后修改时间

absent:删除目录、文件或者取消链接文件


ansible all -m file -a "path=/app/hidir state=directory owner=nobody mode=700" [url=]\\在远程主机创建一个空目录,并指定权限[/url]
ansible all -m file -a "path=/app/ff state=touch owner=nobody mode=770" [url=]\\创建空文件并指定权限,注意这里要用touch[/url]
ansible all -m file -a "path=/app/ff state=file owner=daemon mode=770" [url=]\\file只能用于已经存在文件修改权限,如果文件不存在不会创建[/url]
ansible all -m file -a "path=/app/fff src=/app/ff state=link" [url=]\\创建一个软连接文件/app/fff指向源文件/app/ff[/url]
ansible all -m file -a "path=/app/fff state=absent"  [url=]\\删除文件[/url]
get_url模块

该模块主要用于从http、ftp、https服务器上下载文件(类似于wget),主要有如下选项:

sha256sum:下载完成后进行sha256 check;

timeout:下载超时时间,默认10s

url:下载的URL必须有

url_password、url_username:主要用于需要用户名密码进行验证的情况

use_proxy:是事使用代理,代理需事先在环境变更中定义

dest  下载到目录必须有

ansible all -m get_url -a "url=http://example.com/path/file.conf dest=/etc/foo.conf mode=0440"

ansible all -m get_url -a  "url=http://example.com/path/file.conf dest=/etc/foo.conf sha256sum=b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"

ansible all -m get_url -a "url=http://mirrors.sohu.com/centos/7/os/x86_64/RPM-GPG-KEY-CentOS-7 dest=/app"   [url=]\\下载网上的文件到多台主机[/url]
cron 模块

用于管理计划任务包含如下选项:

backup:对远程主机上的原任务计划内容修改之前做备份 backup=true
cron_file:如果指定该选项,则用该文件替换远程主机上的cron.d目录下的用户的任务计划
day:日(1-31,*,*/2,……)
hour:小时(0-23,*,*/2,……)  
minute:分钟(0-59,*,*/2,……)
month:月(1-12,*,*/2,……)
weekday:周(0-7,*,……)
job:要执行的任务,依赖于state=present
name:该任务的描述
special_time:指定什么时候执行,参数:reboot,yearly,annually,monthly,weekly,daily,hourly
state:确认该任务计划是创建present(默认)还是删除 absent
user:以哪个用户的身份执行

例:

[iyunv@localhost ~]# ansible wserver -m cron -a 'name=sync_time minute=*/5 job="/sbin/ntpdate 172.16.0.1 > /dev/null;/sbin/hwclock -w"'
连到一台主机看一下crontab。
[iyunv@localhost ~]# crontab -l
#Ansible: sync_time                #这个就是我们刚添加的。
*/5 * * * * /sbin/ntpdate 172.16.0.1 > /dev/null;/sbin/hwclock -w
删除:
[iyunv@localhost ~]# ansible wserver -m cron -a 'name=sync_time state=absent'

例: 添加每2天的2:30备份/etc目录到/var/backup下。
[iyunv@localhost ~]# ansible wserver -m cron -a 'name=etc_tar minute=30 hour=2 day=*/2 job="/bin/tar -Jcf /var/backup/`/bin/date "+\\%Y\\%m\\%d-\\%H\\%M"`.tar.xz /etc"'

查看一下:
#Ansible: etc_tar
30 2 */2 * * /bin/tar -Jcf /var/backup/`/bin/date +\%Y\%m\%d-\%H\%M`.tar.xz /etc
yum模块

在远程主机安装软件包

使用yum包管理器来管理软件包,其选项有:

config_file:yum的配置文件
disable_gpg_check:关闭gpg_check
disablerepo   #临时禁止使用yum库。 只用于安装或更新时。
enablerepo    #临时使用的yum库。只用于安装或更新时。
name:要进行操作的软件包的名字,也可以传递一个url或者一个本地的rpm包的路径
state:状态(present,absent,latest)
例:安装httpd。
这里只是说明一下conf_file的用法,yum的仓库文件没有在/etc/yum.repos.d/目录下的话。
[iyunv@localhost ~]# ansible wserver -m yum -a 'name=httpd state=present conf_file="/root/local.repo"'

如果库本来是禁止使用的,就要用enablerepo来临时使用这个库。
这里的yum库文件已经在/etc/yum.repos.d/目录下了,不需要conf_file指定配置文件了。
[iyunv@localhost html]# ansible wserver -m yum -a 'name=httpd state=present enablerepo=local'

安装包组

ansible test -m yum -a 'name="@Development tools" state=present' \安装包组,只要在名称前面加上@

url路径安装

ansible test -m yum -a 'name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present

service模块
服务程序管理
arguments            #命令行提供额外的参数
enabled                 #设置开机启动。
name=                  #服务名称
runlevel                #开机启动的级别,一般不用指定。
sleep                     #在重启服务的过程中,是否等待。如在服务关闭以后等待2秒再启动。
state                      #started启动服务, stopped停止服务, restarted重启服务,reloaded重载配置。

启动httpd服务:
[iyunv@localhost html]# ansible all -m service -a 'name=httpd state=started'
设置开机启动:
[iyunv@localhost ~]# ansible all -m service -a 'name=httpd enabled=yes'
重启服务:
[iyunv@localhost ~]# ansible all -m service -a 'name=httpd sleep=2 state=restarted'
unarchive模块
用于解压文件,模块包含如下选项:
  • copy:在解压文件之前,是否先将文件复制到远程主机,默认为yes。若为no,则要求目标主机上压缩包必须存在。
  • creates:指定一个文件名,当该文件存在时,则解压指令不执行
  • dest:远程主机上的一个路径,即文件解压的路径
  • grop:解压后的目录或文件的属组
  • list_files:如果为yes,则会列出压缩包里的文件,默认为no,2.0版本新增的选项
  • mode:解决后文件的权限
  • src:如果copy为yes,则需要指定压缩文件的源路径
  • owner:解压后文件或目录的属主

示例如下:
- unarchive: src=foo.tgz dest=/var/lib/foo   \复制到远程主机,在解压
- unarchive: src=/tmp/foo.zip dest=/usr/local/bin copy=no
- unarchive: src=https://example.com/example.zip dest=/usr/local/bin copy=no
filesystem模块
在块设备上创建文件系统
选项:
dev:目标块设备
force:在一个已有文件系统 的设备上强制创建
fstype:文件系统的类型
opts:传递给mkfs命令的选项
示例:
ansible test -m filesystem -a 'fstype=ext2 dev=/dev/sdb1 force=yes'
ansible test -m filesystem -a 'fstype=ext4 dev=/dev/sdb1 opts="-cc"'
mount模块
配置挂载点
选项:
dump
fstype:必选项,挂载文件的类型
name:必选项,挂载点
opts:传递给mount命令的参数
src:必选项,要挂载的文件
state:必选项
      present:只处理fstab中的配置
      absent:删除挂载点
      mounted:自动创建挂载点并挂载之
      umounted:卸载

示例1:

ansible test -m mount -a "name=/mnt/dvd src=/dev/sr0 fstype=iso9660 opts=ro state=present"

ansible test -m mount -a "name=/srv/disk src='LABEL=SOME_LABEL' state=present"

ansible test -m mount -a "name=/home src='UUID=b3e48f45-f933-4c8e-a700-22a159ec9077' opts=noatime state=present'"

示例2:

创建disk.img磁盘镜像文件

ansible test -a 'dd if=/dev/zero of=/disk.img bs=4k count=1024'

使用 losetup将磁盘镜像文件虚拟成快设备

ansible test -a 'losetup /dev/loop0 /disk.img'

给块设备创建文件系统

ansible test -m filesystem -a 'fstype=ext4 force=yes opts=-F dev=/dev/loop0'

挂载

ansible test -m mount -a  'name=/mnt src=/dev/loop0 fstype=ext4 state=mounted opts=rw'

经过上面的四步之后,我们就可以通过/tmp目录,像访问真实快设备一样来访问磁盘镜像文件disk.img。

ansible webs -m mount -a  'name=/mnt state=absent'  [url=]\\删除挂载点[/url]

script模块
发送脚本到各被管理节点,并执行。同样不需要参数。
[iyunv@localhost ~]# ansible all -m script -a 'test.sh'
直接在-a 后面指定脚本即可。
selinux模块
管理selinux选项
conf     #指定应用selinux的配置文件。
state=enforcing|permissive|disabled           #对应于selinux配置文件的SELINUX。
policy=targeted|minimum|mls        #对应于selinux配置文件的SELINUXTYPE

关闭selinux:
[iyunv@localhost ~]# ansible all -m selinux -a 'state=disabled'
在selinux处于enforceing状态下的时候只能用permissive。
在state非disabled的情况下必须要指定policy。

pip模块:在远程主机安装python库
常用参数name,state,version
npm模块:在远程主机安装node.js库
常用参数name,state,version

git模块:Deploy software (or files) from git checkouts
在websrvs每个节点上yum install git
访问此https://github.com/
搜索fastdfs
watermark,size_16,text_QDUxQ1RP5Y2a5a6i,color_FFFFFF,t_100,g_se,x_10,y_10,shadow_90,type_ZmFuZ3poZW5naGVpdGk=.jpg
[iyunv@node1 app]#ansible websrvs -m git -a "repo=https://github.com/happyfish100/fastdfs.git dest=/app/fastdfs"  [url=]\\可以在github上下载软件或者文件到远程多台主机[/url]
setup模块

setup模块,主要用于获取主机信息,在playbooks里经常会用到的一个参数gather_facts就与该模块相关。

这些信息是由特定格式的键和值组成的,键可以做为ansible的系统内建变量,可以调用这些变量使用,以后想使用哪些变量,可以用这种方式查找变量,相当于查字典的方式,如果要调用变量里面嵌套的变量可以使用外面的变量名[嵌套的变量]的方式实现.

setup模块下经常使用的一个参数是filter参数

具体使用示例如下:

[iyunv@ansible ~]# ansible db -m setup
db | SUCCESS => {
    "ansible_facts": {
        "ansible_all_ipv4_addresses": [
            "192.168.33.137",
            "172.17.42.1"
        ],
….
….

使用filter过滤等等,支持通配符

获取ip

[iyunv@ansible ~]# ansible db -m setup -a 'filter=ansible_default_ipv4'
获取主机名。。
[iyunv@ansible ~]# ansible db -m setup -a 'filter=ansible_nodename'
获取内存信息。
[iyunv@ansible ~]# ansible db -m setup -a 'filter=ansible_memory_mb'

可以使用grep过滤
[iyunv@node1 ~]$ ansible 172.18.251.90 -m setup |grep mem
        "ansible_memfree_mb": 1240,
        "ansible_memory_mb": {
        "ansible_memtotal_mb": 1823,

deploy_helper模块:Manages some of the steps common in deploying projects.
常用参数: backend、 host、 state、 weight
可以标记多台后端主机的状态,实现灰度发布
template模块:基于模板方式生成一个文件复制到远程主机
主要参数:*src,*dest,owner,group,mode
注意此模块只能在playbook中使用,而不能在命令行中使用,因为只有ansible-playbook才能收内建变量,基于内建变量才能生成
模板文件


                                       


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-419614-1-1.html 上篇帖子: 通过ansible部署高可用LNAMMKP架构 下篇帖子: ansible 介绍
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表