rolandvarga
rolandvarga

Reputation: 126

Elixir generating content

Elixir beginner here! I am attempting to generate a bash script based on a config file. When I iterate the configuration and print the string I generate it is all fine. However, when I try to concat or append to a list then I'm not getting anything back!

def generate_post_destroy_content(node_config) do
  hosts = create_post_destroy_string(:vmname, node_config)
  ips = create_post_destroy_string(:ip, node_config)
  content = "#!/bin/bash\n\n#{hosts}\n\n#{ips}"
  IO.puts content
end

def create_post_destroy_string(key, node_config) do
  # content = ""
  content = []
  for address <- node_config, do:
    # content = content <> "ssh-keygen -f ~/.ssh/known_hosts -R #{address[key]}"]
    content = content ++ ["ssh-keygen -f ~/.ssh/known_hosts -R # {address[key]}"]
    # IO.puts ["ssh-keygen -f ~/.ssh/known_hosts -R #{address[key]}"]
  content = Enum.join(content, "\n")
  content
end

my output

#!/bin/bash




=========END=========

Upvotes: 0

Views: 136

Answers (1)

Dogbert
Dogbert

Reputation: 222348

Variables in Elixir are immutable. Your code is creating a brand new content in every iteration of for . For this particular code, you make use of the fact that for returns a list of the evaluated value of the do block:

def create_post_destroy_string(key, node_config) do
  for address <- node_config do
    "ssh-keygen -f ~/.ssh/known_hosts -R #{address[key]}"
  end |> Enum.join("\n")
end

If you need to do more complex calculations, like only adding a list on some condition and/or adding more than one for some, you can use Enum.reduce/2. For details about that, check out this answer.

Upvotes: 1

Related Questions