IT技术博客大学习 共学习 共进步

Puppet 的类参数传递

三斗室 2014-12-02 23:53:27 浏览 1,344 次

   之前使用 ENC 管理 puppet,尽量保持了输出 yaml 内容的简单,只提供了一个统一的全局参数定义 node 的 role。(题外话,puppetlabs 推荐了另一个通过继承关系实现 role 的示例,见:Designing Puppet - Roles and Profiles。)

   但是 puppet 中有些配置确实修改比较频繁,文件操作不得不说是一件不甚方便的事情,于是重新考虑通过类参数的方式来灵活化某些配置的操作。

修改前

nginx/manifests/init.pp

class nginx {
    include "nginx::${::role}"
}

nginx/manifests/loadbalancer.pp

class nginx::loadbalancer {
    $iplist = ['192.168.0.2:80']
    file { 'nginx.conf':
        content => template('nginx/nginx.conf.erb'),
    }
}

enc nginxhostname

---
classes:
  - nginx
  - base
environment: production
parameters:
  role: loadbalancer

修改后

nginx/manifests/init.pp

class nginx ($iplist = []) {
    class { "nginx::${::role}":
        iplist => $iplist
    }
}

nginx/manifests/loadbalancer.pp

class nginx::loadbalancer ($iplist = []) {
    file { 'nginx.conf':
        content => template('nginx/nginx.conf.erb'),
    }
}

enc nginxhostname

---
classes:
  nginx:
    iplist:
      - 192.168.0.2:80
  base: ~
environment: production
parameters:
  role: loadbalancer

要点

  • 虽然真正需要 $iplist 的是下面的一个子类,但是 ENC 传值是给的父类,所以需要一层层传递下去;

  • ENC 中给类传参,类就要写成哈希形式,否则是数组形式;

  • 有参数的类,在调用的时候无法使用 include 形式的写法,只能用资源调用形式的写法。

建议继续学习

  1. 使用Apache 和Passenger来运行puppetmaster (阅读 8,165)
  2. perl模块Getopt::Std用法及实例-从命令行读取参数模块 (阅读 6,924)
  3. 千万不要把 bool 当成函数参数 (阅读 5,121)
  4. 自动化运维之企业实际案例分析 (阅读 4,623)
  5. puppet使用rsync来同步文件教程 (阅读 4,082)
  6. 关于在函数调用时传递string引用的必要性 (阅读 3,884)
  7. DevOps之Puppet (阅读 3,824)
  8. 如何有效运行puppet cron任务以及如何触发运行puppet (阅读 3,762)
  9. 使用参数化查询防止SQL注入漏洞 (阅读 3,623)
  10. MyISAM和InnoDB的一些记录 (阅读 3,541)