ansible 初级使用
yum install ansible -y
设置本机免密钥登录到 192.168.1.21
ssh-copy-id 192.168.1.21
vim /etc/ansible/hosts 添加2行
[web]
192.168.1.21
命令行操作方法,:ansible 主机组或ip -m 指定模块 -a 模块对应的参数
ansible 192.168.1.21 -m shell -a "echo hello"
192.168.1.21 | SUCCESS | rc=0 >>
hello
ansible 192.168.1.21 -m setup # 主机所有信息
ansible 192.168.1.21 -m setup -a "filter=ansible_hostname" # 用setup模块取得主机名
192.168.1.21 | SUCCESS => {
"ansible_facts": {
"ansible_hostname": "21hostname"
},
"changed": false
}
ansible web -m shell -a "echo hello"
192.168.1.21 | SUCCESS | rc=0 >>
hello
编写简单的play-book
cat test.yml
---
- hosts: 192.168.1.21
tasks:
- name: just test ansible
shell: echo hello
- name: get hostname
setup: filter=ansible_hostname
执行
ansible-play test.yml
PLAY [192.168.1.21] ********************************************************************************************************************************************************
TASK [Gathering Facts] *****************************************************************************************************************************************************
ok: [192.168.1.21]
TASK [just test ansible] ***************************************************************************************************************************************************
changed: [192.168.1.21]
TASK [get hostname] ********************************************************************************************************************************************************
ok: [192.168.1.21]
PLAY RECAP *****************************************************************************************************************************************************************
192.168.1.21 : ok=3 changed=1 unreachable=0 failed=0
如需要指定其他ip,可以
---
- hosts: all # 这改成all
tasks:
- name: just test ansible
shell: echo hello
- name: get hostname
setup: filter=ansible_hostname
ansible-playbook -i '192.168.1.21,' test.yml # -i 指定执行清单 记得192.168.1.21, 后面有逗号.
play-book 中传入默认变量
---
- hosts: 192.168.1.146
remote_user: root
vars:
- hello: hello-world # 设定hello 变量的默认值为 hello-world
gather_facts: false # 可选参数
tasks:
- name: var test
shell: echo {{ hello }} > /dev/pts/0
ansible-play a.yml 输出为hello-world
ansible-play a.yml -e hello=xiaoming 输出为小明
ansible play-book 一个套路,记得最基本的方法,使用其他模块一样的。
play-book 中做条件判断
- name: check kafka
shell: pip list | grep kafka | wc -l
ignore_errors: True
register: check_kafka
- name: pip install kafka-1.3.5
shell: pip install {{ item }}
with_items:
- kafka
when: check_kafka.stdout == "0"
判断是否已经安装了kafka 没安装则安装,已安装则跳过。
- name: install zabbix-agent for centos-7
yum: name=zabbix22-agent.x86_64 state=present
when: ansible_os_family == "RedHat" and ansible_distribution_major_version == "7"
判断是否是redhat或centos 7 版本,来安装对应的包。
ansible 基本操作(初试)
原文:http://blog.51cto.com/19941018/2067632