我按照此处的示例http://docs.ansible.com/ansible/iam_policy_module.html尝试创建新的AWS IAM用户,然后使用此新用户的用户名将IAM策略附加到其中。
示例:
task:
- name: Create Two Groups, Mario and Luigi
iam:
iam_type: group
name: "{{ item }}"
state: present
with_items:
- Mario
- Luigi
register: new_groups
- name: Apply READ-ONLY policy to new groups that have been recently created
iam_policy:
iam_type: group
iam_name: "{{ item.created_group.group_name }}"
policy_name: "READ-ONLY"
policy_document: readonlypolicy.json
state: present
with_items: "{{ new_groups.results }}"
我已将其改编为与一位用户合作:
- hosts: 127.0.0.1
gather_facts: no
connection: local
tasks:
- name: Create user lamda_ecr_delete
iam:
iam_type: user
name: "{{ item }}"
state: present
with_items:
- lambda_ecr_delete
register: new_user
- name: Apply ecr delete policy to newly created user
iam_policy:
iam_type: user
iam_name: "{{ item.created_user.user_name }}"
policy_name: "lambda_ecr_delete"
policy_document: assets/aws-policies/lambda_ecr_delete.json
state: present
with_items: "{{ new_user.results }}"
但是当我尝试在字典中检索用户名时,item.created_user
不存在。
当我使用debug
查看{{ new_user.results }}
的内容时,我可以确定它是包含dict的python列表,因此我可以使用[0]
访问它然后致电invocation.module_args.name
,这是一个有效的密钥。
这是使用debug: msg="{{ new_user.results }}"
运行时--check
的输出:
ok: [127.0.0.1] => {
"changed": false,
"msg": [
{
"_ansible_item_result": true,
"_ansible_no_log": false,
"_ansible_parsed": true,
"changed": false,
"invocation": {
"module_args": {
"iam_type": "user",
"name": "lambda_ecr_delete",
"state": "present"
}
},
"item": "lambda_ecr_delete",
"msg": "remote module (iam) does not support check mode",
"skipped": true
}
]
}
但这似乎是黑客。是否有直接访问这些module_args的快捷方式?示例中显示的内容为.created_user
?
答案 0 :(得分:0)
改为使用item.user_meta.created_user.user_name
。
如果检查created_user
的调试输出,您可能会注意到user_meta
嵌套在new_user.results
中。看起来像:
"user_meta": {
"access_keys": null,
"created_user": {
"arn": "arn:aws:iam::<yourid>:user/test-ansible",
"create_date": "2017-04-03T16:31:53.530Z",
"path": "/",
"user_id": "EXAMPLEKAJHFEXAMPLE",
"user_name": "test-ansible"
},
"password": null
}
但请注意,在第二次运行时iam
模块会返回不同的输出:
"user_name": "test-ansible"
而不是user_meta
字典。