Home > front end >  regex in terraform replace function to uncomment multiple lines in a YAML file
regex in terraform replace function to uncomment multiple lines in a YAML file

Time:01-25

I have the following three lines in a YAML file:

# upstream_dns_servers:
#   - 8.8.8.8
#   - 8.8.4.4

I would like to remove the hash symbol from the start of each line whilst preserving everything that follows the hash symbol, i.e. to get:

upstream_dns_servers:
   - 8.8.8.8
   - 8.8.4.4

This should be possible with HCL replace function and the dialect of regex that this supports, I've tried using (?:x) syntax for the search string (non capturing sub-pattern - per the Terraform documentation) without success.

CodePudding user response:

Just as a dummy example, given the following test.yml file

some_key: toto 
# upstream_dns_servers:
#   - 8.8.8.8
#   - 8.8.4.4
other_key: titi

The following entries in main.tf perfectly do the job:

data "local_file" "config" {
    filename = "test.yml"
}

resource "local_file" "config_changed" {
  content  = join("\n", [for line in split("\n", data.local_file.config.content) : replace(line, "/^# (.*)$/", "$1")] )
  filename = "test-copy.yml"
}

Result:

$ terraform apply

Terraform used the selected providers to generate the following execution plan. Resource actions are indicated with the
following symbols:
    create

Terraform will perform the following actions:

  # local_file.config_changed will be created
    resource "local_file" "config_changed" {
        content              = <<-EOT
            some_key: toto 
            upstream_dns_servers:
              - 8.8.8.8
              - 8.8.4.4
            other_key: titi
        EOT
        directory_permission = "0777"
        file_permission      = "0777"
        filename             = "test-copy.yml"
        id                   = (known after apply)
    }

Plan: 1 to add, 0 to change, 0 to destroy.

Do you want to perform these actions?
  Terraform will perform the actions described above.
  Only 'yes' will be accepted to approve.

  Enter a value: yes

local_file.config_changed: Creating...
local_file.config_changed: Creation complete after 0s [id=cbf2811f5394ed4e55e0fa986432ae077790a6c8]

$ cat test-copy.yml
some_key: toto 
upstream_dns_servers:
  - 8.8.8.8
  - 8.8.4.4
other_key: titi
  •  Tags:  
  • Related