如何将文件中的一行读入 ansible 变量

Ser*_*ult 6 ansible

我正在尝试从文件中读取远程主机上的数据库密码/etc/mysql/debian.cnf。文件格式如下。有没有办法解析该password字段,以便我可以通过 Ansible 删除 mysql 用户?

# Automatically generated for Debian scripts. DO NOT TOUCH!
[client]
host     = localhost
user     = root
password = 5unnyv4l3
socket   = /var/run/mysqld/mysqld.sock
[mysql_upgrade]
host     = localhost
user     = root
password = 5unnyv4l3
socket   = /var/run/mysqld/mysqld.sock
basedir  = /usr
Run Code Online (Sandbox Code Playgroud)

小智 11

看起来“slurp”模块可以满足您的要求:https : //docs.ansible.com/ansible/latest/modules/slurp_module.html

- name: extract password from file
  slurp:
    src: /etc/mysql/debian.cnf
register: mypasswordfile

- name: Set User Password
  user: name=newUser
    password="{{ passwordfile['content'] | b64decode | regex_findall('password = \"(.+)\"') | first }}"

Run Code Online (Sandbox Code Playgroud)

测试和修复后编辑。


Zor*_*che 5

如果文件位于 ansible 系统本地,您可以使用ini 查找,它将从 ini 样式文件中读取值。如果您的文件是远程的,您可以使用 fetch/slurp 将副本拉取到本地系统。

我猜想查找会是这样的

- debug: msg="Password is {{ lookup('ini', 'password section=client file=my.cnf') }}"
Run Code Online (Sandbox Code Playgroud)