Ansible 基础

发布时间: 更新时间: 总字数:619 阅读时间:2m 作者:IP:上海 网址

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 按换行符分割输出的内容,在多行输出时,结果更加直观
ansible-playbook -i hosts.test register-demo1.yaml ...

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"
本文总阅读量 次 本站总访问量 次 本站总访客数