H
H
HighMan2020-12-01 18:32:15
PostgreSQL
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)
Z
zohan1993, 2020-12-01
@zohan1993

- hosts: 127.0.0.1

  tasks:

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

M
MaxKozlov, 2020-12-01
@MaxKozlov

I would recommend using a specialized tool rather than the shell
https://docs.ansible.com/ansible/latest/collection...
https://docs.ansible.com/ansible/latest/collection...
and loop through loop/with_items

P
Puma Thailand, 2020-12-01
@opium

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.

O
Oleg Volkov, 2020-12-02
@voleg4u

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