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:
- In puppet, resources are global once they are declared. Any resource, declared anywhere, can declare a relationship to any other resource, declared anywhere else.
- 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': }
}