简述:这里只介绍了一些简单的模块例子,想更深入的学习可以查看下面两个地址。
英文手册:https://docs.ansible.com/ansible/latest/index.html
中文权威指南:http://www.ansible.com.cn/index.html
inventory:
inventory文件定义主机以及主机组变量
playbook:
playbooks是ansible的脚本、如同shell脚本一样,它是控制远程主机的一系列命令的集合,通过YAML语言编写。执行一些简单的任务,我们可以使用ad-hoc命令就可以解决,对于一些较复杂的任务,ad-hoc就不能胜任了,这时候playbooks就派上用场了,在playbooks中可以编排有序的执行过程,甚至可以在多组机器间来回有序的执行特定的步骤,并且可以同步或异步发起任务。
inventory_host示例:
[kubernetes:children]
master
minion
#master组
[master]
100.100.111.108 ansible_ssh_pass='ASx@7NCL' ansible_port=22 kuberole=[minion,master]
#minion组
[minion]
100.100.111.108 ansible_ssh_pass='ASx@7NCL' ansible_port=22 kuberole=[minion,master]
10.21.59.55 ansible_ssh_pass='2yxSf_DA' ansible_port=22 kuberole=[minion]
#参数
[kubernetes:vars]
data_dir=/data
playbook.yaml示例::
---
- name: one example
remote_user: root
hosts: kubernetes
tasks:
#shell,debug,register
#将shell命令执行的输出保存在disk_status变量里面
- name: Query the disk_status
shell: fdisk -l
register: disk_status
#打印出disk_status变量的属性值
- name: Print disk
debug: var=' disk_status.stdout '
#stat,register
#将查询到的文件信息保存在dir_exist里面
- name: Query file
stat: path={{ data_dir }}
register: dir_exist
#如果dir_exist记录的文件不存在则创建一个{{ data_dir }}相应的目录
- name: Create the data directory
shell: mkdir -p {{ data_dir }}
when: not dir_exist.stat.exists
local_action
在本地执行机上执行 echo 会在本地生成一个test01的文件
- name: echo test01
shell: 'echo "test01 " >> test01'
connection: local
#在本地执行机上执行 echo 会在本地生成一个test02的文件
- name: echo test02
shell: 'echo "test02 " >> test02'
connection: local
#copy
#将本地文件复制到远程机器上
- name: Copy example
copy: src='./{{ item }}' dest=/data/
with_items:
- test01
- test02
#copy
#将本地文件复制到远程机器上
- name: Copy example
copy: src='./{{ item }}' dest=/data/
with_items:
- test01
- test02
#file
#删除远程机器上的文件
- file: path=/data/{{ item }} state=absent
with_items:
- test01
- test02
#删除本地文件
- file: path={{ item }} state=absent
with_items:
- test02
connection: local
service
重启ssh服务
- name: restart ssh
service: name=ssh state=restarted enabled=yes
when: '"master" in kuberole'
指定inventory执行playbook命令:
ansible-playbook -i inventory_host playbook.yaml
使用ansible脚本清理none镜像的一个demo
![](https://img.haomeiwen.com/i2496446/7dd0162e8bf7b1ce.png)
inventory:
[node]
47.98.218.146 ansible_ssh_pass='asasasas' ansible_port=22
47.98.218.147 ansible_ssh_pass='asasasas' ansible_port=22
47.98.218.148 ansible_ssh_pass='asasasas' ansible_port=22
47.98.218.149 ansible_ssh_pass='asasasas' ansible_port=22
47.98.218.150 ansible_ssh_pass='asasasas' ansible_port=22
clear_image.yaml
---
- name: clear none images
remote_user: root
hosts: node
tasks:
- name: Query none images
shell: docker images -f "dangling=true" -q
register: docker_images
- name: Print none images
debug: var=' docker_images.stdout '
- name: Delete none image
shell: docker rmi $(docker images -f "dangling=true" -q)
指定inventory执行playbook命令:
ansible-playbook -i inventory image-clear.yaml
网友评论