首页 > 解决方案 > Ansible playbook 使用 shell 命令更改用户

问题描述

我是 Ansible 的新手,愿意编写一个切换到另一个用户的小剧本,进入 Postgres 数据库,进行一些更改,退出数据库并切换回原始用户。

这是我手动执行的操作,但我想将这些命令放入剧本中:

sudo su - postgres
psql postgres
DROP DATABASE scm;
CREATE DATABASE scm OWNER scm ENCODING 'UTF8';
\q   ##This will quit the database
exit ##This will quit postgres user back to original user

我开始将其写入剧本,但似乎不起作用:

---

- name: TEST
  hosts: master_servers
  tasks: 
  - name: Delete DB
    shell:
      cmd: psql postgres | DROP DATABASE scm; | CREATE DATABASE scm OWNER scm ENCODING 'UTF8'; | \q | exit
    become: yes
    become_user: postgres

这是我得到的错误:

fatal: [xx.xx.xx.xx]: FAILED! => {
"msg": "Failed to change ownership of the temporary files Ansible needs to create despite connecting as a privileged user. Unprivileged become user would be unable to read the file."
}

提前致谢!

标签: postgresqlansible

解决方案


我建议您使用postgresql_db模块(由 Ansible 核心团队维护)。

您可以以幂等方式创建、删除或以其他方式操作 PostgreSQL 数据库(您应始终避免使用shellcmd模块,因为它们在设计上不是幂等的)。


推荐阅读