-
Notifications
You must be signed in to change notification settings - Fork 201
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
examples: Add an example of how to use Netplan's CFFI bindings
- Loading branch information
Showing
1 changed file
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,58 @@ | ||
#!/usr/bin/env python3 | ||
|
||
# Copyright (C) 2023 Canonical, Ltd. | ||
# Author: Lukas Märdian <[email protected]> | ||
# | ||
# This program is free software; you can redistribute it and/or modify | ||
# it under the terms of the GNU General Public License as published by | ||
# the Free Software Foundation; version 3. | ||
# | ||
# This program is distributed in the hope that it will be useful, | ||
# but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
# GNU General Public License for more details. | ||
# | ||
# You should have received a copy of the GNU General Public License | ||
# along with this program. If not, see <http://www.gnu.org/licenses/>. | ||
|
||
import io | ||
import tempfile | ||
from netplan import Parser, State, NetplanException, _create_yaml_patch | ||
FALLBACK_FILENAME = '70-netplan-set.yaml' | ||
|
||
if __name__ == '__main__': | ||
yaml_path = ['network', 'ethernets', 'eth99', 'dhcp4'] | ||
value = 'true' | ||
|
||
parser = Parser() | ||
with tempfile.TemporaryFile() as tmp: | ||
_create_yaml_patch(yaml_path, value, tmp) | ||
tmp.flush() | ||
|
||
# Parse the full, existing YAML config hierarchy | ||
parser.load_yaml_hierarchy(rootdir='/') | ||
|
||
# Load YAML patch, containing our new settings | ||
tmp.seek(0, io.SEEK_SET) | ||
parser.load_yaml(tmp) | ||
|
||
# Validate the final parser state | ||
state = State() | ||
try: | ||
# validation of current state + new settings | ||
state.import_parser_results(parser) | ||
except NetplanParserException as e: | ||
print('Error in', e.filename, 'Row/Col', e.line, e.column, '->', e.message) | ||
except NetplanException as e: | ||
print('Error:', e.message) | ||
|
||
# Walk through all NetdefIDs in the state and print their backend | ||
# renderer, to demonstrate working with NetDefinitionIterator & | ||
# NetDefinition | ||
for netdef_id, netdef in state.netdefs.items(): | ||
print('Netdef', netdef_id, 'is managed by:', netdef.backend) | ||
|
||
# Write the new data from the YAML patch to disk, updating an | ||
# existing Netdef, if file already exists, or FALLBACK_FILENAME | ||
state._update_yaml_hierarchy(FALLBACK_FILENAME, rootdir='/') | ||
|