HighMan2020-12-01 18:32:15
HighMan, 2020-12-01 18:32:15

Ansible how to write a command loop correctly?

Hello comrades!
I am not strong in Ansible. Now only in the process of studying,
Task: execute several commands in a loop. Some commands are repeated. Here are the commands:
psql -U postgres -c "CREATE USER user_name"
psql -U postgres -c "CREATE DATABASE dn_name OWNER user_name "
the first part of the command is constant: psql -U postgres -c only queries are changed.
You can, of course, decide on the forehead:
- name: Create user
command: psql -U postgres -c "CREATE USER user_name"
Also, as I understand it, ansible has a plugin for working with postgresql, but for my tasks , in my opinion, it is superfluous. Or am I wrong?
Also, of course, you can just throw a bash script that will do all this in the best possible way.
How would you approach the decision?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
zohan1993, 2020-12-01

- hosts:


    - name: test
      shell: echo {{ item }} >> /tmp/test.txt
        - "1"
        - "2"
        - "3"
        - "4"
        - "5"

MaxKozlov, 2020-12-01

I would recommend using a specialized tool rather than the shell
and loop through loop/with_items

Puma Thailand, 2020-12-01

There is a postgres module through it and you have to do, what for to fence your shit crutch? It is more difficult to maintain and understand when there is a standard elegant solution to their box.

Oleg Volkov, 2020-12-02

The main thing when writing an ansible is to think, what will happen if it is run more than once?
Ideally, if the system is already in the desired state, it should not start or restart anything.
If the whole ansible is a team shell - just write a script and don't bother.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question