Ansible 常用模块介绍

添加ssh信任

信任的主机添加在 默认的配置文件 /etc/ansible/hosts [nodes] 下

---
- name: configure ssh connection
  hosts: nodes
  gather_facts: false
  connection: local
  tasks:
    - name: configure ssh connection
      shell: |
        ssh-keyscan {{inventory_hostname}} >>~/.ssh/known_hosts
        sshpass -p'Thtf#997' ssh-copy-id root@{{inventory_hostname}}

首先要解释的是{{inventory_hostname}},其中{{}}在前面的文章中已经解释过了,它可以用来包围变量,在解析时会进行变量替换。而这里引用的变量为inventory_hostname,该变量表示的是当前正在执行任务的目标节点在inventory中定义的主机名。

command、shell、raw、script 模块介绍

command、shell、raw和script这四个模块的作用和用法都类似,都用于远程执行命令或脚本:
(1).command模块:执行简单的远程shell命令,但不支持解析特殊符号”< > | ; &”等,比如需要重定向时不能使用command模块,而应该使用shell模块
(2).shell模块:和command相同,但是支持解析特殊shell符号
(3).raw模块:执行底层shell命令。command和shell模块都是通过目标主机上的python代码启动/bin/sh来执行命令的,但目标主机上可能没有安装python,这时只能使用raw模块在远程主机上直接启动/bin/sh来执行命令,通常只有在目标主机上没有安装python时才使用raw模块,其它时候都不使用该模块
(4).script模块:在远程主机上执行脚本文件

---
- name: use some module
  hosts: new
  gather_facts: false
  tasks: 
    - name: use command module
      command: date +"%F %T"

    - name: use shell module
      shell: date +"%F %T" | cat >/tmp/date.log

    - name: use raw module
      raw: date +"%F %T"

如果要执行的命令有多行,根据之前文章中介绍的YAML语法,可以换行书写。例如:

---
- name: use some module
  hosts: new
  gather_facts: false
  tasks: 
    - name: use shell module
      shell: |
        date +"%F %T" | cat >/tmp/date.log
        date +"%F %T" | cat >>/tmp/date.log

如果想要看到命令的输出结果,可在执行playbook的时候加上一个-v选项:

$ ansible-playbook -v module.yaml

执行脚本

如果要执行的是一个远程主机上已经存在的脚本文件,可以使用shell、command或raw模块,但有时候脚本是写在Ansible控制端的,可以先将它拷贝到目标主机上再使用shell模块去执行这个脚本,但更佳的方式是使用script模块,script模块默认就是将Ansible控制端的脚本传到目标主机去执行的。此外,script模块和raw模块一样,不要求目标主机上已经装好python。

---
- name: use some module
  hosts: nodes
  gather_facts: false
  tasks:
    - name: use shell module
      script: /tmp/hello.sh  HELLOWORLD

幂等性

Ansible中绝大多数的模块都具有幂等特性,意味着执行一次或多次不会产生副作用。但是shell、command、raw、script这四个模块默认不满足幂等性,所以操作会重复执行,但有些操作是不允许重复执行的。例如mysql的初始化命令mysql_install_db,逻辑上它应该只在第一次配置的过程中初始化一次,其他任何时候都不应该再执行。所以,每当使用这4个模块的时候都要在心中想一想,重复执行这个命令会不会产生负面影响。

当然,除了raw模块外,其它三个模块也提供了实现幂等性的参数,即creates和removes:
(1).creates参数: 当指定的文件或目录存在时,则不执行命令
(2).removes参数: 当指定的文件或目录不存在时,则不执行命令

---
- name: use some module
  hosts: new
  gather_facts: false
  tasks: 
    # 网卡配置文件不存在时不执行
    - name: use command module
      command: ifup eth0
      args: 
        removes: /etc/sysconfig/network-scripts/ifcfg-eth0

    # mysql配置文件已存在时不执行,避免覆盖
    - name: use shell module
      shell: cp /tmp/my.cnf /etc/my.cnf
      args: 
        creates: /etc/my.cnf
Index