ansible的安装及常用的模块和命令

ansible的安装方式

官网:https://www.ansible.com/
Ansible是基于Python语言开发,轻量级批量管理工具

ansible介绍

Ansible基于Paramiko实现SSH协议链接通讯,默认只要被管理节点开启SSH服务,Ansible就可以管理远程主机

使用Ansible不需要在客户端主机(被管理主机)安装Agent

Ansible模块化设计,并且模块丰富,支持自定义模块,自定义模块可用任何语言编写

Ansible基于PyYAML模块支持Playbook,可以通过Playbook完成可重复的复杂工作

支持Jinjia2模板

ansible安装:

安装ansible软件包,由于ansible需要epel源,本实验配置了阿里的epel源和阿里的Base源(Base源用于安装ansible所需依赖),本地的CentOS7镜像源

[root@ansible-server ~]# yum -y install wget	#下载wget工具
[root@ansible-server ~]# wget -O /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo	#下载阿里Base源
[root@ansible-server ~]# wget -O /etc/yum.repos.d/epel.repo http://mirrors.aliyun.com/repo/epel-7.repo		 #下载阿里epel源

安装ansible软件包

[root@ansible-server ~]# yum -y install ansible

下载完成,查看ansible版本

[root@ansible-server ~]# ansible --version
ansible 2.9.27
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Oct 14 2020, 14:45:30) [GCC 4.8.5 20150623 (Red Hat 4.8.5-44)]

安装好,会显示以上信息

定义ansible主机清单

  • ansible主配置文件:/etc/ansible/ansible.cfg
  • ansible默认清单文件:/etc/ansible/hosts

编辑清单文件定义主机组

[root@ansible-server ansible]# vim hosts
...
[test]
192.168.122.11
192.168.122.22

[all:vars]
ansible_ssh_user=root
ansible_ssh_password=root
ansible_ssh_port=22               ##这种是2.9版本的配置方法

#[all:vars]
#ansible_user=root
#ansible_password=root
#ansible_port=22                  ##这种是2.8版本的配置方法

列出组内主机列表

[root@ansible-server ansible]# ansible test --list-host
  hosts (2):
    192.168.122.11
    192.168.122.22

注意
需要给给客户机做主机名做个解析

[root@ansible-server ~]# vim /etc/hosts
...
127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
192.168.122.11 web1
192.168.122.22 web2

再做个免密

[root@ansible-server ansible]# ssh-keygen
...
[root@ansible-server ansible]# for i in web1 web2
> do
> ssh-copy-id $i
> done

使用ping模块测试websrvs组主机连通性

[root@ansible-server ansible]# ansible test -m ping
192.168.122.22 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}
192.168.122.11 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

Ansible命令返回值的颜色所表示的意思

  • 绿色:代表对远程节点不进行相应修改,没有发生改变,命令执行成功了
  • 黄色:代表对远程节点进行了相应的修改,命令执行成功了
  • 红色:代表你的命令执行失败或者是有异常,反正就是错误了
  • 粉色:代表命令执行后发出的警告信息,给我们一些建议(可以忽略)

Ansible命令格式介绍
常用命令格式:ansible 组名/主机 [-m 模块名] [-a 模块参数]
查询模块参数命令:ansible-doc -s 模块名
例:

[root@ansible-server ansible]# ansible-doc -s shell
- name: Execute shell commands on targets
  shell:
      chdir:                 # Change into this directory before running the command.
      cmd:                   # The command to run followed by optional arguments.
      creates:               # A filename, when it already exists, this step will *not* be run.
      executable:            # Change the shell used to execute the command. This expects an absolute path to the executable.
      free_form:             # The shell module takes a free form command to run, as a string. There is no actual parameter named 'free form'. See the examples on how to use this module.
      removes:               # A filename, when it does not exist, this step will *not* be run.
      stdin:                 # Set the stdin of the command directly to the specified value.
      stdin_add_newline:     # Whether to append a newline to stdin data.
      warn:                  # Whether to enable task warnings.

ansible常用模块

command 模块
  • command模块为默认模块,用于远程执行命令(命令模块)

  • 注意:使用command模块在远程主机中执行命令时,不会经过远程主机的shell处理,在使用command模块时,如果需要执行的命令中含比如”<“, “>”, “|”, “;” 和 “&” 这些符号时,这些符号的功能也会失效
    command模块示例:

[root@ansible-server ~]# ansible websrvs -m command -a 'hostname'
[root@ansible-server ~]# ansible websrvs -m command -a 'ip a s ens32'
[root@ansible-server ~]# ansible websrvs -a 'uname -r'	#查看内核信息
[root@ansible-server ~]# ansible websrvs -a 'free -h'	#查看内存信息
shell 模块
  • shell 模块,远程执行命令模块,和command模块类似,区别在于shell模块通过/bin/bash程序处理命令

  • 常用参数

    • cmd:此参数指定用于执行的命令(用于在Playbook剧本中)
    • chdir:此参数表示执行命令之前,会先进入到指定的目录中
    • creates: 此参数表示文件如果存在于远程主机中,则不执行对应命令,如果不存在,才执行
    • removes:此参数表示文件如果不存在于远程主机中,则不执行对应命令,如果存在 ,才执行

shell 模块示例

#查看/etc/passwd文件,并通过管道符传递给“wc -l”统计文件行数
[root@ansible-server ~]# ansible websrvs -m shell -a 'cat /etc/passwd | wc -l'

#查看/etc/passwd文件,并通过“>”将文件内容重定向至/opt/passwd文件中
[root@ansible-server ~]# ansible websrvs -m shell -a 'cat /etc/passwd > /opt/passwd'

#通过chdir参数进入/opt/目录,执行“ls”
[root@ansible-server ~]# ansible websrvs -m shell -a 'chdir=/opt/ ls'

#通过chdir参数进入/opt目录,执行“cat”查看passwd文件内容
[root@ansible-server ~]# ansible websrvs -m shell -a 'chdir=/opt/ cat passwd'

#查看主机名
[root@ansible-server ~]# ansible websrvs -m shell -a 'hostname'

#查看内核信息
[root@ansible-server ~]# ansible websrvs -m shell -a 'uname -r'

#查看ens32网卡的IP地址信息
[root@ansible-server ~]# ansible websrvs -m shell -a 'ip a s ens32 | grep inet'

#查看内存使用信息
[root@ansible-server ~]# ansible websrvs -m shell -a 'free -h'

#查看分区使用信息
[root@ansible-server ~]# ansible websrvs -m shell -a 'df -h'

#关闭防火墙&&设置开机不自起
[root@ansible-server ~]# ansible websrvs -m shell -a 'systemctl stop firewalld && systemctl disable firewalld'
script 模块
  • script 模块用于远程执行脚本,脚本存放在ansible主机本地,不需要拷贝到远程主机

  • 常用参数:

    • chdir:此参数表示执行命令之前,会先进入到指定的目录中
    • creates: 此参数表示文件如果存在于远程主机中,则不执行对应命令,如果不存在,才执行命令
    • removes:此参数表示文件如果不存在于远程主机中,则不执行对应命令,如果存在 ,才执行命令

script模块示例:

#编写搭建yum仓库脚本
[root@ansible-server ~]# vim yum.sh 
#!/bin/bash
mkdir /mnt/centos
mount /dev/cdrom /mnt/centos
echo "/dev/cdrom /mnt/centos iso9660 defaults 0 0" >> /etc/fstab
rm -rf /etc/yum.repos.d/*
echo "[local_centos7]
name=local_centos7
baseurl=file:///mnt/centos
enabled=1
gpgcheck=0" > /etc/yum.repos.d/centos.repo
yum repolist

#使用script模块执行此脚本
[root@ansible-server ~]# ansible websrvs -m script -a '/root/yum.sh'
yum 模
  • yum 模块,用于在远程主机通过yum源管理软件包

  • 常用参数:

    • name:必须参数,用于指定需要管理的软件包名字

    • state:用于指定软件包的状态

      • present:此状态为默认值,表示安装软件包

      • installed:此状态表示安装软件包,与present等效

      • latest:此状态表示安装yum中最新版本软件包

      • removed:此状态表示删除对应软件包

      • absent:此状态表示删除对应软件包,与removed等效

yum模块示例:

#使用yum模块安装vsftpd软件包(本地yum源默认已经禁用软件包检测)
[root@ansible-server ~]# ansible websrvs -m yum -a 'name=vsftpd'

#卸载vsftpd软件包
[root@ansible-server ~]# ansible websrvs -m yum -a 'name=vsftpd state=removed'

#ftp组内主机安装vsftpd服务
[root@ansible-server ~]# ansible websrvs -m yum -a 'name=vsftpd'
service 模块
  • service 模块,用于管理远程主机的服务,如:启动或停止服务

  • 常用参数:

    • name:此参数用于指定需要操作的服务名称,如 vsftpd

    • state: 此参数用于指定服务的状态

started:此状态用于启动服务

#启动vsftpd服务
[root@ansible-server ~]# ansible websrvs -m service -a 'name=vsftpd state=started'

#查看服务状态
[root@ansible-server ~]# ansible websrvs -m shell -a 'systemctl status vsftpd'

restarted:此状态用于重启服务

#重启服务
[root@ansible-server ~]# ansible ftp -m service -a 'name=vsftpd state=restarted'

stopped:此状态用于停止服务

#停止vsftpd服务
[root@ansible-server ~]# ansible ftp -m service -a 'name=vsftpd state=stopped'

enabled:此参数 用于指定是否将服务设置为开机启动项,设置为yes表示将对应服务设置为开机启动,设置为no表示不会开机启动。

#启动服务并设置服务随机自启
[root@ansible-server ~]# ansible ftp -m service -a 'name=vsftpd state=started enabled=yes'
copy 模块
  • copy 模块,用于将文件复制到远程主机

  • 常用参数:

    • src:此参数用于指定需要拷贝的文件或目录
    • dest:此参数用于指定文件将拷贝到远程主机的哪个目录中,dest为必须参数
#在ansible本地主机创建文件
[root@ansible-server ~]# touch /tmp/test.txt

#将本地/tmp/test.txt文件拷贝至ftp组内主机的/var/ftp目录下
[root@ansible-server ~]# ansible ftp -m copy -a 'src=/tmp/test.txt dest=/var/ftp/'
[root@ansible-server ~]# ansible ftp -m shell -a 'ls /var/ftp'
  • content:此参数当不使用src指定拷贝的文件时,可以使用content直接指定文件内容,src与content两个参数必有其一,否则会报错
#使用content参数在远程主机直接创建文件并写入内容
[root@ansible-server ~]# ansible ftp -m copy -a 'content="hello" dest=/var/ftp/test1'

#查看远程主机文件内容
[root@ansible-server ~]# ansible ftp -a 'cat /var/ftp/test1'
  • force:此参数当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否强制覆盖,可选值有yes和no,默认值为yes,表示覆盖,如果设置为no,则不会执行覆盖拷贝操作,远程主机中的文件保持不变
#本地创建test1文件,并写入abc
[root@ansible-server ~]# echo abc > test1
[root@ansible-server ~]# cat test1

#使用force参数指定当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,不执行覆盖
[root@ansible-server ~]# ansible ftp -m copy -a 'src=/tmp/test1 dest=/var/ftp/test1 force=no'
192.168.0.25 | SUCCESS => {
    "changed": false

  • backup:此参数当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,是否对远程主机的文件进行备份,可选值有yes和no,当设置为yes时,会先备份远程主机中的文件,然后再将ansible主机中的文件拷贝到远程主机
#使用backup参数指定当远程主机的目标路径中已经存在同名文件,并且与ansible主机中的文件内容不同时,对远程主机文件先进行备份
[root@ansible-server ~]# ansible ftp -m copy -a 'src=/root/test1 dest=/var/ftp backup=yes'

#查看远程主机信息
[root@ansible-server ~]# ansible ftp -a 'ls /var/ftp'
...
test1
test1.12778.2021-03-16@00:57:26~  #备份后文件
  • owner:此参数指定文件拷贝到远程主机后的属主,但是远程主机上必须有对应的用户,否则会报错。
#创建文件
[root@ansible-server ~]# touch test2

#拷贝test2文件到远程主机,并指定属主为ftp用户
[root@ansible-server ~]# ansible ftp -m copy -a 'src=/root/test2 dest=/var/ftp/ owner=ftp'

#查看文件详细属性信息
[root@ansible-server ~]# ansible ftp -a 'ls -l /var/ftp/test2'
192.168.0.29 | CHANGED | rc=0 >>
-rw-r--r--. 1 ftp root 6 3月  16 01:07 /var/ftp/test2
#可以看到文件的属主以变成ftp用户
  • group:此参数指定文件拷贝到远程主机后的属组,但是远程主机上必须有对应的组,否则会报错
#创建test3文件
[root@ansible-server ~]# touch test3

#拷贝test3文件到远程主机,并指定属主为ftp用户,所属组为ftp用户基本组
[root@ansible-server ~]# ansible ftp -m copy -a 'src=/root/test3 dest=/var/ftp/ owner=ftp group=ftp'

#查看文件详细属性信息
[root@ansible-server ~]# ansible ftp -a 'ls -l /var/ftp/test3'
192.168.0.29 | CHANGED | rc=0 >>
-rw-r--r--. 1 ftp ftp 0 3月  16 01:16 /var/ftp/test3
  • mode:此参数指定文件拷贝到远程主机后的权限,如果你想将权限设置为”rw-r–r–“,则可以使用mode=0644表示
#拷贝test4文件到远程主机,并指定属主为ftp用户,所属组为ftp用户基本组,并指定权限为0744
[root@ansible-server ~]# ansible ftp -m copy -a 'src=/root/test4 dest=/var/ftp/ owner=ftp group=ftp mode=0744'

#查看文件详细属性信息
[root@ansible-server ~]# ansible ftp -a 'ls -l /var/ftp/test4'

#如果后期需要修改权限可以使用shell模块修改
[root@ansible-server ~]# ansible ftp -m shell -a 'chmod 755 /var/ftp/test4'
[root@ansible-server ~]# ansible ftp -a 'ls -l /var/ftp/test4'
192.168.0.29 | CHANGED | rc=0 >>
-rwxr-xr-x. 1 ftp ftp 0 3月  16 01:23 /var/ftp/test4
#可以看到,权限已被修改成功
Ansible剧本Playbook
Ansible playbook剧本介绍
  • 在ansible中,类似”脚本”的文件被称作”剧本”,英文名称为’playbook’ ,用于配置,部署,和管理被控节点

  • 我们只需要把模块按照顺序编排在playbook剧本中,ansible就会按照剧本一步一步的执行,最终达到我们的目的

  • playbook是由一个或多个”play”组成的列表,当我们在工作中往往需要不止做一件事情的时候,使用playbook会更加适合。

  • playbook 与ad-doc相比是一种完全不同的运用方式,剧本需要遵循YAML语法格式编写,文件名以”.yaml”或者”.yml”作为文件名后缀

playbook核心元素
  • hosts:执行的远程主机列表’
  • tasks:任务集
  • variables:内置变量或自定义变量在playbook中调用
  • tempaltes 模板,可替换文件中的变量并实现一些简单逻辑的文件
  • handles 和notify结合使用,由特定条件触发的操作,满足条件方执行,否则不执行
  • tags标签,指定某条任务执行,用于选择运行playbook中的部分代码。
    编写剧本的时候,不知道怎么用模块中的参数,可以使用ansible-doc 模块名,在例子EXAMPLES中就可以找到对应的例子,直接复制就能用
[root@ansible-server ansible]# ansible-doc shell
...
EXAMPLES:

- name: Execute the command in remote shell; stdout goes to the specified file on the remote.
  shell: somescript.sh >> somelog.txt

- name: Change the working directory to somedir/ before executing the command.
  shell: somescript.sh >> somelog.txt
  args:
    chdir: somedir/

# You can also use the 'args' form to provide the options.
- name: This command will change the working directory to somedir/ and will only run when somedir/somelog.txt doesn't exist.
  shell: somescript.sh >> somelog.txt
  args:
    chdir: somedir/
    creates: somelog.txt

# You can also use the 'cmd' parameter instead of free form format.
- name: This command will change the working directory to somedir/.
  shell:
    cmd: ls -l | grep log
    chdir: somedir/

- name: Run a command that uses non-posix shell-isms (in this example /bin/sh doesn't handle redirection and wildcards together but bash does)
  shell: cat < /tmp/*txt
  args:
    executable: /bin/bash

- name: Run a command using a templated variable (always use quote filter to avoid injection)
  shell: cat {{ myfile|quote }}
#以上这些全都是例子,可以直接拷贝使用,根据需要选择即可

编写第一个Playbook剧本

#使用ping模块测试远程主机联通性,并在远程主机创建目录
[root@ansible-server ~]# vim ping_websrvs.yml
---
- hosts: websrvs
  remote_user: root
  tasks:
  - name: ping websrvs
    ping:
  - name: mkdir directory test
    shell:
       cmd: mkdir /test
#      cmd: touch /root/myoutput.txt && cp /root/myoutput.txt /mnt/ 可以这样写,或者cmd: touch /root/myoutput.txt,cp /root/myoutput.txt /mnt/ 

#第一行:playbook剧本以---开头表明yaml格式文件
#第二行:使用”- “作为开头,”- “表示一个列表项,”- “后面使用hosts关键字指定要操作的主机组名,(注意:横杠后面有空格)表示我要在websrvs这组主机上进行操作,在YAML语法中,键值对需要使用冒号作为分隔,而且冒号后边必须还要有一个空格作为分隔
#第三行:remote_user关键字可以指定在进行远程操作时使用哪个用户进行操作
#第四行:tasks关键字是用来指定要执行哪些操作任务,之后的行都属于tasks任务列表中的任务,每个任务都以”- “开头,每个任务都有自己的名字,任务名使用name关键字进行指定

#运行剧本需要使用’ansible-playbook’命令
[root@ansible-server ~]# ansible-playbook ping_websrvs.yml
TASK [Gathering Facts]   ****************************************************************
ok: [192.168.0.28]
ok: [192.168.0.27]
ok: [192.168.0.26]

TASK [ping websrvs] ****************************************************************
ok: [192.168.0.26]
ok: [192.168.0.27]
ok: [192.168.0.28]

TASK [mkdir directory test] ****************************************************************
changed: [192.168.0.28]
changed: [192.168.0.26]
changed: [192.168.0.27]

PLAY RECAP ******************************************************************
192.168.0.26               : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.0.27               : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.0.28               : ok=3    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

Playbook源码部署Nginx的Web服务

[root@ansible-server ~]# vim nginx.yml
---
- hosts: websrvs
  remote_user: root
  tasks:
  - name: Copy nginx
    copy: src=/root/nginx-1.18.0.tar.gz  dest=/tmp
  - name: install Rely
    yum: name=gcc,pcre-devel,openssl-devel,zlib
  - name: unpacek nginx
    shell: tar -xf /tmp/nginx-1.18.0.tar.gz -C /tmp
  - name: install nginx
    shell:  cd /tmp/nginx-1.18.0 && ./configure && make && make install
  - name: Copy index.html
    copy: src=/root/index.html dest=/usr/local/nginx/html
  - name: start nginx
    shell: /usr/local/nginx/sbin/nginx


#--syntax-check 用于检测playbook语法是否正确,如果正确只返回playbook名称
[root@ansible-server ~]# ansible-playbook --syntax-check nginx.yml

playbook: nginx.yml

#--check 用于模拟执行playbook
[root@ansible-server ~]# ansible-playbook --check nginx.yml 

PLAY [websrvs] ****************************************************

TASK [Gathering Facts] *******************************************************************
ok: [192.168.0.28]
ok: [192.168.0.26]
ok: [192.168.0.27]

TASK [Copy nginx] *************************************************
ok: [192.168.0.28]
ok: [192.168.0.27]
ok: [192.168.0.26]

TASK [install Rely] ***********************************************
ok: [192.168.0.26]
ok: [192.168.0.27]
ok: [192.168.0.28]

TASK [unpacek nginx] **********************************************
skipping: [192.168.0.26]
skipping: [192.168.0.28]
skipping: [192.168.0.27]

TASK [install nginx] ******************************************************************
skipping: [192.168.0.26]
skipping: [192.168.0.27]
skipping: [192.168.0.28]

TASK [Copy index.html] ******************************************************************
ok: [192.168.0.27]
ok: [192.168.0.26]
ok: [192.168.0.28]

TASK [start nginx] ******************************************************************
skipping: [192.168.0.26]
skipping: [192.168.0.27]
skipping: [192.168.0.28]

PLAY RECAP ******************************************************************
192.168.0.26               : ok=4    changed=0    unreachable=0    failed=0    skipped=3    rescued=0    ignored=0   
192.168.0.27               : ok=4    changed=0    unreachable=0    failed=0    skipped=3    rescued=0    ignored=0   
192.168.0.28               : ok=4    changed=0    unreachable=0    failed=0    skipped=3    rescued=0    ignored=0   


#使用playbook剧本批量在远程主机源码安装nginx
[root@ansible-server ~]# ansible-playbook nginx.yml 

PLAY [websrvs] ******************************************************************

TASK [Gathering Facts] ******************************************************************
ok: [192.168.0.28]
ok: [192.168.0.27]
ok: [192.168.0.26]

TASK [Copy nginx] ******************************************************************
changed: [192.168.0.28]
changed: [192.168.0.27]
changed: [192.168.0.26]

TASK [install Rely] ******************************************************************
ok: [192.168.0.26]
ok: [192.168.0.27]
ok: [192.168.0.28]

TASK [unpacek nginx] ******************************************************************
changed: [192.168.0.28]
changed: [192.168.0.26]
changed: [192.168.0.27]

TASK [install nginx] *******************************************************************
changed: [192.168.0.26]
changed: [192.168.0.28]
changed: [192.168.0.27]

TASK [Copy index.html] *******************************************************************
changed: [192.168.0.27]
changed: [192.168.0.28]
changed: [192.168.0.26]

TASK [start nginx] ********************************************************************
changed: [192.168.0.27]
changed: [192.168.0.28]
changed: [192.168.0.26]

PLAY RECAP ********************************************************************
192.168.0.26               : ok=7    changed=5    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.0.27               : ok=7    changed=5    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0   
192.168.0.28               : ok=7    changed=5    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0 

以上只是ansible的一些简单操作,只是个入门,可以通过https://www.zsythink.net/archives/tag/ansible/page/5深入学习

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值