使用ansible使用ec2实例启动多个卷

dri*_*uja 5 amazon-ec2 amazon-web-services ansible

我正在配置一个附加了多少卷的ec2实例.以下是我的剧本,也是如此.

---
- hosts: localhost
  connection: local
  gather_facts: false
  vars:
    instance_type: 't2.micro'
    region: 'my-region'
    aws_zone: 'myzone'
    security_group: my-sg
    image: ami-sample
    keypair: my-keypair
    vpc_subnet_id: my-subnet
  tasks:
  - name: Launch instance
    ec2:
      image: "{{ image }}"
      instance_type: "{{ instance_type }}"
      keypair: "{{ keypair}}"
      instance_tags: '{"Environment":"test","Name":"test-provisioning"}'
      region: "{{region}}"
      aws_zone: "{{ region }}{{ aws_zone }}"
      group: "{{ security_group }}"
      vpc_subnet_id: "{{vpc_subnet_id}}"
      wait: true
      volumes:
        - device_name: "{{ item }}"
          with_items:
             - /dev/sdb
             - /dev/sdc
          volume_type: gp2
          volume_size: 100
          delete_on_termination: true
          encrypted: true
    register: ec2_info
Run Code Online (Sandbox Code Playgroud)

但得到以下错误

致命:[localhost]:失败!=> {"failed":true,"msg":"字段'args'的值无效,似乎包含一个未定义的变量.错误是:'item'未定义

如果我更换{{item}}/dev/sdb实例获取与比容容易启动.但我想用指定的项目列表创建多个卷 - /dev/sdb,/ dev/sdc等任何可能的方法来实现这一点?

Kon*_*rov 4

您不能with_items与变量和参数 \xe2\x80\x93 一起使用,它仅用于任务。
\n您需要提前构建卷列表:

\n\n
- name: Populate volumes list\n  set_fact:\n    vol:\n      device_name: "{{ item }}"\n      volume_type: gp2\n      volume_size: 100\n      delete_on_termination: true\n      encrypted: true\n  with_items:\n     - /dev/sdb\n     - /dev/sdc\n  register: volumes\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后执行ec2模块:

\n\n
volumes: "{{ volumes.results | map(attribute=\'ansible_facts.vol\') | list }}"\n
Run Code Online (Sandbox Code Playgroud)\n\n

更新:另一种方法没有set_fact

\n\n

为卷定义变量 \xe2\x80\x93 类型的模板字典(不带device_name):

\n\n
vol_default:\n  volume_type: gp2\n  volume_size: 100\n  delete_on_termination: true\n  encrypted: true\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后在你的ec2模块中你可以使用:

\n\n
volumes: "{{ [{\'device_name\': \'/dev/sdb\'},{\'device_name\': \'/dev/sdc\'}] | map(\'combine\',vol_default) | list }}"\n
Run Code Online (Sandbox Code Playgroud)\n