Often times, when discussing automation strategies, the topic of Python vs Ansible comes up. However, automation goes beyond a script, task, tool or platform. Don’t fall into the trap of looking at this as a binary solution!.

通常,在讨论自动化策略时,会出现Python vs Ansible的话题。 但是,自动化不仅限于脚本,任务,工具或平台。 不要陷入将其视为二进制解决方案的陷阱!

I see Ansible as a framework to wire things together, to reduce the overhead of mundane tasks. Interconnecting different building blocks to orchestrate an end-to-end automation workflow, which in most cases involves different tools, platforms or resources in a diverse ecosystem across multiple domains in your organization.

我将Ansible视为将事物组合在一起的框架,以减少日常任务的开销。 互连不同的构建基块以协调端到端的自动化工作流,在大多数情况下,它涉及组织中多个域的多样化生态系统中的不同工具,平台或资源。

If you are comfortable running Python to automate parts of your infrastructure, but find yourself in a team of one, automating a single domain, it’s probably time to think on how to make your home-grown tools more accessible to others, in other words how to increase the adoption of your work, which will hopefully become a component of a larger project that automates your end-to-end infrastructure deployment, application lifecycle or service delivery.

如果您可以轻松地运行Python来自动化基础结构的一部分,但是却发现自己是一个由一个域组成的团队,可以自动化一个域,那么现在就该考虑如何使自己开发的工具更易于他人使用了,换句话说,增加您的工作采用率,这有望成为大型项目的组成部分,该项目可以自动化您的端到端基础架构部署,应用程序生命周期或服务交付。

One way to achieve this is by making your Python program easier to use to lower the barrier of entry. Do you provide a GUI? a CLI? an API? Does the user need to know programming? Here is where Ansible comes in! If you made your Python program an Ansible Module, you would then let users call it by using a simple, and easy to read language that enable automation content sharing across an organization.

实现此目的的一种方法是使您的Python程序更易于使用,以降低进入门槛。 您提供GUI吗? CLI? API? 用户是否需要了解编程? 这是Ansible进来的地方! 如果将Python程序设置为Ansible模块,则可以让用户使用一种简单易读的语言来调用它,从而可以在整个组织中实现自动化内容共享。

In this post we are going to describe how you can make your favorite Python library an Ansible module and how that becomes a key component to solve a business need.

在这篇文章中,我们将描述如何使自己喜欢的Python库成为Ansible模块,以及它如何成为解决业务需求的关键组件。

用例 (The use-case)

Let’s imagine a company that is concerned about people outside their premises accessing their internal infrastructure, from servers to networking equipment. They are very paranoid, so they not only set up filters on their Firewalls to restrict external access, but also apply Access Control Lists (ACL’s) on every management interface to prevent SSH access to anyone not in their company allocated IP address space. These configurations are fairly static, so no automation required!

假设有一家公司担心在办公室外的人访问从服务器到网络设备的内部基础结构。 它们非常偏执,因此,它们不仅在防火墙上设置过滤器以限制外部访问,而且还在每个管理接口上应用访问控制列表(ACL),以防止对不在公司分配IP地址空间中的任何人进行SSH访问。 这些配置是相当静态的,因此不需要自动化!

However, in covid-19 times, the scenario has changed. Their now remote users need access to their internal infrastructure. They don’t have a VPN setup, so they decide to allow access to remote IP addresses of their authenticated admin users. However, these IP addresses can change over time. Also, there is no margin for error when you modify a management ACL. A good percentage of Network Engineers have locked themselves out of a device when performing this type of activity (TRUE FACT!).

但是,在covid-19时代,情况发生了变化。 他们现在的远程用户需要访问其内部基础结构。 他们没有VPN设置,因此他们决定允许访问经过身份验证的管理员用户的远程IP地址。 但是,这些IP地址可能会随时间变化。 另外,修改管理ACL时没有错误余地。 当执行此类活动时,有很大比例的网络工程师已将自己锁定在设备之外( TRUE FACT! )。

Given that we need to make sensitive config changes on multiple devices, which include servers, network devices from different vendors, and firewalls, each with their own configuration syntax, this activity could take hours. It will also need to be executed an undetermined number of times to add and remove entries.

鉴于我们需要在多个设备上进行敏感的配置更改,包括服务器,来自不同供应商的网络设备和防火墙,每个设备都有自己的配置语法,因此此活动可能需要几个小时。 还需要执行不确定的次数才能添加和删除条目。

It becomes apparent this process needs to be automated. An engineer suggested they use this cool Python library to translate a generic ACL policy into the specific configuration syntax of each platform, named Capirca.

很明显,此过程需要自动化。 工程师建议他们使用这个很酷的Python库将通用ACL策略转换为每个平台的特定配置语法,称为Capirca

Alright, one less problem to solve! They now need to figure out:

好了,还有一个要解决的问题! 他们现在需要弄清楚:

  1. How to test these changes in a lab/development environment
    如何在实验室/开发环境中测试这些更改
  2. Generate configuration backups before making any changes to production devices
    对生产设备进行任何更改之前,请生成配置备份
  3. Connect to the devices and apply the configuration changes
    连接到设备并应用配置更改
  4. Have a rollback strategy ready to go in case something fails
    准备好回滚策略,以防万一失败
  5. Commit the changes and notify users and other systems
    提交更改并通知用户和其他系统

Because Ansible can help us with all these, we will make Capirca an Ansible module to run this process as a fully automated workflow.

由于Ansible可以为我们提供所有帮助,因此我们将Capirca 设为Ansible模块,以将其作为全自动工作流程运行。

创建作为集合一部分分发的模块 (Creating a Module distributed as part of a Collection)

According to Ansible module development, an Ansible Module is a reusable, standalone script that Ansible runs on your behalf, either locally or remotely. Modules interact with your local machine, an API, or a remote system to perform specific tasks like changing a database password or spinning up a cloud instance. Each module can be used by the Ansible API, or by the ansible or ansible-playbook programs. A module provides a defined interface, accepting arguments and returning information to Ansible by printing a JSON string to stdout before exiting.

根据Ansible模块开发 ,Ansible Module 是可重用的独立脚本,Ansible可以代表您在本地或远程运行。 模块与本地计算机,API或远程系统交互以执行特定任务,例如更改数据库密码或启动云实例。 每个模块可由Ansible API或ansible或ansible-playbook程序使用。 模块提供了一个已定义的接口,通过在退出前将JSON字符串打印到stdout来接受参数并将信息返回给Ansible

We store this reusable, standalone script that Ansible runs on your behalf in the “magic” directory (plugins/modules), as described in Adding modules and plugins locally. But, where does this directory live? It actually depends on how you distribute this content. There are different options as listed in Adding a module locally, but in this case we are going to take advantage of Collections, a new standard of distributing, maintaining and consuming automation as described in Getting Started With Ansible Content Collections. In order to initialize a collection, we run ansible-galaxy collection init <namespace.name> to create a skeleton directory structure.

我们将Ansible代表您运行的可重复使用的独立脚本存储在“魔术”目录( plugins/modules )中,如在本地添加模块和插件中所述 。 但是,该目录在哪里? 实际上,这取决于您如何分发此内容。 本地添加模块中列出了不同的选项,但是在这种情况下,我们将利用Collections的优势,Collections 是分发,维护和使用自动化新标准,Ansible Content Collections入门中所述。 为了初始化集合,我们运行ansible-galaxy collection init <namespace.name>来创建框架目录结构。

ansible-galaxy collection init nleiva.capirca_acl- Collection nleiva.capirca_acl was created successfully

Resulting in:

导致:

tree nleiva/capirca_aclnleiva/capirca_acl├── docs├── galaxy.yml├── plugins│   └── README.md├── README.md└── roles

In the plugins folder, we create a new one named modules. We put the code of our first module, named translate in there.

plugins文件夹中,我们创建一个新的名为modules 。 我们在其中放置了第一个模块的代码,名为translate

tree nleiva/capirca_acl...├── plugins│   └── modules│       └── translate.py

The initial code comes straight from Starting a new module. Remember: “Good developers copy; great developers paste

初始代码直接来自于启动新模块 。 记住:“ 好的开发人员应该复制; 伟大的开发人员粘贴

演示地址

We are ready to implement the logic of our module, which for simplicity will only parse the inputs and pass that data to Capirca to let it do its magic.

我们准备好实现模块的逻辑,为简单起见,该逻辑仅会解析输入并将数据传递给Capirca,以使其发挥作用。

编写模块 (Writing the Module)

In their Wiki page, they describe Capirca as a tool designed to utilize common definitions of networks, services and high-level policy files to facilitate the development and manipulation of network access control lists (ACLs) for various platforms.

他们在其Wiki页面中将Capirca描述为一种工具,旨在利用网络,服务和高级策略文件的通用定义来促进针对各种平台的网络访问控制列表(ACL)的开发和操作。

The name, “capirca”, was intended to be “caprica” from BattleStar galactica (the “new world”). They registered the misspelling, then later noticed the error, but the correct spelling was already taken [SOURCE].

名字“ capirca”原意是太空堡垒卡拉狄加(“新世界”)的“ caprica”。 他们注册了拼写错误,然后发现错误,但是已经采用了正确的拼写 [ SOURCE ]。

Capirca requires a naming definition for network or services, and a policy file to generate ACL filters for different target platforms. These are inputs we need to provide to the library. We will instruct our Ansible module to take these as arguments, so we edit module_args in the initial code we copied to looks like this:

Capirca需要网络或服务的命名定义,以及一个策略文件才能为不同的目标平台生成ACL筛选器。 这些是我们需要提供给库的输入。 我们将指示Ansible模块将其作为参数,因此我们在复制到的初始代码中编辑module_args如下所示:

module_args = dict(platform        = dict(type='str', required=True, choices=['juniper', 'cisco', 'ciscoasa', 'ciscoxr', 'brocade', \'arista', 'aruba', 'ipset', 'iptables', 'nsxv', \'packetfilter', 'pcap', 'speedway', 'srx', 'srxlo', \'windows_advfirewall', 'nftables', 'gce', 'paloalto', 'cloudarmor' \'fail me']),filter_options  = dict(type='list', required=False, default=['Default-ACL-Name']),comment         = dict(type='str', required=False, default="Default Comment"),def_folder      = dict(type='str', required=False, default="integration/targets/translate/files/def"),pol_file        = dict(type='str', required=False, default="integration/targets/translate/files/policies/terms.pol"),
)

Where:

哪里:

  • platform: Has to be one of the platforms from the extensive list of options Capirca supports, otherwise the module will complain. See platform.

    platform :必须是Capirca支持的广泛选项列表中的一种 ,否则该模块将报错。 见平台 。

  • filter_options: Additional arguments, which are optional in many cases. For example, the ACL filter name. Full details in filter_options.

    filter_options :附加参数,在许多情况下是可选的。 例如,ACL过滤器名称。 filter_options中的完整详细信息。

  • comment: An optional comment.

    comment :可选注释。

  • def_folder: Folder where the naming definitions are stored. Each file must end in either a ‘.net’ or ‘.svc’ extension, specifying a network or services definitions files. We’ll discuss an example in a few paragraphs.

    def_folder :存储命名定义的文件夹。 每个文件都必须以“ .net”或“ .svc”扩展名结尾,并指定网络或服务定义文件 。 我们将在几段中讨论一个示例。

  • pol_file: Policy file that describe the Filter terms. We’ll discuss an example in a few paragraphs.

    pol_file :描述过滤条件的策略文件。 我们将在几段中讨论一个示例。

Next, we pass the value for these arguments, which we specify in the Playbook, to Ansible. No change is required to the initial code. A dictionary result is also defined in the original code, which we will leave as is for simplicity, and leverage one of its elements (message) later on.

接下来,我们将在Playbook中指定的这些参数的值传递给Ansible。 不需要更改初始代码。 字典result也在原始代码中定义,为简单起见,我们将其保留下来,并稍后使用其元素之一( message )。

module = AnsibleModule(argument_spec=module_args,supports_check_mode=True
)

Now that we have the user inputs collected during execution, we can call our Python library. In this example, we defined a separate function (get_acl) to handle this portion. Notice we pass the parsed module arguments to this function, which at this point you have access to through module.params.

现在我们已经在执行期间收集了用户输入,现在可以调用我们的Python库了。 在此示例中,我们定义了一个单独的函数( get_acl )处理这一部分。 注意,我们将已解析的模块参数传递给此函数,此时您可以通过module.params访问该module.params

acl = get_acl(module.params)

An oversimplified version of this function (get_acl) would look like this:

此函数的简化版本( get_acl )如下所示:

from capirca.lib import cisco, juniperdef get_acl(inputs):...header = header_template.safe_substitute(inputs)defs = naming.Naming(inputs['def_folder'])terms = open(inputs['pol_file']).read()pol = policy.ParsePolicy(header + '\n' + terms, defs, optimize=True)...if inputs['platform'] == 'juniper':result = juniper.Juniper(pol, EXP_INFO)elif inputs['platform'] == 'cisco':result = cisco.Cisco(pol, EXP_INFO)...return str(result)

In a nutshell, we will generate a templated header for the policy, read the input files with the naming definitions in the folder (defs), and the policy terms (terms). Then call Capirca to generate a filter ACL for a given platform (juniper and cisco included as examples in this code snippet).

简而言之,我们将为策略生成模板化的header ,读取文件夹中的命名定义( defs )和策略术语( terms )的输入文件。 然后,调用Capirca为给定平台生成过滤器ACL(此代码段中包含junipercisco作为示例)。

Finally, we store the value returned by this function on the result dictionary, message field, and pass it to AnsibleModule.exit_json().

最后,我们将此函数返回的值存储在result字典, message字段中,并将其传递给AnsibleModule.exit_json()

result['message'] = acl
...
module.exit_json(**result)

That’s it! If you want to see the full code, take a look at capirca_acl. Some things might change as we iterate over this module.

而已! 如果要查看完整的代码,请查看capirca_acl 。 当我们迭代此模块时,某些事情可能会更改。

使用模块 (Using the Module)

Let’s go through a simple example to update a SSH Filter (there is another example documented in translate docs). Our Playbook consists of a single Play with two Tasks. The first one run the translate module we just described, and then we use the debug module to print out the result.

让我们来看一个简单的示例,以更新SSH过滤器(在翻译文档中记录了另一个示例)。 我们的剧本由一个带有两个任务的剧本组成。 第一个运行我们刚刚描述的translate模块,然后我们使用debug模块打印出结果。

---
- name: Generate SSH ACL Filter for a given OS.hosts: localhostgather_facts: notasks:- name: Run Capirca Modulenleiva.capirca_acl.translate:platform: 'ciscoxr'filter_options: 'My-SSH-Filter'def_folder: "sample"pol_file: "sample/terms.pol"register: testout- name: Display the filterdebug:msg: "{{ testout.message }}"

In this case we choose Cisco IOS XR (ciscoxr) as the target platform to generate an ACL filter for this specific Operating System. We store our naming definitions in a folder (def_folder) named sample. There are two files in there, one that defines our networks (networks.net):

在这种情况下,我们选择Cisco IOS XR( ciscoxr )作为目标platform ,以为此特定操作系统生成ACL过滤器。 我们将命名定义存储在名为sample的文件夹( def_folder )中。 那里有两个文件,其中一个定义了我们的网络( networks.net ):

RFC1918  = 192.168.0.0/16172.16.0.0/1210.0.0.0/8OFFICE   = 192.0.2.0/24   # company IP block-1198.51.100.0   # company IP block-2INTERNAL = RFC1918OFFICEREMOTE   = 203.0.113.100/32203.0.113.200/32

And another one that defines our services (services.svc):

另一个定义我们的服务的服务( services.svc ):

SSH = 22/tcp

These files are fairly static, you would normally re-use them every time and update when required. We will most likely make these YAML compatible in a future release of the module.

这些文件是相当静态的,通常您每次都会重复使用它们,并在需要时进行更新。 我们很可能在将来的模块版本中使这些YAML兼容。

However, the most important part is the actual policy (pol_file) we want to generate. These are the terms, which we describe in a generic language, to be translated into the syntax of the target platform. In this example we use:

但是,最重要的部分是我们要生成的实际策略( pol_file )。 这些是我们用通用语言描述的术语,可以转换为目标platform的语法。 在此示例中,我们使用:

term allow-intra-office {comment:: "Spoofs are already blocked at the borders"source-address:: INTERNALdestination-address:: INTERNALdestination-port:: SSHprotocol:: tcpaction:: accept
}term allow-remote {source-address:: REMOTEdestination-port:: SSHprotocol:: tcpaction:: accept
}term implicit-default-deny {comment:: "Deny everything else"action:: deny
}

The resulting ACL filter for Cisco IOS XR (ciscoxr) will be:

Cisco IOS XR( ciscoxr )的最终ACL过滤器将是:

ipv4 access-list My-SSH-Filterremark allow-intra-office remark Spoofs are already blocked at the borders permit tcp 10.0.0.0 0.255.255.255 10.0.0.0 0.255.255.255 eq 22 permit tcp 10.0.0.0 0.255.255.255 172.16.0.0 0.15.255.255 eq 22 permit tcp 10.0.0.0 0.255.255.255 192.0.2.0 0.0.0.255 eq 22 permit tcp 10.0.0.0 0.255.255.255 192.168.0.0 0.0.255.255 eq 22 permit tcp 10.0.0.0 0.255.255.255 host 198.51.100.0 eq 22 permit tcp 172.16.0.0 0.15.255.255 10.0.0.0 0.255.255.255 eq 22 permit tcp 172.16.0.0 0.15.255.255 172.16.0.0 0.15.255.255 eq 22 permit tcp 172.16.0.0 0.15.255.255 192.0.2.0 0.0.0.255 eq 22 permit tcp 172.16.0.0 0.15.255.255 192.168.0.0 0.0.255.255 eq 22 permit tcp 172.16.0.0 0.15.255.255 host 198.51.100.0 eq 22 permit tcp 192.0.2.0 0.0.0.255 10.0.0.0 0.255.255.255 eq 22 permit tcp 192.0.2.0 0.0.0.255 172.16.0.0 0.15.255.255 eq 22 permit tcp 192.0.2.0 0.0.0.255 192.0.2.0 0.0.0.255 eq 22 permit tcp 192.0.2.0 0.0.0.255 192.168.0.0 0.0.255.255 eq 22 permit tcp 192.0.2.0 0.0.0.255 host 198.51.100.0 eq 22 permit tcp 192.168.0.0 0.0.255.255 10.0.0.0 0.255.255.255 eq 22 permit tcp 192.168.0.0 0.0.255.255 172.16.0.0 0.15.255.255 eq 22 permit tcp 192.168.0.0 0.0.255.255 192.0.2.0 0.0.0.255 eq 22 permit tcp 192.168.0.0 0.0.255.255 192.168.0.0 0.0.255.255 eq 22 permit tcp 192.168.0.0 0.0.255.255 host 198.51.100.0 eq 22 permit tcp host 198.51.100.0 10.0.0.0 0.255.255.255 eq 22 permit tcp host 198.51.100.0 172.16.0.0 0.15.255.255 eq 22 permit tcp host 198.51.100.0 192.0.2.0 0.0.0.255 eq 22 permit tcp host 198.51.100.0 192.168.0.0 0.0.255.255 eq 22 permit tcp host 198.51.100.0 host 198.51.100.0 eq 22remark allow-remote permit tcp host 203.0.113.100 any eq 22 permit tcp host 203.0.113.200 any eq 22remark implicit-default-deny remark Deny everything else deny ipv4 any anyexit

However, the beauty of Capirca is that if we only changed the target platform to juniper in this example, we would then get this result instead:

然而,美容Capirca是,如果我们只改变了目标platform ,以juniper在这个例子中,我们便得到这样的结果,而不是:

firewall {    family inet {        replace:        filter My-SSH-Filter {            interface-specific;            term allow-intra-office {                from {                    source-address {                        10.0.0.0/8;                        172.16.0.0/12;                        192.0.2.0/24;                        192.168.0.0/16;                        198.51.100.0/32;                    }                    destination-address {                        10.0.0.0/8;                        172.16.0.0/12;                        192.0.2.0/24;                        192.168.0.0/16;                        198.51.100.0/32;                    }                    protocol tcp;                    destination-port 22;                }                then accept;            }            term allow-remote {                from {                    source-address {                        203.0.113.100/32;                        203.0.113.200/32;                    }                    protocol tcp;                    destination-port 22;                }                then accept;            }            term implicit-default-deny {                then {                    discard;                }            }        }    }}

Or maybe if we chose iptables with something like:

或者,如果我们选择类似以下内容的iptables

- name: Run Capirca Modulenleiva.capirca_acl.translate:platform: 'iptables'filter_options:- 'INPUT'- 'ACCEPT'def_folder: "sample"pol_file: "sample/terms.pol"

To get:

要得到:

-P INPUT ACCEPT-N I_allow-intra-office-A INPUT -j I_allow-intra-office-A I_allow-intra-office -m comment --comment "Spoofs are already blocked at the borders"-A I_allow-intra-office -p tcp --dport 22 -s 10.0.0.0/8 -d 10.0.0.0/8 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT ...-A I_allow-intra-office -p tcp --dport 22 -s 198.51.100.0/32 -d 10.0.0.0/8 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT-A I_allow-intra-office -p tcp --dport 22 -s 198.51.100.0/32 -d 172.16.0.0/12 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT-A I_allow-intra-office -p tcp --dport 22 -s 198.51.100.0/32 -d 192.0.2.0/24 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT-A I_allow-intra-office -p tcp --dport 22 -s 198.51.100.0/32 -d 192.168.0.0/16 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT-A I_allow-intra-office -p tcp --dport 22 -s 198.51.100.0/32 -d 198.51.100.0/32 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT-N I_allow-remote-A INPUT -j I_allow-remote-A I_allow-remote -p tcp --dport 22 -s 203.0.113.100/32 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT-A I_allow-remote -p tcp --dport 22 -s 203.0.113.200/32 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT-N I_implicit-default-deny-A INPUT -j I_implicit-default-deny-A I_implicit-default-deny -m comment --comment "Deny everything else"-A I_implicit-default-deny -p all -j DROP

How cool is that!?

多么酷啊!?

最终工作流程 (Final workflow)

Let’s now put all the pieces together. We will run this against two separate group of hosts, as defined in our inventory; Lab and Prod. The first one is small number of devices that represent one of every platform running in production, used for testing purposes in the lab, so changes can be exercised in a safe environment before jumping into production.

现在让我们将所有内容放在一起。 我们将针对inventory定义的两个独立的主机组运行此命令; LabProd 。 第一个是代表生产环境中运行的每个平台之一的少量设备,用于实验室中的测试目的,因此可以在进入生产环境之前在安全的环境中进行更改。

The fist step will be to Generate an ACL Filter as we run through the different target hosts with the module we just built (Generate ACL Filters). We dynamically determine the target platform by mapping the data Ansible gets from the systems when gather_facts is enabled. This mapping looks something like this:

第一步将是生成ACL过滤器,这是因为我们使用刚刚构建的模块在不同的目标主机上运行( 生成ACL过滤器 )。 我们动态地确定目标platform通过映射时Ansible从系统中获取数据gather_facts启用。 该映射如下所示:

vars:map:ios: "cisco"junos: "juniper"CentOS: "iptables"RedHat: "iptables"tasks:
- name: Set platform for Networking devicesset_fact: platform: "{{ map[ansible_net_system] }}"when: ansible_net_system is defined- name: Set platform for Linux systemsset_fact: platform: "{{ map[ansible_distribution] }}"when: ansible_distribution is defined

Now, before we apply the ACL Filter produced, we backup the current configuration and also prepare a last resort plan in case something goes wrong when the new config is applied, which might prevent us from accessing the device to revert these changes (Backup and Rollback scheduling). If the target was a JunOS device, then this would be as simple as setting the confirm argument in the junos_config module when making changes to configure a time out value in minutes for the commit to be confirmed before it is automatically rolled back. On a Cisco IOS device I can only think of a very disruptive reload in without saving the running to start-up config.

现在,在应用生成的ACL过滤器之前,我们将备份当前配置,并准备万不得已的计划,以防万一在应用新配置时出现问题,这可能会阻止我们访问设备以还原这些更改(“ 备份和回滚”)安排 )。 如果目标是JUNOS设备,那么这将是简单的设置confirm参数中junos_config更改在几分钟配置超时值时提交之后系统会自动回滚到确认模块。 在Cisco IOS设备上,我只能想到破坏性很大的reload in而无需保存runningstart-up配置。

If we are modifying iptables on a Linux machine, maybe we could leverage the module at to revert back to the initial config.

如果我们要在Linux机器上修改iptables ,也许我们可以利用at模块来恢复到初始配置。

tasks:
- name: Save current iptables rulesshell: iptables-save > /tmp/iptables-rules-backup.txt- name: Schedule iptables-restore to execute in 20 minutes as rootat:command: iptables-restore < /tmp/iptables-rules-backup.txtcount: 20units: minutes

With these safeguards in place, we can proceed to apply the configuration changes (Apply Filters). Our workflow so far looks like this:

有了这些保护措施,我们就可以继续应用配置更改( Apply Filters )。 到目前为止,我们的工作流程如下:

In case we can’t apply the changes, we cancel any scheduled rollback. Otherwise we continue with the execution of our workflow. Before we can call it a day, we need to run some tests to make sure everything is running as expected.

如果我们无法应用更改,我们将取消所有计划的回滚。 否则,我们将继续执行工作流程。 在一天结束之前,我们需要运行一些测试以确保一切都按预期运行。

There are different strategies to verify things look good. The more you test, the better. In this case, we will check that a set of test hosts can still access the platforms we are configuring. We leverage the delegate_to module tell Ansible to execute this task from a different host (test_host) that will validate it can still set up a SSH connection to the device whose configuration we just changed. ansible_host is the ‘current’ host being iterated over in the play, see Special Variables.

有多种策略可以验证事物的外观。 测试越多越好。 在这种情况下,我们将检查一组测试主机是否仍可以访问我们正在配置的平台。 我们利用delegate_to模块delegate_to Ansible从另一台主机( test_host )执行此任务,该主机将验证它仍可以建立与刚刚更改其配置的设备的SSH连接。 ansible_host正在播放的“当前”主机 ,请参见特殊变量 。

- name: Wait until we can SSH to the target from the Test Hostwait_for:host: "{{ ansible_host }}"port: 22state: startedtimeout: 30delegate_to: "{{ test_host }}"

If the test pass, then we are in good shape to save our changes (Commit Changes), notify users via email, chat or any other mechanism, as well as updating any system like your CMDB (Notify users/systems). Let’s not forget of cancelling any planned rollback (Cancel Rollback). Of course, if the tests didn’t pass, we want to return to the previous state as soon as possible to minimize any negative impact changes might have caused (Execute Rollback).

如果测试通过,则我们处于保存状态( 提交更改 ),通过电子邮件,聊天或任何其他机制通知用户以及更新任何系统(如CMDB)的状态( 通知用户/系统 )。 我们不要忘记取消任何计划的回滚( Cancel Rollback )。 当然,如果测试没有通过,我们希望尽快返回到先前的状态,以最大程度地减少可能造成的负面影响( 执行回滚 )。

结论 (Conclusion)

Automation is not a tool nor a feature you add to your project. It’s an ongoing practice that requires discipline to glue all the pieces of the puzzle together. Along the same lines, is not about Python or Ansible, they are actually better together.

自动化既不是您添加到项目中的工具也不是功能。 这是一项持续不断的实践,需要纪律来将难题的所有部分粘合在一起。 同样,不是Python还是Ansible,它们在一起实际上更好。

We didn’t dive into how you upload your Collection/Module to Ansible Galaxy to share your work with the community, do versioning, or test your modules with Travis CI or Github Actions. This will be part of a separate blog post, stay tuned! If you can’t wait, check out capirca_acl repo to get an idea.

我们没有深入探讨如何将集合/模块上载到Ansible Galaxy以与社区共享您的工作,进行版本控制或使用Travis CI或Github Actions测试模块。 这将是另一篇博客文章的一部分,请继续关注! 如果您迫不及待,请查看capirca_acl repo以获得想法。

翻译自: https://medium.com/swlh/python-and-ansible-to-automate-a-network-security-workflow-28b9a44660c6

http://www.taodudu.cc/news/show-5762608.html

相关文章:

  • 没有一种工作是不委屈的
  • java随机生成中文姓名
  • 二维码生成工具:zxing
  • 二维码生成工具源码(C#版)
  • Java:二维码生成工具类
  • 勒索文件恢复_我将如何从勒索软件中恢复
  • iframe如何发送请求_【第1803期】如何在 Web 上构建一个插件系统
  • ai人工智能的本质和未来_是人工智能手中网络安全的未来AI 3
  • 【HTTP- TCP- IP】【前端网安】总结篇
  • 底层开发崇拜_我应该何时加入品牌崇拜
  • 2019年如何撸一个Cloud Studio插件?
  • java后台两个表关联查询_Java Criteria表关联查询(两个表未定义关联关系)
  • 大前端–Vue前端体系、前后端分离
  • Figma: 如何在 Web 上构建一个插件系统
  • 五一回宜兴记 -- 植物志_拔剑-浆糊的传说_新浪博客
  • 思科ASA防火墙中存在多个漏洞,可被用于供应链攻击
  • 2019年写一个Cloud Studio插件吧
  • React不是一个好主意(React Is A Terrible Idea(翻译自Dan Yoder))
  • Vue中毒第二天
  • OpenCV 安装和配置 - Mac OS 环境
  • python环境下opencv安装与一些坑
  • opencv的安装及使用
  • JAVA毕业设计工资管理系统计算机源码+lw文档+系统+调试部署+数据库
  • 基于JAVA田径运动会管理系统计算机毕业设计源码+系统+mysql数据库+lw文档+部署
  • 计算机毕业设计ssm基于SSM框架的药店管理系统ghao1系统+程序+源码+lw+远程部署
  • java计算机毕业设计高校贫困生信息管理系统MyBatis+系统+LW文档+源码+调试部署
  • 基于Java毕业设计智慧养老院管理系统源码+系统+mysql+lw文档+部署软件
  • 中国啤酒10强“燕京漓泉”引入法大大电子合同,加速数字化升级
  • 电子信息/通信保研/考研复试经验贴,保姆级经验之时间安排篇
  • 燕京啤酒携手法大大,电子合同助力异地高效签约

python和ansible自动化网络安全工作流程相关推荐

  1. python工作技巧_4个基本的 Python 技巧让你的工作流程自动化

    说实话,即使是简单的任务也需要大量的时间和大量的依赖管理,这可能会变得非常复杂. 尽管如此,让一些简单的任务自动化是非常值得的,即使它更多的是为了好玩. 对于那些已经是 Python 爱好者的人来说, ...

  2. python django ansible自动化运维管理平台源码收藏

    yianjiajia / django_web_ansible GitHub - yianjiajia/django_web_ansible: 自动化运维管理系统 纳兰秋水 / AnsibleUI A ...

  3. 使用Tand自动化您的机器学习工作流程

    This is a post on TanD, a no-code framework to automate the machine learning workflow. Its purpose i ...

  4. python实现erp自动化_用轻流,实现ERP的自动化工作流程

    ERP,Enterprise Resource Planning,即企业资源计划.从字面上来理解,ERP就是指建立在信息技术基础上,用系统化的管理思想,为企业决策层及员工提供决策运行手段的管理方法.它 ...

  5. 大数据分析工作流程是什么

    大数据分析工作流程是什么?高效的工作流应该做到这一点-流程化-将我们从项目的每个阶段无缝地引导到下一个阶段,优化任务管理,并最终指导我们从业务问题到解决方案再到价值.随着数据泛滥的持续减少,企业正在淹 ...

  6. 远程会计人员如何通过数字工作流程完成工作

    远程会计人员如何通过数字工作流程完成工作 当大多数员工居家办公时,会计部门通常会敏锐地感受到挑战.如果您的组织开始数字化转型或只迈出了第一步,您会发文档管理系统现在已成为必备品,而不是可有可无的.现在 ...

  7. python做流程管理平台_[译] Airflow: 一个工作流程管理平台

    Airflow: 一个工作流程管理平台 Airbnb 是一个快速增长的.数据启示型的公司.我们的数据团队和数据量都在快速地增长,同时我们所面临的挑战的复杂性也在同步增长.我们正在扩张的数据工程师.数据 ...

  8. python爬虫之Scrapy框架的post请求和核心组件的工作 流程

    python爬虫之Scrapy框架的post请求和核心组件的工作 流程 一 Scrapy的post请求的实现 在爬虫文件中的爬虫类继承了Spider父类中的start_urls,该方法就可以对star ...

  9. Python+Django+Ansible Playbook自动化运维项目实战(二)

    Python+Django+Ansible Playbook自动化运维项目实战 一.资产管理,自动化发现.扫描 1.服务端资产探测.扫描发现 1)资产管理的资产: 2)抽象与约定: 2.探测协议和模块 ...

最新文章

  1. scss里的继承操作符@extend
  2. cuda-convnet在Ubuntu12.04+CUDA5.5下的配置
  3. word2vec相关资料
  4. linux重定向命令语法,linux重定向命令应用及语法
  5. VS2005中ajax安装指南
  6. 某互联网公司数据分析岗 SQL 笔试题
  7. photoshop cs6(mac版)安装教程
  8. win7磁盘清理_电脑磁盘已满怎么清理?磁盘清理的注意事项有哪些?
  9. PVE使用USB蓝牙直通配置
  10. tan x x的matlab求解,matlab画x=tan(x)
  11. win32模拟鼠标动作
  12. vue引入jquery的方法
  13. 三、全国计算机三级数据库考试——操作题(1—5套)
  14. 孙陶然:企业的愿景、使命和价值观
  15. 洛谷P1562 还是N皇后(DFS+状态压缩+位运算)
  16. python全栈指的是什么_python全栈指的是什么
  17. 阿里巴巴的卫哲现在在做的事
  18. 《世界上最远的距离》(泰戈尔)
  19. 商业级4G代理搭建指南【搭建篇之Docker版】
  20. 揭秘淘宝倒卖QQ产业,他们上万QQ号都是哪来的?

热门文章

  1. sqlserver 交集 并集 差集
  2. 【bzoj4715】囚人的旋律 dp
  3. jmetal解决超多目标问题,并且利用igd值进行评价
  4. 第五话·数据结构必看之·栈 真的这么简单?
  5. 国家级森林公园——昆嵛山之秋
  6. 老师教了我们三年的PS 全部在这里了,都是精华!
  7. 三角灯箱 css_不错的jQuery CSS3灯箱图库
  8. PCB板布线中地线和电源线的布线规则
  9. Java动态代理和Cglib动态代理最强王者阵容
  10. 新零售门店 SD-WAN 应用场景和组网解决方案