2017-08-28 67 views
0

我正在使用Ansible來部署我的Django應用程序。如何以冪等方式在Ansible中創建Django超級用戶?

我有我的Ansible劇本這個步驟來創建一個超級用戶:

- name: django create superuser 
    django_manage: 
     virtualenv: /.../app 
     app_path: /.../app 
     command: "createsuperuser --noinput --username=admin [email protected]{{ inventory_hostname }}" 

但是當我運行我的劇本第二次失敗與數據庫約束錯誤,因爲與給定用戶名超級用戶已經存在。我希望Ansible只能創建一次用戶。

我該如何使這個步驟具有冪等性?

回答

1

這是未經測試,但它應該工作:

- name: Check if django superuser exists 
    django_manage: 
    virtualenv: /.../app 
    app_path: /.../app 
    command: shell -c 'import sys; from django.contrib.auth.models import User; sys.exit(0 if User.objects.filter(username="admiin").count() > 0 else 1)' 
    register: checksuperuser 
    check_mode: True 
    ignore_errors: True 
    changed_when: False  

- name: django create superuser 
    django_manage: 
    virtualenv: /.../app 
    app_path: /.../app 
    command: "createsuperuser --noinput --username=admin [email protected]{{ inventory_hostname }}" 
    when: checksuperuser.rc != 0 
相關問題