循环中的Ansible和嵌套变量

时间:2016-04-16 06:53:14

标签: loops variables ansible

我在Ansible中有一种方法可以在循环中访问变量中的变量吗?例如,配置debconf来安装MySQL / MariaDB服务器需要两个如下指令:

- name: Define maria root password
  shell: echo mysql-server mysql-server/root_password password {{ mysqlRootPass }} | debconf-set-selections

- name: Define maria root password again
  shell: echo mysql-server mysql-server/root_password_again password {{ mysqlRootPass }} | debconf-set-selections

但如果我能做到这一点,那将会更加紧凑:

- name: Define maria root password
  shell: {{ item }}
  with_items:
    - "{ echo mysql-server mysql-server/root_password password {{ mysqlRootPass }} | debconf-set-selections }"
    - "{ echo mysql-server mysql-server/root_password_again password {{ mysqlRootPass }} | debconf-set-selections }"

显然,这不起作用。

有没有办法让它发挥作用?有没有更好的方法呢?我错过了什么吗?

2 个答案:

答案 0 :(得分:1)

这是我完整的MySQL工作角色,可能对您有帮助。

<强>乏/ main.yml

mysql_root_pass: mypassword #MySQL Root Password

<强>任务/ main.yml

---
 - name: Install the MySQL packages
   apt:
     name: "{{ item }}"
     state: installed
     update_cache: yes
   with_items:
     - mysql-server-5.6
     - mysql-client-5.6
     - python-mysqldb
     - libmysqlclient-dev

 - name: Update MySQL root password for all root accounts
   mysql_user:
     name: root
     host: "{{ item }}"
     password: "{{ mysql_root_pass }}"
     state: present
   with_items:
     - "{{ ansible_hostname }}"
     - 127.0.0.1
     - ::1
     - localhost

 - name: Copy the root credentials as .my.cnf file
   template:
     src: root.cnf.j2
     dest: "~/.my.cnf"
     mode: 0600

 - name: Ensure Anonymous user(s) are not in the database
   mysql_user:
     name=''
     host: "{{ item }}"
     state: absent
   with_items:
     - localhost
     - "{{ ansible_hostname }}"

 - name: Remove the test database
   mysql_db:
     name: "test"
     state: absent
   notify:
     - Restart MySQL

<强>模板/ root.cnf.j2

[client]
user=root
password={{ mysql_root_pass }}

<强>处理程序/ main.yml

---
 - name: Restart MySQL
   service:
     name: mysql
     state: restarted

我的site.yml看起来像这样:

---
- hosts: all
  become: yes
  gather_facts: yes
  roles:
    - mysql

如果您只是想更新已配置的MySQL的密码:

vars/main.yml

mysql_old_root_pass: olmysqldpassword
mysql_root_pass: newmysqlpassword 

tasks/main.yml

- name: Set root user password
  mysql_user:
    name: root
    host: "{{ item }}"
    password: "{{ mysql_root_pass }}"
    check_implicit_admin=yes
    login_user: root
    login_password: "{{ mysql_old_root_password }}"
    state: present
  with_items:
    - "{{ ansible_hostname }}"
    - 127.0.0.1
    - ::1
    - localhost

希望这会对你有所帮助。如果您需要任何帮助,请查看此github https://github.com/firebug/firebug/issues/6410

答案 1 :(得分:1)

Ansible中的{{ }}符号来自Jinja2模板,它基本上指示Ansible将其替换为该变量的内容。

with_items引入了特殊变量item,它是当前循环的特定项。

因此,您指示命令模块执行{ echo...,即with_items中的任何内容。您只需要命令本身:echo...

参考:Ansible docs: using variables and Jinja2