首页 文章

在Ansible Playbook中指定PostgreSQL密码

提问于
浏览
2

Ansible的新功能,运行版本2.1.0 . 我编写了一个Ansible playbook,它针对一组主机运行PostgreSQL查询 . 当我在shell命令中指定SQL DB密码时,它可以工作,但我希望针对一组主机运行该剧本,并且需要一种更好的方式来输入密码,因为它们都是唯一的 . 有谁能建议一个更好的方法来做到这一点?

---

- hosts: Test_Hosts    
  sudo: yes    
  sudo_user: root    
  gather_facts: yes
  tasks:    
  - name: Login to DB and run command    
    shell: export PGPASSWORD='Password'; psql -U 'user' -d 'db' -c 'select * FROM table'; 
    register: select_all_from_table

  - name: Display table contents    
    debug: msg="{{ select_all_from_table.stdout }}"

我看到了关于该主题的另一个帖子,但不确定如何实现该建议:Run a postgresql command with ansible playbook. Postgresql requires password

2 回答

  • 4

    Ansible允许您使用environment parameter为任务设置任务的环境变量 .

    所以在你的情况下你可以这样做:

    - name: Login to DB and run command    
        shell: export PGPASSWORD='Password'; psql -U 'user' -d 'db' -c 'select * FROM table'; 
        register: select_all_from_table
        environment:
          PGPASSWORD: '{{ pgpassword }}'
    

    然后在grouphost级别设置 pgpassword 变量 .

  • 0

    我今天刚遇到这个问题,这对我有用 . 在Linux上,您可以将所有凭据打包到 ~/.pgpass 隐藏文件中 .

    只需在本地创建它(在本例中为 ./files/pgpass ),然后在运行psql命令之前使用ansible将其复制到主机上 .

    - name: set passwd file for PSQL
      copy:
        src: files/pgpass
        dest: ~/.pgpass
        mode: 0600           ### important: will not work with wrong permissions
    
    - name: PSQL command
      shell: "psql -U 'user' -d 'db' -c 'select * FROM table'"
      register: select_all_from_table
    

    文件内容必须采用以下格式:

    hostname:port:database:username:password
    

    但是,您可以使用通配符,因此我看起来像这样,例如:

    *:*:db1:user1:passwd1
    *:*:db2:user2:passwd2
    

    有关详细信息,请参阅文档:https://www.postgresql.org/docs/9.1/static/libpq-pgpass.html

相关问题