获取目标主机的信息

ansible all -m setup -a "filter=ansible_os_family"

获取ip地址

# {{ ansible_eth0.ipv4.address }}
如:
CATALINA_OPTS="$CATALINA_OPTS
-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port=12345
-Dcom.sun.management.jmxremote.authenticate=false
-Dcom.sun.management.jmxremote.ssl=false
-Djava.rmi.server.hostname={{ ansible_eth0.ipv4.address }}"

定义变量

---
- hosts: all
  vars:
    username: chentiangang
    passwd: {{ ansible_eth0.ipv4.address }}

使用ip地址最后一段做my.cnf的server-id

    - name: change my.cnf server-id
      shell: server_id=`echo {{ ansible_eth0.ipv4.address }} | awk -F "." '{print \$4}'` ; sed -i "s#server-id = 1#server-id = ${server_id}#g" /etc/my.cnf

不执行仅测试

ansible-playbook test.yml -C

安装一个zabbix-agent

---
- hosts: newserver
  handlers:
    - name: restart zabbix-agent
      service: name=zabbix-agent state=restarted

  tasks:
    - name: install zabbix22-agent
      yum: name={{ item }} state=latest
#  -name: 删除zabbix-agent
#    yum: name={{ item }} state=absent
      with_items: zabbix22-agent

    - name: template
      template: src=/etc/ansible/roles/zabbix22-agent/templates/zabbix_agentd.conf dest=/etc/zabbix_agentd.conf owner=root group=root mode=0644
      notify: restart zabbix-agent
      when: ansible_os_family == "RedHat" and ansible_lsb.major_release == "7"

    - name: start zabbix-agent
      service: name=zabbix-agent state=started

检查语法

ansible-playbook main.yml --syntax-check

查看错误模块

ansible-playbook main.yml --verbose

要在运行之前查看哪些主机会受到影响,请执行以下操作:

ansible-playbook playbook.yml --list-hosts

正则

jinja中的正则
这边使用match和search关键字,匹配比较简单,用来when判断非常方便,直接贴一下官网代码和链接。

vars:
  url: "http://example.com/users/foo/resources/bar"

tasks:
    - debug: "msg='matched pattern 1'"
      when: url | match("http://example.com/users/.*/resources/.*")

    - debug: "msg='matched pattern 2'"
      when: url | search("/users/.*/resources/.*")

    - debug: "msg='matched pattern 3'"
      when: url | search("/users/")

---
- hosts: tomcatservers
  tasks:
    - name: create dir
      shell: hostname
      when:  ansible_hostname | search("inner-api")

指定远程连接端口

---
- hosts: ecAppB
  port: 22

  tasks:
    - name: ping
      ping:

首次连接不输yes的方法

打开/etc/ansible/ansible.cfg这一行的注释

默认情况下,首次登陆一台服务器,系统会提示是否要记住对端的指纹,用ansible也会这样,这样会导致需要手工输入yes或no,ansible 才可以往下执行。如需避免这种情况,需要在 /etc/ansible/ansible.cfg 文件中设置 host_key_checking = False
# uncomment this to disable SSH key host checking
host_key_checking = False

变量注册

---
- name: 注册变量
  shell: hostname | sed -r 's#(.*)(-)([A-Z])([0-9])#\1#g'
  register: pkgname

# 通过切片取到最终想要的结果
- debug: "msg='{{ pkgname.stdout_lines[0] }}.war'"

执行的时候不获取主机信息(Gathering Facts)

---
- hosts: java*
  gather_facts: no
  roles:
    - log/log-privileges

替换

    - name: PMM                        | Fix nginx config
      replace:
        dest: /etc/nginx/nginx.conf
        regexp: '^(\s*)listen'
        replace: '\1#listen'

ansible roles详解

https://www.cnblogs.com/zhaojiankai/p/7655855.html