ansible 命令
Inventory
:Ansible 管理的主机信息,包括 IP 地址、SSH 端口、账号、密码等Modules
:任务均有模块完成,也可以自定义模块,例如经常用的脚本。Plugins
:使用插件增加 Ansible 核心功能,自身提供了很多插件,也可以自定义插件。例如 connection 插件,用于连接目标主机。Playbooks
:“剧本”,模块化定义一系列任务,供外部统一调用。Ansible 核心功能。
编辑主机清单
1[webservers]
2192.168.0.20 ansible_ssh_user=root ansible_ssh_pass=’200271200’
3192.168.0.21 ansible_ssh_user=root ansible_ssh_pass=’200271200’
4192.168.0.22 ansible_ssh_user=root ansible_ssh_pass=’200271200’
5
6[dbservers]
710.12.0.100
810.12.0.101
1sed -i "s/#host_key_checking = .*/host_key_checking = False/g" /etc/ansible/ansible.cfg
命令行
1ansible all -m ping
2ansible all -m shell -a "ls /root" -u root -k
常用模块
在目标主机执行 shell 命令。
- shell
1- name: 将命令结果输出到指定文件
2 shell: somescript.sh >> somelog.txt
3- name: 切换目录执行命令
4 shell:
5 cmd: ls -l | grep log
6 chdir: somedir/
7- name: 编写脚本
8 shell: |
9 if [ 0 -eq 0 ]; then
10 echo yes > /tmp/result
11 else
12 echo no > /tmp/result
13 fi
14 args:
15 executable: /bin/bash
- copy 将文件复制到远程主机。
1- name: 拷贝文件
2 copy:
3 src: /srv/myfiles/foo.conf
4 dest: /etc/foo.conf
5 owner: foo
6 group: foo
7 mode: u=rw,g=r,o=r
8 # mode: u+rw,g-wx,o-rwx
9 # mode: '0644'
10 backup: yes
- file 管理文件和文件属性。
1- name: 创建目录
2 file:
3 path: /etc/some_directory
4 state: directory
5 mode: "0755"
6- name: 删除文件
7 file:
8 path: /etc/foo.txt
9 state: absent
10- name: 递归删除目录
11 file:
12 path: /etc/foo
13 state: absent
- present,latest:表示安装
- absent:表示卸载
- yum 软件包管理。
1- name: 安装最新版apache
2 yum:
3 name: httpd
4 state: latest
5- name: 安装列表中所有包
6 yum:
7 name:
8 - nginx
9 - postgresql
10 - postgresql-server
11 state: present
12- name: 卸载apache包
13 yum:
14 name: httpd
15 state: absent
16- name: 更新所有包
17 yum:
18 name: "*"
19 state: latest
20- name: 安装nginx来自远程repo
21 yum:
22 name: http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm
23 # name: /usr/local/src/nginx-release-centos-6-0.el6.ngx.noarch.rpm
24 state: present
- service/systemd 管理服务
1- name: 服务管理
2 service:
3 name: httpd
4 state: started
5 #state: stopped
6 #state: restarted
7 #state: reloaded
8- name: 设置开机启动
9 service:
10 name: httpd
11 enabled: yes
- unarchive 解压
1- name: 解压
2 unarchive: src=test.tar.gz
3 dest=/tmp
- debug 执行过程中打印语句。
1- debug:
2 msg: System {{ inventory_hostname }} has uuid {{ ansible_product_uuid }}
3
4- name: 显示主机已知的所有变量
5 debug:
6 var: hostvars[inventory_hostname]
7 verbosity: 4