0

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=========

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.