Access resources from other class

In some case , we may want to access or reference resources from other class, like:
class nodes::test_1{
     file{'/root/test_1':
          ensure=>directory,
     }
}
class nodes::test_2{
     file{'/root/test_1/test_2':
          ensure=>present,
          require=>File['/root/test_1'],
     }
}
As the above vicious codes show, File['/root/test_1/test_2']  want to reference File['/root/test_1'], because the former must be created after the later. But how?
To clarify the reason, we must the kown the following points: 
  1.  In puppet, resources are global once they are declared. Any resource, declared anywhere, can declare a relationship to any other resource, declared anywhere else.
  2. It is important to ensure that resources are declared before references to them are used.
In the same class, all resources can be viewed as they are declared  at the same time. That is, the order they appear dosen't mean the order in which they are declared. However, considering accessing resources in other resouces,  if a resource declared in one class is going to declare a relationship to a resource declared in a different one, then you must make sure that the latter class is parsed before the former one's resource declaration. As long as the latter class is not parametrized,  the easiest and best way to accomplish that is for the former class to 'include' (declare) the latter at the top of its body:
class nodes::test_2{
     include 'nodes::test_1'
     # or class {'nodes::test_1': }
     file{'/root/test_1/test_2':
          require=>File['/root/test_1'],
     }
}
As you can see, r eso urces are global, so you can access File['/root/test_1'] without any prefix , such as Class['nodes::test_1']. And note that  after  including Class['nodes::test_1'] in Class['nodes::test_2'], the resources in the them can be viewed as declared at the same time.  So the below code works fine:
class nodes::test_1{
      file{'/root/test_1':
            ensure=>directory,
     }
      file{'/root/test_1/test_2/test_3':
            ensure=>present,
            require=>File['/root/test_1/test_2'],
     }
}
class nodes::test_2{
      include 'nodes::test_1'
      file{'/root/test_1/test_2':
            ensure=>directory,
            require=>File['/root/test_1'],
      }
      # you can also put the declaration at the tail, the position mean nothing.
      # class {'nodes::test_1': }
} 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值