Leveraging Terraform for Enhanced Asset Security with Mondoo - Part 1: Resources


Bicycle

In an era where information security management is more crucial than ever, organizations are seeking innovative solutions to safeguard their digital assets effectively. Enter Mondoo, a dynamic platform designed to enhance security and compliance across various infrastructures. By integrating with Terraform, Mondoo leverages the power of infrastructure as code to automate and streamline the deployment of secure and compliant environments. Our partnership with Mondoo has not only expanded our and Mondoo's capabilities but also provided a more robust framework for managing infrastructure security, making it easier for companies to adapt to fast-changing security landscapes. Together, Mondoo and Terraform are setting new standards in the proactive management of information security. This blog-series will focus on recent updates resulting from our partnership. This blogpost will be about all developments for the Terraform provider resources.

A Few Words on Mondoo

Mondoo is a comprehensive security and compliance platform that integrates with various infrastructure components like cloud providers, SaaS platforms and even workstations. It offers continuous security assessments and compliance checks, helping ensure that IT infrastructures are secure and adhere to best practices, as well as compliance guidelines. Mondoo is particularly noted for its policy-as-code capabilities, which allow for automated security enforcement throughout development and operational processes.

For a more detailed explanation and insights into how Mondoo operates, you can refer to the full article about Mondoo on our blog here.

In our partnership, we were able to actively participate in the further development of Mondoo, in particular the Mondoo Terraform provider, in order to be able to provide a bigger variety of Terraform resources for easy and automated integration of IT-assets.

Discovering Mondoo's Integration Types

As of June 2024, the Mondoo Terraform provider offers a variety of resource and integration types for asset integration, along with four valuable data sources, and continues to expand its capabilities. The resources include management options for policies, assets, and integrations, enabling us to implement comprehensive security and compliance checks seamlessly within your infrastructure managed by Terraform.

Google Cloud Platform Integration

The Mondoo GCP integration allows continuous scanning of Google Cloud Platform (GCP) resources to identify vulnerabilities and misconfigurations. This integration is established by configuring the Terraform file to include Mondoo's GCP integration resources. It requires specifying GCP credentials and the scope of resources to be monitored.

Be sure to set up the necessary prerequisites for a successful integration, such as configuring GCP IAM roles and permissions to allow Mondoo access for scanning. Detailed setup instructions and requirements can be found in the Mondoo documentation here.

Google Cloud Platform Resource

Oracle Cloud Infrastructure Integration

The Mondoo OCI (Oracle Cloud Infrastructure) integration enables continuous scanning of OCI resources to detect security vulnerabilities and misconfigurations. To set up this integration, you must configure your Terraform file with the necessary details such as OCI credentials and the specific resources or compartments to be monitored.

For successful integration of Mondoo with Oracle Cloud Infrastructure (OCI), ensure that the necessary OCI policies and roles are configured. This preparation enables Mondoo to perform comprehensive security scans. Detailed instructions on configuring OCI access for Mondoo are available in the Mondoo documentation here.

Oracle Cloud Infrastructure Resource

Continuing with the introduction of new resources, together with the Mondoo Team we expanded the Mondoo Terraform provider significantly since April 2024, offering a bigger variety of integration types and resources designed to bolster security and compliance across different platforms with an automated process. Let’s explore them together!

Microsoft Azure Integration

Continuing with our exploration of Mondoo’s integration with Terraform, a significant addition as of version 0.5 is the Microsoft Azure integration. This enables the Mondoo Terraform provider to continuously scan Microsoft Azure subscriptions and their resources, identifying misconfigurations and vulnerabilities. The integration is designed to enhance security and compliance by providing insights into the Azure environment directly from the Mondoo platform.

This integration type facilitates seamless security checks across Azure resources, ensuring that they conform to your security policies and compliance requirements. Users can easily set up the Azure integration via the Terraform configuration, specifying necessary parameters such as the Azure subscription ID and credentials.

Be sure to meet the prerequisites for integrating Mondoo with Microsoft Azure. This involves configuring Azure to allow Mondoo to scan your subscriptions for security and compliance issues. Essential steps include setting up the appropriate Azure Active Directory (AD) permissions, creating a custom role with necessary access rights, and generating a service principal for authentication.

Microsoft Azure Resource

Domain Integration

Another exciting feature of the Mondoo Terraform provider as of version 0.5 is the integration with domains or websites. This integration type allows for the scanning of domain configurations to identify security misconfigurations and vulnerabilities, providing an essential layer of security for web-facing assets.

The Domain/Website integration through Mondoo allows users to specify the domain names they wish to monitor. Once configured, Mondoo can assess the security posture of these domains, checking for issues like SSL/TLS weaknesses, misconfigured DNS records, and other common web vulnerabilities that could expose the domain to cyber threats. To set up the domain integration, users simply need to provide the domain name within their Terraform configuration.

Domain Resource

Slack Integration

In version 0.6 of the Mondoo Terraform provider, the Slack integration specifically supports scanning Slack teams to assess and ensure security and compliance within the communication platform. This integration is crucial for organizations that use Slack as their primary communication tool, as it allows them to monitor and maintain security standards directly within their Slack environments.

The integration can evaluate various aspects of Slack usage and configurations, helping to identify potential security risks such as inappropriate access permissions or insecure content sharing practices. To set up this integration, we will need to configure it with appropriate parameters like the Slack API token.

Slack Resource

Microsoft 365 Integration

The Mondoo Microsoft 365 integration introduced in version 0.7 of the Mondoo Terraform provider allows for continuous scanning of Microsoft 365 resources. This integration is designed to identify misconfigurations and vulnerabilities within users and applications, providing ongoing security assessments. Once deployed, this integration continuously updates security assessments for new accounts and resources, ensuring your Microsoft 365 environment remains secure without the need for manual reconfiguration.

Be sure to meet the prerequisites for the Mondoo Microsoft 365 integration as outlined in the documentation. This includes setting up the necessary permissions and configuring settings within your Microsoft 365 environment to allow Mondoo to perform comprehensive security assessments effectively.

Microsoft 365 Resource

GitHub Integration

The Mondoo GitHub integration, introduced in version 0.8 of the Mondoo Terraform provider, enables continuous scanning of GitHub organizations and repositories. This integration is designed to identify misconfigurations and vulnerabilities within your GitHub environment, ensuring that your code repositories maintain high security and compliance standards.

To effectively use this integration, you will need to meet certain prerequisites. These include setting up appropriate permissions on GitHub to allow Mondoo access for scanning. This typically involves generating a GitHub API token with the necessary scopes and configuring this within your Mondoo setup to establish a secure connection between Mondoo and your GitHub repositories.

GitHub Resource

For an engaging dive into how to effectively use GitHub with Mondoo and Terraform, be sure to explore our blogs! These posts offer dynamic insights into securing your GitHub development processes through the Mondoo GitHub integration and reveal how integrating GitHub with Terraform can streamline and secure your infrastructure management.

AWS Integration

The Mondoo AWS integration, available from version 0.9 of the Mondoo Terraform provider, allows you to continuously scan AWS environments for security vulnerabilities and misconfigurations. This integration is crucial for maintaining stringent security standards across your AWS resources, including EC2 instances, S3 buckets, and more.

Be sure to meet the prerequisites for setting up this integration by configuring AWS permissions and roles appropriately, as detailed in the Mondoo documentation. This setup ensures that Mondoo can perform comprehensive scans effectively.

AWS Resource

These last advancements for the Mondoo Terraform provider have significantly contributed to a broader automated process of securing assets. We are proud to collaborate with the Mondoo Team to enhance its capabilities, making Mondoo a leading solution for infrastructure security and compliance. If you are interested in trying out for yourself, check out our blogpost about using Mondoo with Terraform automation.

Discovering how to build Terraform provider resources

As mentioned above, we at Infralovers, in collaboration with the Mondoo Team have been working on expanding the Mondoo Terraform provider capabilities. We vastly expanded our knowledge regarding the development of Terraform providers and in this blog of the series, we would like to share our knowledge regarding the development of Resources and Integrations for Mondoo using the Terraform provider Framework.

Mondoo uses the terraform-plugin-codegen-framework allowing for an easy and consistent expansion of their Terraform provider. The code below showcases the bare-bones structure of such a resource, which we will discuss in detail. Therefore the following paragraphs will showcase the different code and building blocks of a resource.

Packages and Imports

1package provider
2import (
3    "context"
4    "github.com/hashicorp/terraform-plugin-framework/resource"
5    "github.com/hashicorp/terraform-plugin-framework/resource/schema"
6    "github.com/hashicorp/terraform-plugin-framework/types"
7)

Like in every Go code, the first thing we typically do is to define the package name, followed by importing the necessary packages and dependencies that the code will use. Here, essential imports include context for managing requests contexts, and several packages from the Terraform Plugin Framework, which are important for defining resources and their schemas in a Terraform provider.

Type Declarations

1var _ resource.Resource = (*testResourceResource)(nil)
2func NewTestResourceResource() resource.Resource {
3    return &testResourceResource{}
4}
5type testResourceResource struct{}
6type testResourceResourceModel struct {
7    Id types.String `tfsdk:"id"`
8}

The provided Go code defines a Terraform resource for a provider using the HashiCorp Terraform Plugin Framework. The resource is named testResourceResource, and it implements the resource.Resource interface. This interface requires several functions to manage the lifecycle of the resource: Metadata, Schema, Create, Read, Update, and Delete.

We need to define the following types before starting to implement resource lifecycle logic:

  • testResourceResource: This is an empty struct that serves as the receiver for the resource functions. During our development of the Mondoo provider we would use this struct to declare the client API, which in Mondoo’s case was a Graphql API. This would later allow us to call on this client to make Graphql requests.
  • testResourceResourceModel: This struct defines the schema for the resource, containing for example an Id field of type types.String. Notice that the struct adds a tfsdk:"id" to the Id field. This tells Terraform that the resource we want to create can have a field called id. For example:
1resource "mondoo_test_resource" "my_resource" {
2  id = "MY_ID" // This resource has a field called `id`.
3}

Metadata Function

1func (r *testResourceResource) Metadata(ctx context.Context, req resource.MetadataRequest, resp *resource.MetadataResponse) {
2    resp.TypeName = req.ProviderTypeName + "_test_resource"
3}

The Metadata function sets the resource type name by appending _test_resource to the provider type name. This helps Terraform identify the resource type.

Schema Function

 1func (r *testResourceResource) Schema(ctx context.Context, req resource.SchemaRequest, resp *resource.SchemaResponse) {
 2    resp.Schema = schema.Schema{
 3        Attributes: map[string]schema.Attribute{
 4            "id": schema.StringAttribute{
 5                Computed: true,
 6                Validators: []validator.String{
 7                  // These are example validators from terraform-plugin-framework-validators
 8                  stringvalidator.LengthBetween(10, 256),
 9                  stringvalidator.RegexMatches(
10                    regexp.MustCompile(`^[a-z0-9]+$`),
11                    "must contain only lowercase alphanumeric characters",
12                  ),
13                },
14            },
15        },
16    }
17}

The Schema function defines the schema for the resource. It specifies that the resource has an id attribute, which is a computed string. This means the id is generated by the provider and not supplied by the user. Each resource (e.g. integration type) requires its own set of attributes, like names or configuration options, which must be added here.

Following what we just read, we need to change the Terraform resource we declared in the section "Type Declaration":

1resource "mondoo_test_resource" "my_resource" {
2  // Since the `id` is computed we should not declare it here
3}

In addition, validation of the different fields is handled here as can be seen in the example Schema above. If you want to read more on validating Terraform fields, you could refer to the following link.

Create Function

 1func (r *testResourceResource) Create(ctx context.Context, req resource.CreateRequest, resp *resource.CreateResponse) {
 2    var data testResourceResourceModel
 3    // Read Terraform plan data into the model
 4    resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
 5    if resp.Diagnostics.HasError() {
 6        return
 7    }
 8    // Create API call logic
 9    // Example data value setting
10    data.Id = types.StringValue("example-id")
11    // Save data into Terraform state
12    resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
13}

The Create function handles the creation of the resource. It reads the planned state from Terraform into a testResourceResourceModel field to a placeholder value ("example-id") and saves this state back to Terraform. This would be the correct place to call the client we declared previously and use it to create our resource and save the values we get back from the call to our Terraform state file.

Read Function

 1func (r *testResourceResource) Read(ctx context.Context, req resource.ReadRequest, resp *resource.ReadResponse) {
 2    var data testResourceResourceModel
 3    // Read Terraform prior state data into the model
 4    resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
 5    if resp.Diagnostics.HasError() {
 6        return
 7    }
 8    // Read API call logic
 9    // Save updated data into Terraform state
10    resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
11}

The Read function reads the current state of the resource from Terraform into a testResourceResourceModel instance. It then updates the state in Terraform, ensuring that any changes made outside of Terraform are reflected in the state.

Update Function

 1func (r *testResourceResource) Update(ctx context.Context, req resource.UpdateRequest, resp *resource.UpdateResponse) {
 2    var data testResourceResourceModel
 3    // Read Terraform plan data into the model
 4    resp.Diagnostics.Append(req.Plan.Get(ctx, &data)...)
 5    if resp.Diagnostics.HasError() {
 6        return
 7    }
 8    // Update API call logic
 9    // Save updated data into Terraform state
10    resp.Diagnostics.Append(resp.State.Set(ctx, &data)...)
11}

The Update function is similar to the Create function. It reads the planned state, performs any necessary updates, and saves the updated state back to Terraform.

Delete Function

1func (r *testResourceResource) Delete(ctx context.Context, req resource.DeleteRequest, resp *resource.DeleteResponse) {
2    var data testResourceResourceModel
3    // Read Terraform prior state data into the model
4    resp.Diagnostics.Append(req.State.Get(ctx, &data)...)
5    if resp.Diagnostics.HasError() {
6        return
7    }
8    // Delete API call logic
9}

The Delete function reads the current state of the resource and performs any necessary cleanup. Unlike the other functions, it does not save any state back to Terraform, as the resource is being deleted.

Code Summary

The code provides a basic implementation of a Terraform resource using the HashiCorp Terraform Plugin Framework. It includes functions for managing the resource's lifecycle and defines a simple schema with a single computed id attribute. The actual API call logic for creating, reading, updating, and deleting the resource is not implemented and would need to be added where indicated by comments.

Conclusion

In this blog post we explored the advancements in the Mondoo Terraform provider, achieved through our collaboration with Mondoo. It highlights the integration of Mondoo with various integration types, enhancing security and compliance automation across IT infrastructures. Our post showcases new resources and integration types introduced since April 2024, emphasizing the ease and effectiveness of securing assets through automated processes using Terraform. We also demonstrated the technical aspects of these integrations, providing insights into the coding process of Terraform providers. Stay tuned for our next blogs within this series about Data Sources and Imports using Terraform.

Go Back explore our courses

We are here for you

You are interested in our courses or you simply have a question that needs answering? You can contact us at anytime! We will do our best to answer all your questions.

Contact us