Ansible 基础语法
基础
register
---
- name: Check the user
hosts: h-1
tasks:
- name: View the logged in user name
shell: whoami
register: user
- debug:
var: user # 输出指定的内容 msg: "Logged in as user {{ user.stdout }}"
# - name: Create a register to represent the status if the /dev/sda1 exsited
# shell: df -h | grep sda1
# register: dev_sda1_result
# ignore_errors: True
# tags: docker
# - name: Copy docker.sh to all hosts
# copy: src=docker.sh dest=/usr/bin/docker mode=0755
# when: dev_sda1_result | succeeded
# tags: docker
register 将 task 执行的结果注册为变量,供后边使用
change
执行命令的状态,如果命令执行了,则为 true
cmd
当前执行的命令
delta
命令执行所花费的时间
start
命令开始执行的时间
end
命令结束的时间
failed
命令执行的结果,如果为 false 则表示命令执行成功,true 则表示命令执行失败
rc
命令执行的返回码(return code),0 表示执行成功
stderr
命令输出的标准错误信息
stderr_lines
按换行符分割输出的内容,在多行输出时,显示的效果比 stderr 更加直观
stdout
命令的标准输出信息
stdout_lines
按换行符分割输出的内容,在多行输出时,结果更加直观
root@dev:~# ansible-playbook -i hosts.test register-demo1.yaml
PLAY [Check the user] ************************************************************************************************
TASK [Gathering Facts] ***********************************************************************************************
ok: [h-1]
TASK [View the logged in user name] **********************************************************************************
changed: [h-1]
TASK [debug] *********************************************************************************************************
ok: [h-1] => {
"user": {
"changed": true,
"cmd": "whoami",
"delta": "0:00:00.005363",
"end": "2018-08-07 15:33:44.057578",
"failed": false,
"msg": "",
"rc": 0,
"start": "2018-08-07 15:33:44.052215",
"stderr": "",
"stderr_lines": [],
"stdout": "root",
"stdout_lines": [
"root"
]
}
}
PLAY RECAP ***********************************************************************************************************
h-1 : ok=3 changed=1 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
ignore_errors
ignore_errors
设置成True,用来忽略错误,表示即使当前task执行报错,ansible也会忽略这个错误,继续执行playbook
ad-hoc 模式运行
ad-hoc
意思:for this purpose only
Ansible ad-hoc 临时命令使用 /usr/bin/ansible
命令行工具在一个或多个受管节点上自动执行单个任务
# ping
ansible -i hosts all -m ping
# inventory 文件
$ cat hosts
[all]
192.168.179.21
192.168.179.22
# 执行 shell
ansible -i hosts all -m shell "pwd"
ansible -i hosts all -m shell -a "cat /etc/hosts"
# sync file
ansible -i hosts all -m copy -a "src=/root/centos-7.repo dest=/etc/yum.repos.d/"
# 安装 nginx
ansible -i hosts all -m yum -a "name=nginx state=installed"
ansible -i hosts all -m shell -a "yum info nginx"
ansible -i hosts all -m service -a "name=nginx state=started"
ansible -i hosts all -m shell -a "nginx -t"
ansible -i hosts all -m pip -a "name=python3-pip state=present"
ansible -i hosts all -a "hostname"