2016-06-20 32 views
1

Ansible的新手,运行版本2.1.0。我写了一个Ansible playbook,它针对一组主机运行PostgreSQL查询。当我在shell命令中指定SQL DB密码时,它的工作原理是,但我希望针对一组主机运行该手册,并需要更好的方式来输入密码,因为它们都是唯一的。任何人都可以提出一个更好的方法来做到这一点在Ansible Playbook中指定PostgreSQL密码

--- 

- 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

回答

3

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 }}' 

,然后设置pgpassword变量在grouphost水平。

+0

谢谢你的回复,我会t你的建议。 – Sysadmin1234

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