Backup FortiOS config with Ansible – with RestAPI

In the previous post, I demonstrated how to get the fortigate configuration using Ansible with fortios module. In this post, I will show you how to get the backup config using Ansible with RestAPI via uri module.

Here’s pros and cons compared to fortios module:

pros

  • Not dependent on external module, which may be outdated/not maintained
  • Access right is more developer friendly — it’s based on API token, which can be expired/regenerate on demand.

cons

  • Not fully integrated with Ansible — you need to have a knowledge on FortiOS RestAPI to call them

Differences compared to fortios module generated backup, which might be or might not be important in your use case.

  • uuid, snmp-index are not redacted in the config
  • double quotation is not redacted in the config

1. Create API user and generate API key on Fortigate

Please refer my previous post “Fortigate RestAPI config backup – FortiOS” and generate API key.

2. Configure Ansible inventory and playbook

In your Ansible environment, configure inventory file. In my case, I just use default file in /etc/ansible/hosts for demonstration purpose. API_token is specific to each device, so it is registered as an individual variable.

In playbook, I use uri module to retrieve the config, and use copy to write the content into the local file. In my example below, I backup all the configuration, but you can change scope(vdom) or any other parameter to suite your needs. I’m gathering facts simply because I need to use ansible_date_time variable, you can disable fact gathering and save a few seconds per run if you don’t need these variable appended in your config.

3. Test

Once it’s configured, you can just run the playbook.

Now you should have backup file where you specified in the playbook. In my case, I got two backup config in the same directory as the playbook. And of course it correctly parses the Non-Ascii characters.