zhouer 发表于 2018-1-2 22:52:10

《Ansible权威指南》笔记(2)

  四、Inventory配置
  ansible通过Inventory来定义主机和组,使用时通过-i指定读取,默认/etc/ansible/hosts。可以存在多个Inventory,支持动态生成。
  1、定义主机和组
  # vim /etc/ansible/hosts
  192.168.12.22    #可以直接为IP地址
  nfs.magedu.com    #可以是域名
  ntp.magedu.com:2200    #可以:接ssh端口
    #[]内为分组名,下面都是该组组员
  web.magedu.com    #表示1~10所有数字
  db-.magedu.com    #表示a~f所有字母
  2、定义主机变量
  定义的变量可以在playbook中使用,在playbook中设定的同名变量会优先于此处变量。
  other1.example.com    ansible_connection=ssh    ansible_ssh_user=mpdehaan    #选择连接类型和连接用户
  other2.example.com    http_port=8800    #定义http_port端口号8800
  3、定义组变量

  web1.example.com
  web2.example.com
    #组变量,下面定义的变量test组内的所有主机通用
  ntp_server=ntp.example.com
  proxy=proxy.example.com
  4、把一个组作为另一个组的子成员

  web1.example.com

  web2.example.com

  other1.example.com

  apache
  nginx
  #上例中webserver包括web1.example.com、web2.example.com、other1.example.com
  5、其他Inventory参数
  ansible_ssh_host
  将要连接的远程主机名.与你想要设定的主机的别名不同的话,可通过此变量设置.
  ansible_ssh_port
  ssh端口号.如果不是默认的端口号,通过此变量设置.
  ansible_ssh_user
  默认的 ssh 用户名
  ansible_ssh_pass
  ssh 密码(这种方式并不安全,我们强烈建议使用 --ask-pass 或 SSH 密钥)
  ansible_sudo_pass
  sudo 密码(这种方式并不安全,我们强烈建议使用 --ask-sudo-pass)
  ansible_sudo_exe (new in version 1.8)
  sudo 命令路径(适用于1.8及以上版本)
  ansible_connection
  与主机的连接类型.比如:local, ssh 或者 paramiko. Ansible 1.2 以前默认使用 paramiko.1.2 以后默认使用 'smart','smart' 方式会根据是否支持 ControlPersist, 来判断'ssh' 方式是否可行.
  ansible_ssh_private_key_file
  ssh 使用的私钥文件.适用于有多个密钥,而你不想使用 SSH 代理的情况.
  ansible_shell_type
  目标系统的shell类型.默认情况下,命令的执行使用 'sh' 语法,可设置为 'csh' 或 'fish'.
  ansible_python_interpreter
  目标主机的 python 路径.适用于的情况: 系统中有多个 Python, 或者命令路径不是"/usr/bin/python",比如\*BSD, 或者 /usr/bin/python
  不是 2.X 版本的 Python.我们不使用 "/usr/bin/env" 机制,因为这要求远程用户的路径设置正确,且要求 "python" 可执行程序名不可为 python以外的名字(实际有可能名为python26).
  与 ansible_python_interpreter 的工作方式相同,可设定如 ruby 或 perl 的路径....
  6、变量读取的四个位置
  Inventory配置
  Playbook中vars定义的区域
  Roles中vars目录下的文件
  Roles同级目录group_vars和hosts_vars目录下的文件
  #设置变量时尽量沿用同一种方式。
  7、ansible正则
  (1)全量匹配 all与*功能相同,但*需引起来。
  ansible all -m ping
  ansible "*" -m ping
  (2)逻辑或(or)匹配
  多台主机或多个组同时执行
  ansible "web1:web2" -m ping
  (3)逻辑非(!)匹配
  所有在web1组,但不在web2组的主机
  web1:!web2
  (4)逻辑与(&)匹配
  web1和web2中同时存在的主机
  web1:&web2
  (5)模糊匹配
  检查192.168.1.0/24网段所有主机存活状态。
  ansible 192.168.1.* -m ping
  test开头的所有组
  ansible "test*" -m ping
  (6)域切割,同python字符串域切割
  例:

  web1.example.com
  web2.example.com
  web3.example.com
  webservers    #==web1.example.com
  webservers[-1]    #==web3.example.com
  webservers    #第一位到第三位==web1.example.com、web2.example.com、web3.example.com
  webservers    #第二位到最后==web2.example.com、web3.example.com
  (7)正则匹配,"~"开始表示正则匹配
  ansible "~(web|data|test)\.example\.(com|org)" -m ping
页: [1]
查看完整版本: 《Ansible权威指南》笔记(2)