1. 指定单个ip运行(使用root用户)

ansible all -i 10.10.120.255, -m ping -u root  
 #检测连接是否正常
 10.10.120.255 | SUCCESS => {
    "ansible_facts": {
        "discovered_interpreter_python": "/usr/bin/python"
    }, 
    "changed": false, 
    "ping": "pong"
}

还有setup模块打印出的信息,在使用变量/判断的时候可以拿到很多有用的信息,比如指定操作系统平台或版本信息

ansible-playbook all -i 10.10.1.3, test.yml

ansible-playbook的用法

2. 使用yum安装httpd并启动

1
2
3
4
5
6
7
8
9
- name: install httpd
  yum: 
    name: httpd 
    state: present

- name: start httpd
  service: 
    name: httpd
    state: start

3. 新建目录,拷贝文件并给(改变)执行权限

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
- name: create zabbix directory
  file:
    path: /usr/local/zabbix
    state: directory

- name: copy tcp_connections.sh
  copy: src=../file/tcp_connections.sh dest=/etc/zabbix

- name: change tcp_connections.sh 
  file: dest=/etc/zabbix/tcp_connections.sh mode=a+x

4. 条件判断,只在centos7上安装zabbix

1
2
3
4
- name: centos7 install zabbix-agend
  shell: rpm -ivh https://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-agent-3.4.15-1.el7.x86_64.rpm
  when:
    ansible_distribution == "CentOS" and ansible_distribution_major_version == "7","ALL"

5. 定义handlers并引用

在handlers/main.yml中定义一个重启的handlers

1
2
3
4
- name: zabbix restart  #命名
  service: 
    name: zabbix-agent
    state: restarted

在tasks/main.yml中引用,只要执行过程中配置文件是change状态就触发notify

1
2
3
4
- name: up zabbix-agent file client
  template: src=zabbix_agentd.conf.j2 dest=/usr/local/zabbix/zabbix_agentd.conf
  notify: 
  - zabbix restart

6. 改变所在目录执行命令,如出错则忽略错误信息并继续执行

1
2
3
4
5
- name: enabled service zabbix-agent
  shell: ./zabbix_agentd.exe -i -c ./zabbix_agentd.conf
  args:
    chdir: /usr/local/zabbix
  ignore_errors: True

roles的目录树 ansible.png

7. 命令

1. ansible all -m ping
2. ansible all -m shell -a "echo $TERM"
3. ansible web -m copy -a "src=/etc/hosts dst=/etc/hosts"
4. ansible web -m file -a "dest=/etc/hosts mode=600","ALL"
5. ansible web -m yum -a "name=nginx state=present"
6. ansible web -m service -a "name=httpd state=restart"