-
Notifications
You must be signed in to change notification settings - Fork 9
Adding nodes to the tree
When you need to add a new node to the tree, you need to know two things:
- where the new node should go
- what its label should be
defvar hosts /files/etc/hosts
The primary means of adding a node is by inserting it:
ins alias before $hosts/1/alias[1]will insert an alias node before all the other aliases for $hosts/1 — that entry will now be $hosts/1/alias[1].
For nodes whose children are numbered sequentially (like the children of $hosts), you need to invent a new label for the new child. You can either try to find out how many children $hosts actually has, and then use the next number in the sequence. A much simpler way to generate a new unique numbered label is to use numbers that start with 0; since Augeas treats labels as strings, 01 and 1 are different, and since it will never use such a label, it's guaranteed to be unique:
ins 01 before $hosts/2 ins 02 after $hosts/01will put two new entries between $hosts/1 and $hosts/2.
The ins command gives you full control over where the new node goes; it's fairly common though that you just want to append a node somewhere in the tree, and writing all those ins commands followed by set to assign a value to the node can become tedious. As a simplification, set will create new nodes if it is asked to set a non-existant node.
The command
set $hosts/03/ipaddr 192.168.0.1will append a new entry 03 to the children of $hosts and create an ipaddr node — that means that you can use set to create several nodes at once.
You can use a special trick to append to a list of nodes that all have the same name, for example to append a new alias to an entry in /etc/hosts:
set $hosts/1/alias[last()+1] myhost.example.comThe predicate [last()+1] forces set to create a new node. Of course, after the node is created, it is now reachable as $hosts/1/alias[last()]. It's important to remember that creating nodes with set can only work if the labels for all the nodes that need to be created are known explicitly. In particular, you can't add a new host entry using something like set $hosts/*[last()+1]/ipaddr 192.168.0.1 — there's no way for Augeas to know what the new node for *[last()+1] should be called.
Sometimes, it is convenient to store a newly created node in a variable. You can use defnode for that:
defnode myalias $hosts/1/alias[last()+1] myhost.example.comThis command will do a set $hosts/1/alias[last()+1] myhost.example.com and store the resulting node in the variable myalias. The defnode command is very useful when you add a node that you need to modify further, e.g. by adding children to it.