首页 > 技术文章 > Ansible 模块使用

huangjinbin 2018-04-14 23:26 原文

 1、变量控制

- hosts: woshi129
  tasks:
    - name: copy /etc
      copy:
        src: "{{ item }}"
        dest: /root/ooo/
      with_fileglob:
        - /data/ppp/*
    - name: combine
      command: echo "msg={{ item.0 }} and {{ item.1 }}"
      with_together:
        - [1,2,3]
        - ['a','b']

 with_fileglob:  将文件下所有的文件作为变量传输,但不是递归。

 with_together: 列表组合形式传输变量

 

本地变量facts

 

 

自定义facts变量

—— 在被控制的服务器上 /etc/ansible/facts.d/  目录下创建文本文件,数据格式为json。控制机上收集被控制机的facts数据时,会读取该目录下的数据,将保存至key为 "ansible_local" 的字典里。

{
    "family": {
        "father": {
            "name": "Zhangsan",
            "age": "39"
        },
        "mother": {
            "name": "Lisi",
            "age": "35"
        }
    }
}

获取相应数据,(文件名my.fact)

- hosts: linux2
  tasks:
  - debug: msg="{{ ansible_local.my.family.mother.age}}"

 

注册变量register 

 

 

 

2、流程控制

- hosts: linux2 linux3
  tasks:
    - name: task1
      command: date1
      ignore_errors: True
    - name: task2
      command: date

ignore_errors:True 或者 yes ,忽略当前task错误,继续往下执行。通常如果不加这个参数,ansible一遇到错误的task就会停止运行

- hosts: linux2
  vars_prompt:
    - name: "username"
      prompt: "what is your name?"
      default: "bhs"
      private: no
      comfirm: yes
    - name: "password"
      prompt: "what is your password?"
      default: "pssss"
      private: yes
      comfirm: yes
  tasks:
    - debug: msg="Welcome {{ username }}" 

 vars_prompt:与控制台交互输入变量, name:定义变量,prompt:交互时显示的文本,private:输入时候是否隐藏文本,default:若不输入回车即是默认值

 

推荐阅读