Ansible 不会按应有的方式解释命令


- name: Execute commands in docker postgres container
command: docker exec -i postgres bash -c 'psql -U postgres -c "create user gitlab with password '000000b';"'

这个模块在 000000b(语法(附近向我发送了一个错误,但是当我使用命令时:
psql -U postgres -c "create user gitlab with password '000000b';"在终端上它工作正常。

为什么 Ansible 会以其他方式解释我的命令?

它失败是因为您的命令对于 ansibles 命令模块来说太复杂了(通过 3 个不同的命令行解释器和所有;)传递转义序列。你可能会用很多巧妙的转义序列来修复它,但我不建议尝试这样做,主要是因为它破坏了幂等性,其次是因为它真的不可读且维护起来很烦人,第三是因为这样做时你的衰老速度会快 2.34 倍。

如果你想要的只是使用 ansible 快速而肮脏地创建一个 gitlab 用户,你可以做这样的事情(仍然会破坏幂等性,这意味着你必须在多次运行时捕获错误(:

  • 确保将容器 Postgres 端口公开给本地主机:

    docker run -d --name postgres -p 5432:5432 postgres

  • 将剧本任务更改为如下所示的内容:

    - command: psql -h localhost -U postgres -c "create user gitlab with password '000000b';"
    ignore_errors: yes
    

但是,在我看来,执行此操作的正确方法是利用 ansibles postgres_user模块:

对于此示例,我使用上述命令在 docker 容器中运行了一个 postgresql。

剧本.yml

---
- hosts: localhost
tasks:
- name: create gitlab user
postgresql_user:
login_host: localhost
login_user: postgres
name: gitlab
password: '000000b'

这需要在系统上安装psycopg2,这应该可以从发行版存储库或 pypi 获得。此外,您可能希望提供经过哈希处理的密码,而不是明文形式。链接的模块文档也解决了这个问题。

最新更新