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执行命令的状态,如果命令执行了,则为 truecmd当前执行的命令delta命令执行所花费的时间start命令开始执行的时间end命令结束的时间failed命令执行的结果,如果为 false 则表示命令执行成功,true 则表示命令执行失败rc命令执行的返回码(return code),0 表示执行成功stderr命令输出的标准错误信息stderr_lines按换行符分割输出的内容,在多行输出时,显示的效果比 stderr 更加直观stdout命令的标准输出信息stdout_lines按换行符分割输出的内容,在多行输出时,结果更加直观
ignore_errors
ignore_errors 设置成True,用来忽略错误,表示即使当前task执行报错,ansible也会忽略这个错误,继续执行playbook
ad-hoc 模式运行
ad-hoc意思:for this purpose onlyAnsible 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"