【问题标题】:Running Ansible playbook using the Python API [duplicate]使用 Python API 运行 Ansible playbook [重复]
【发布时间】:2016-05-08 12:04:34
【问题描述】:

我创建了一个 Ansible 剧本来启动 5 个 AWS EC2 实例。我想使用 Python API 运行这个剧本,但我对如何做到这一点感到困惑。

这是我的剧本:

---
- name: Provision an EC2 Instance
hosts: local
connection: local
gather_facts: False
tags: provisioning
# Necessary Variables for creating/provisioning the EC2 Instance
vars:
  instance_type: t2.micro
  security_group: webserver 
  image: ami-f95ef58a
  region: eu-west-1c 
  keypair: Daniel 
  count: 5

# Task that will be used to Launch/Create an EC2 Instance
tasks:

  - name: Create a security group
    local_action: 
      module: ec2_group
      name: "{{ security_group }}"
      description: Security Group for webserver Servers
      region: "{{ region }}"
      rules:
        - proto: tcp
          type: ssh
          from_port: 22
          to_port: 22
          cidr_ip: 0.0.0.0/0
        - proto: tcp
          from_port: 80
          to_port: 80
          cidr_ip: 0.0.0.0/0
      rules_egress:
        - proto: all
          type: all
          cidr_ip: 0.0.0.0/0


  - name: Launch the new EC2 Instance
    local_action: ec2 
                  group={{ security_group }} 
                  instance_type={{ instance_type}} 
                  image={{ image }} 
                  wait=true 
                  region={{ region }} 
                  keypair={{ keypair }}
                  count={{count}}
    register: ec2

  - name: Add the newly created EC2 instance(s) to the local host group (located inside the directory)
    local_action: lineinfile 
                  dest="./hosts" 
                  regexp={{ item.public_ip }} 
                  insertafter="[webserver]" line={{ item.public_ip }}
    with_items: ec2.instances


  - name: Wait for SSH to come up
    local_action: wait_for 
                  host={{ item.public_ip }} 
                  port=22 
                  state=started
    with_items: ec2.instances

  - name: Add tag to Instance(s)
    local_action: ec2_tag resource={{ item.id }} region={{ region }} state=present
    with_items: ec2.instances
    args:
      tags:
        Name: webserver

这是运行剧本的代码:

ansible-playbook -i hosts ec2_launch.yml

如何在 Python 项目文件中使用此代码运行 playbook?

【问题讨论】:

标签: python ansible


【解决方案1】:

如果你只是想运行一个可以通过 Ansible 正常运行的完整剧本,那么为什么不直接使用 subprocess 来运行它呢?

这应该像这样简单:

from subprocess import call
call(["ansible-playbook", "-i", "hosts", "ec2_launch.yml"])

只要剧本和清单与您的 Python 项目位于相同的相对路径中。

如果您想与 Ansible 的 Python API 进行更细粒度的交互,那么您可能需要read the docs

【讨论】:

    猜你喜欢
    • 2015-02-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-14
    • 2018-02-10
    相关资源
    最近更新 更多