Adds CredentialLookUp to JT Form

This commit is contained in:
Alex Corey
2019-10-22 16:00:02 -04:00
parent f57cf03f4b
commit d10e727b3c
11 changed files with 375 additions and 68 deletions

View File

@@ -1,5 +1,7 @@
import AdHocCommands from './models/AdHocCommands'; import AdHocCommands from './models/AdHocCommands';
import Config from './models/Config'; import Config from './models/Config';
import CredentialTypes from './models/CredentialTypes'
import Credentials from './models/Credentials'
import InstanceGroups from './models/InstanceGroups'; import InstanceGroups from './models/InstanceGroups';
import Inventories from './models/Inventories'; import Inventories from './models/Inventories';
import InventorySources from './models/InventorySources'; import InventorySources from './models/InventorySources';
@@ -23,6 +25,8 @@ import WorkflowJobTemplates from './models/WorkflowJobTemplates';
const AdHocCommandsAPI = new AdHocCommands(); const AdHocCommandsAPI = new AdHocCommands();
const ConfigAPI = new Config(); const ConfigAPI = new Config();
const CredentialsAPI = new Credentials();
const CredentialTypesAPI = new CredentialTypes();
const InstanceGroupsAPI = new InstanceGroups(); const InstanceGroupsAPI = new InstanceGroups();
const InventoriesAPI = new Inventories(); const InventoriesAPI = new Inventories();
const InventorySourcesAPI = new InventorySources(); const InventorySourcesAPI = new InventorySources();
@@ -47,6 +51,8 @@ const WorkflowJobTemplatesAPI = new WorkflowJobTemplates();
export { export {
AdHocCommandsAPI, AdHocCommandsAPI,
ConfigAPI, ConfigAPI,
CredentialsAPI,
CredentialTypesAPI,
InstanceGroupsAPI, InstanceGroupsAPI,
InventoriesAPI, InventoriesAPI,
InventorySourcesAPI, InventorySourcesAPI,

View File

@@ -0,0 +1,10 @@
import Base from '../Base';
class CredentialTypes extends Base {
constructor(http) {
super(http);
this.baseUrl = '/api/v2/credential_types/';
}
}
export default CredentialTypes;

View File

@@ -0,0 +1,10 @@
import Base from '../Base';
class Credentials extends Base {
constructor(http) {
super(http);
this.baseUrl = '/api/v2/credentials/';
}
}
export default Credentials;

View File

@@ -44,6 +44,14 @@ class JobTemplates extends InstanceGroupsMixin(NotificationsMixin(Base)) {
readCredentials(id, params) { readCredentials(id, params) {
return this.http.get(`${this.baseUrl}${id}/credentials/`, { params }); return this.http.get(`${this.baseUrl}${id}/credentials/`, { params });
} }
associateCredentials(id, credential) {
return this.http.post(`${this.baseUrl}${id}/credentials/`, { id: credential });
}
disassociateCredentials(id, credential) {
return this.http.post(`${this.baseUrl}${id}/credentials/`, { id: credential, disassociate: true });
}
} }
export default JobTemplates; export default JobTemplates;

View File

@@ -0,0 +1,165 @@
import React from 'react';
import PropTypes from 'prop-types';
import { withI18n } from '@lingui/react';
import { withRouter } from 'react-router-dom';
import { t } from '@lingui/macro';
import { FormGroup, Tooltip } from '@patternfly/react-core';
import { QuestionCircleIcon as PFQuestionCircleIcon } from '@patternfly/react-icons';
import styled from 'styled-components';
import { CredentialsAPI, CredentialTypesAPI } from '@api';
import Lookup from '@components/Lookup';
const QuestionCircleIcon = styled(PFQuestionCircleIcon)`
margin-left: 10px;
`;
class CredentialsLookup extends React.Component {
constructor(props) {
super(props)
this.state = {
credentials: props.credentials,
selectedCredentialType: {label: "Machine", id: 1, kind: 'ssh'},
credentialTypes: []
}
this.handleCredentialTypeSelect = this.handleCredentialTypeSelect.bind(this);
this.loadCredentials = this.loadCredentials.bind(this);
this.loadCredentialTypes = this.loadCredentialTypes.bind(this);
this.toggleCredential = this.toggleCredential.bind(this);
}
componentDidMount() {
this.loadCredentials({page: 1, page_size: 5, order_by:'name'})
this.loadCredentialTypes();
}
componentDidUpdate(prevState) {
const {selectedType} = this.state
if (prevState.selectedType !== selectedType) {
Promise.all([this.loadCredentials()]);
}
}
async loadCredentialTypes() {
const {onError} =this.props
try {
const { data } = await CredentialTypesAPI.read()
const acceptableTypes = ["machine", "cloud", "net", "ssh", "vault"]
const credentialTypes =[]
data.results
.forEach(cred => {
acceptableTypes.forEach(aT => {
if (aT === cred.kind) {
// This object has several repeated values as some of it's children
// require different field values.
cred = {
id: cred.id, kind: cred.kind, type: cred.namespace,
value: cred.name, label: cred.name, isDisabled: false
}
credentialTypes.push(cred)
}})
})
this.setState({ credentialTypes })
} catch (err){
onError(err)
}
}
async loadCredentials(params) {
const { selectedCredentialType } = this.state;
params.credential_type = selectedCredentialType.id || 1
return CredentialsAPI.read(params)
}
handleCredentialTypeSelect(value, type) {
const {credentialTypes} = this.state
const selectedType = credentialTypes.filter(item => item.label === type)
this.setState({selectedCredentialType: selectedType[0]})
}
toggleCredential(item) {
const { credentials: stateToUpdate, selectedCredentialType } = this.state;
const { onChange } = this.props;
const index = stateToUpdate.findIndex(
credential => credential.id === item.id
)
if (index > -1) {
const newCredentialsList = stateToUpdate.filter(cred => cred.id !== item.id)
this.setState({ credentials: newCredentialsList });
onChange(newCredentialsList)
return;
}
const credentialTypeOccupied = stateToUpdate.some(cred => cred.kind === item.kind);
if (selectedCredentialType.value === "Vault" || !credentialTypeOccupied ) {
item.credentialType = selectedCredentialType
this.setState({ credentials: [...stateToUpdate, item] })
onChange([...stateToUpdate, item])
} else {
const credsList = [...stateToUpdate]
const occupyingCredIndex = stateToUpdate.findIndex(occupyingCred =>
occupyingCred.kind === item.kind)
credsList.splice(occupyingCredIndex, 1, item)
this.setState({ credentials: credsList })
onChange(credsList)
}
}
render() {
const { tooltip, i18n } = this.props;
const { credentials, selectedCredentialType, credentialTypes } = this.state;
return (
<FormGroup
label={i18n._(t`Credentials`)}
fieldId="org-credentials"
>
{tooltip && (
<Tooltip position="right" content={tooltip}>
<QuestionCircleIcon />
</Tooltip>
)}
{credentialTypes && (
<Lookup
selectCategoryOptions={credentialTypes}
selectCategory={this.handleCredentialTypeSelect}
selectedCategory={selectedCredentialType}
onToggleItem = {this.toggleCredential}
onloadCategories={this.loadCredentialTypes}
id="org-credentials"
lookupHeader={i18n._(t`Credentials`)}
name="credentials"
value={credentials}
multiple
onLookupSave={() => {}}
getItems={this.loadCredentials}
qsNamespace="credentials"
columns={[
{
name: i18n._(t`Name`),
key: 'name',
isSortable: true,
isSearchable: true,
},
]}
sortedColumnKey="name"
/>
)}
</FormGroup>
);
}
}
CredentialsLookup.propTypes = {
tooltip: PropTypes.string,
onChange: PropTypes.func.isRequired,
};
CredentialsLookup.defaultProps = {
tooltip: '',
};
export { CredentialsLookup as _CredentialsLookup };
export default withI18n()(withRouter(CredentialsLookup));

View File

@@ -15,16 +15,19 @@ import {
ButtonVariant, ButtonVariant,
InputGroup as PFInputGroup, InputGroup as PFInputGroup,
Modal, Modal,
ToolbarItem,
} from '@patternfly/react-core'; } from '@patternfly/react-core';
import { withI18n } from '@lingui/react'; import { withI18n } from '@lingui/react';
import { t } from '@lingui/macro'; import { t } from '@lingui/macro';
import styled from 'styled-components'; import styled from 'styled-components';
import AnsibleSelect from '../AnsibleSelect'
import PaginatedDataList from '../PaginatedDataList'; import PaginatedDataList from '../PaginatedDataList';
import VerticalSeperator from '../VerticalSeparator'
import DataListToolbar from '../DataListToolbar'; import DataListToolbar from '../DataListToolbar';
import CheckboxListItem from '../CheckboxListItem'; import CheckboxListItem from '../CheckboxListItem';
import SelectedList from '../SelectedList'; import SelectedList from '../SelectedList';
import { ChipGroup, Chip } from '../Chip'; import { ChipGroup, Chip, CredentialChip } from '../Chip';
import { getQSConfig, parseQueryString } from '../../util/qs'; import { getQSConfig, parseQueryString } from '../../util/qs';
const SearchButton = styled(Button)` const SearchButton = styled(Button)`
@@ -65,32 +68,49 @@ class Lookup extends React.Component {
results: [], results: [],
count: 0, count: 0,
error: null, error: null,
isDropdownOpen: false
}; };
this.qsConfig = getQSConfig(props.qsNamespace, { this.qsConfig = getQSConfig(props.qsNamespace, {
page: 1, page: 1,
page_size: 5, page_size: 5,
order_by: props.sortedColumnKey, order_by: props.sortedColumnKey,
}); });
this.handleModalToggle = this.handleModalToggle.bind(this); this.handleModalToggle = this.handleModalToggle.bind(this);
this.toggleSelected = this.toggleSelected.bind(this); this.toggleSelected = this.toggleSelected.bind(this);
this.saveModal = this.saveModal.bind(this); this.saveModal = this.saveModal.bind(this);
this.getData = this.getData.bind(this); this.getData = this.getData.bind(this);
this.clearQSParams = this.clearQSParams.bind(this); this.clearQSParams = this.clearQSParams.bind(this);
this.toggleDropdown = this.toggleDropdown.bind(this);
} }
componentDidMount() { componentDidMount() {
this.getData(); const {onLoadCredentialTypes} = this.props
} ;
if (onLoadCredentialTypes) {
componentDidUpdate(prevProps) { Promise.all([onLoadCredentialTypes(), this.getData()]);
const { location } = this.props; } else {
if (location !== prevProps.location) {
this.getData(); this.getData();
} }
} }
componentDidUpdate(prevProps) {
const { location, selectedCategory } = this.props;
if ((location !== prevProps.location) ||
(prevProps.selectedCategory !== selectedCategory)) {
this.getData();
}
}
toggleDropdown() {
const { isDropdownOpen } = this.state;
this.setState({isDropdownOpen: !isDropdownOpen})
}
assertCorrectValueType() { assertCorrectValueType() {
const { multiple, value } = this.props; const { multiple, value, selectCategoryOptions } = this.props;
if (selectCategoryOptions) {
return
}
if (!multiple && Array.isArray(value)) { if (!multiple && Array.isArray(value)) {
throw new Error( throw new Error(
'Lookup value must not be an array unless `multiple` is set' 'Lookup value must not be an array unless `multiple` is set'
@@ -110,30 +130,31 @@ class Lookup extends React.Component {
this.setState({ error: false }); this.setState({ error: false });
try { try {
const { data } = await getItems(queryParams); const { data } = await getItems(queryParams);
const { results, count } = data; const { results, count } = data;
this.setState({ this.setState({
results, results,
count, count,
}); });
} catch (err) { } catch (err) {
this.setState({ error: true }); this.setState({ error: true });
} }
} }
toggleSelected(row) { toggleSelected(row) {
const { name, onLookupSave, multiple } = this.props; const { name, onLookupSave, multiple, onToggleItem, selectCategoryOptions } = this.props;
const { const {
lookupSelectedItems: updatedSelectedItems, lookupSelectedItems: updatedSelectedItems, isModalOpen
isModalOpen,
} = this.state; } = this.state;
const selectedIndex = updatedSelectedItems.findIndex( const selectedIndex = updatedSelectedItems.findIndex(
selectedRow => selectedRow.id === row.id selectedRow => selectedRow.id === row.id
); );
if (multiple) { if (multiple) {
if (selectCategoryOptions) {
onToggleItem(row, isModalOpen)
}
if (selectedIndex > -1) { if (selectedIndex > -1) {
updatedSelectedItems.splice(selectedIndex, 1); updatedSelectedItems.splice(selectedIndex, 1);
this.setState({ lookupSelectedItems: updatedSelectedItems }); this.setState({ lookupSelectedItems: updatedSelectedItems });
@@ -150,13 +171,13 @@ class Lookup extends React.Component {
// This handles the case where the user removes chips from the lookup input // This handles the case where the user removes chips from the lookup input
// while the modal is closed // while the modal is closed
if (!isModalOpen) { if (!isModalOpen) {
onLookupSave(updatedSelectedItems, name); onLookupSave(updatedSelectedItems, name)
} };
} }
handleModalToggle() { handleModalToggle() {
const { isModalOpen } = this.state; const { isModalOpen } = this.state;
const { value, multiple } = this.props; const { value, multiple, selectCategory } = this.props;
// Resets the selected items from parent state whenever modal is opened // Resets the selected items from parent state whenever modal is opened
// This handles the case where the user closes/cancels the modal and // This handles the case where the user closes/cancels the modal and
// opens it again // opens it again
@@ -168,6 +189,9 @@ class Lookup extends React.Component {
this.setState({ lookupSelectedItems }); this.setState({ lookupSelectedItems });
} else { } else {
this.clearQSParams(); this.clearQSParams();
if (selectCategory) {
selectCategory(null, "Machine");
}
} }
this.setState(prevState => ({ this.setState(prevState => ({
isModalOpen: !prevState.isModalOpen, isModalOpen: !prevState.isModalOpen,
@@ -177,11 +201,11 @@ class Lookup extends React.Component {
saveModal() { saveModal() {
const { onLookupSave, name, multiple } = this.props; const { onLookupSave, name, multiple } = this.props;
const { lookupSelectedItems } = this.state; const { lookupSelectedItems } = this.state;
const value = multiple const value = multiple ? lookupSelectedItems : lookupSelectedItems[0] || null;
? lookupSelectedItems
: lookupSelectedItems[0] || null; this.handleModalToggle();
onLookupSave(value, name); onLookupSave(value, name);
this.handleModalToggle();
} }
clearQSParams() { clearQSParams() {
@@ -201,6 +225,7 @@ class Lookup extends React.Component {
count, count,
} = this.state; } = this.state;
const { const {
form,
id, id,
lookupHeader, lookupHeader,
value, value,
@@ -208,27 +233,40 @@ class Lookup extends React.Component {
multiple, multiple,
name, name,
onBlur, onBlur,
selectCategory,
required, required,
i18n, i18n,
selectCategoryOptions,
selectedCategory
} = this.props; } = this.props;
const header = lookupHeader || i18n._(t`Items`); const header = lookupHeader || i18n._(t`Items`);
const canDelete = !required || (multiple && value.length > 1); const canDelete = !required || (multiple && value.length > 1);
const chips = () => {
const chips = value ? ( return (selectCategoryOptions && selectCategoryOptions.length > 0) ? (
<ChipGroup> <ChipGroup>
{(multiple ? value : [value]).map(chip => ( {(multiple ? value : [value]).map(chip => (
<Chip <CredentialChip
key={chip.id} key={chip.id}
onClick={() => this.toggleSelected(chip)} onClick={() => this.toggleSelected(chip)}
isReadOnly={!canDelete} isReadOnly={!canDelete}
> credential={chip}
{chip.name} />
</Chip> ))}
))} </ChipGroup>
</ChipGroup> ) : (
) : null; <ChipGroup>
{(multiple ? value : [value]).map(chip => (
<Chip
key={chip.id}
onClick={() => this.toggleSelected(chip)}
isReadOnly={!canDelete}
>
{chip.name}
</Chip>
))}
</ChipGroup>
)
}
return ( return (
<Fragment> <Fragment>
<InputGroup onBlur={onBlur}> <InputGroup onBlur={onBlur}>
@@ -240,7 +278,9 @@ class Lookup extends React.Component {
> >
<SearchIcon /> <SearchIcon />
</SearchButton> </SearchButton>
<ChipHolder className="pf-c-form-control">{chips}</ChipHolder> <ChipHolder className="pf-c-form-control">
{value ? chips(value) : null}
</ChipHolder>
</InputGroup> </InputGroup>
<Modal <Modal
className="awx-c-modal" className="awx-c-modal"
@@ -265,6 +305,13 @@ class Lookup extends React.Component {
</Button>, </Button>,
]} ]}
> >
{(selectCategoryOptions && selectCategoryOptions.length > 0) && (
<ToolbarItem css=" display: flex; align-items: center;">
<span css="flex: 0 0 25%;">Selected Category</span>
<VerticalSeperator />
<AnsibleSelect css="flex: 1 1 75%;" id="credentialsLookUp-select" label="Selected Category" data={selectCategoryOptions} value={selectedCategory.label} onChange={selectCategory} form={form}/>
</ToolbarItem>
)}
<PaginatedDataList <PaginatedDataList
items={results} items={results}
itemCount={count} itemCount={count}
@@ -277,9 +324,10 @@ class Lookup extends React.Component {
itemId={item.id} itemId={item.id}
name={multiple ? item.name : name} name={multiple ? item.name : name}
label={item.name} label={item.name}
isSelected={lookupSelectedItems.some(i => i.id === item.id)} isSelected={selectCategoryOptions ? value.some(i => i.id === item.id)
: lookupSelectedItems.some(i => i.id === item.id)}
onSelect={() => this.toggleSelected(item)} onSelect={() => this.toggleSelected(item)}
isRadio={!multiple} isRadio={!multiple || ((selectCategoryOptions && selectCategoryOptions.length) && selectedCategory.value !== "Vault")}
/> />
)} )}
renderToolbar={props => <DataListToolbar {...props} fillWidth />} renderToolbar={props => <DataListToolbar {...props} fillWidth />}
@@ -288,10 +336,11 @@ class Lookup extends React.Component {
{lookupSelectedItems.length > 0 && ( {lookupSelectedItems.length > 0 && (
<SelectedList <SelectedList
label={i18n._(t`Selected`)} label={i18n._(t`Selected`)}
selected={lookupSelectedItems} selected={selectCategoryOptions ? value : lookupSelectedItems}
showOverflowAfter={5} showOverflowAfter={5}
onRemove={this.toggleSelected} onRemove={this.toggleSelected}
isReadOnly={!canDelete} isReadOnly={!canDelete}
isCredentialList={selectCategoryOptions && selectCategoryOptions.length > 0}
/> />
)} )}
{error ? <div>error</div> : ''} {error ? <div>error</div> : ''}

View File

@@ -2,3 +2,4 @@ export { default } from './Lookup';
export { default as InstanceGroupsLookup } from './InstanceGroupsLookup'; export { default as InstanceGroupsLookup } from './InstanceGroupsLookup';
export { default as InventoryLookup } from './InventoryLookup'; export { default as InventoryLookup } from './InventoryLookup';
export { default as ProjectLookup } from './ProjectLookup'; export { default as ProjectLookup } from './ProjectLookup';
export { default as CredentialsLookup } from './CredentialsLookup';

View File

@@ -2,7 +2,7 @@ import React, { Component } from 'react';
import PropTypes from 'prop-types'; import PropTypes from 'prop-types';
import { Split as PFSplit, SplitItem } from '@patternfly/react-core'; import { Split as PFSplit, SplitItem } from '@patternfly/react-core';
import styled from 'styled-components'; import styled from 'styled-components';
import { ChipGroup, Chip } from '../Chip'; import { ChipGroup, Chip, CredentialChip } from '../Chip';
import VerticalSeparator from '../VerticalSeparator'; import VerticalSeparator from '../VerticalSeparator';
const Split = styled(PFSplit)` const Split = styled(PFSplit)`
@@ -27,22 +27,33 @@ class SelectedList extends Component {
onRemove, onRemove,
displayKey, displayKey,
isReadOnly, isReadOnly,
isCredentialList
} = this.props; } = this.props;
const chips = isCredentialList ? selected.map(item => (
<CredentialChip
key={item.id}
isReadOnly={isReadOnly}
onClick={() => onRemove(item)}
credential={item}
>
{item[displayKey]}
</CredentialChip>
)) : selected.map(item => (
<Chip
key={item.id}
isReadOnly={isReadOnly}
onClick={() => onRemove(item)}
>
{item[displayKey]}
</Chip>
))
return ( return (
<Split> <Split>
<SplitLabelItem>{label}</SplitLabelItem> <SplitLabelItem>{label}</SplitLabelItem>
<VerticalSeparator /> <VerticalSeparator />
<SplitItem> <SplitItem>
<ChipGroup showOverflowAfter={showOverflowAfter}> <ChipGroup showOverflowAfter={showOverflowAfter}>
{selected.map(item => ( {chips}
<Chip
key={item.id}
isReadOnly={isReadOnly}
onClick={() => onRemove(item)}
>
{item[displayKey]}
</Chip>
))}
</ChipGroup> </ChipGroup>
</SplitItem> </SplitItem>
</Split> </Split>

View File

@@ -22,6 +22,7 @@ function JobTemplateAdd({ history, i18n }) {
organizationId, organizationId,
instanceGroups, instanceGroups,
initialInstanceGroups, initialInstanceGroups,
credentials,
...remainingValues ...remainingValues
} = values; } = values;
@@ -33,6 +34,7 @@ function JobTemplateAdd({ history, i18n }) {
await Promise.all([ await Promise.all([
submitLabels(id, labels, organizationId), submitLabels(id, labels, organizationId),
submitInstanceGroups(id, instanceGroups), submitInstanceGroups(id, instanceGroups),
submitCredentials(id, credentials)
]); ]);
history.push(`/templates/${type}/${id}/details`); history.push(`/templates/${type}/${id}/details`);
} catch (error) { } catch (error) {
@@ -60,6 +62,13 @@ function JobTemplateAdd({ history, i18n }) {
return Promise.all(associatePromises); return Promise.all(associatePromises);
} }
function submitCredentials(templateId, credentials = []) {
const associateCredentials = credentials.map(cred =>
JobTemplatesAPI.associateCredentials(templateId, cred.id)
)
return Promise.all(associateCredentials)
}
function handleCancel() { function handleCancel() {
history.push(`/templates`); history.push(`/templates`);
} }

View File

@@ -109,6 +109,8 @@ class JobTemplateEdit extends Component {
organizationId, organizationId,
instanceGroups, instanceGroups,
initialInstanceGroups, initialInstanceGroups,
credentials,
initialCredentials,
...remainingValues ...remainingValues
} = values; } = values;
@@ -118,6 +120,7 @@ class JobTemplateEdit extends Component {
await Promise.all([ await Promise.all([
this.submitLabels(labels, organizationId), this.submitLabels(labels, organizationId),
this.submitInstanceGroups(instanceGroups, initialInstanceGroups), this.submitInstanceGroups(instanceGroups, initialInstanceGroups),
this.submitCredentials(credentials)
]); ]);
history.push(this.detailsUrl); history.push(this.detailsUrl);
} catch (formSubmitError) { } catch (formSubmitError) {
@@ -154,13 +157,30 @@ class JobTemplateEdit extends Component {
async submitInstanceGroups(groups, initialGroups) { async submitInstanceGroups(groups, initialGroups) {
const { template } = this.props; const { template } = this.props;
const { added, removed } = getAddedAndRemoved(initialGroups, groups); const { added, removed } = getAddedAndRemoved(initialGroups, groups);
const associatePromises = added.map(group => const disassociatePromises = await removed.map(group =>
JobTemplatesAPI.associateInstanceGroup(template.id, group.id)
);
const disassociatePromises = removed.map(group =>
JobTemplatesAPI.disassociateInstanceGroup(template.id, group.id) JobTemplatesAPI.disassociateInstanceGroup(template.id, group.id)
); );
return Promise.all([...associatePromises, ...disassociatePromises]); const associatePromises = await added.map(group =>
JobTemplatesAPI.associateInstanceGroup(template.id, group.id)
);
return Promise.all([...disassociatePromises, ...associatePromises, ]);
}
async submitCredentials(newCredentials) {
const { template } = this.props;
const { added, removed } = getAddedAndRemoved(
template.summary_fields.credentials,
newCredentials
);
const disassociateCredentials = removed.map(cred =>
JobTemplatesAPI.disassociateCredentials(template.id, cred.id)
);
const disassociatePromise = await Promise.all(disassociateCredentials);
const associateCredentials = added.map(cred =>
JobTemplatesAPI.associateCredentials(template.id, cred.id)
)
const associatePromise = Promise.all(associateCredentials)
return Promise.all([disassociatePromise, associatePromise])
} }
handleCancel() { handleCancel() {

View File

@@ -27,6 +27,7 @@ import {
InventoryLookup, InventoryLookup,
InstanceGroupsLookup, InstanceGroupsLookup,
ProjectLookup, ProjectLookup,
CredentialsLookup
} from '@components/Lookup'; } from '@components/Lookup';
import { JobTemplatesAPI } from '@api'; import { JobTemplatesAPI } from '@api';
import LabelSelect from './LabelSelect'; import LabelSelect from './LabelSelect';
@@ -62,6 +63,7 @@ class JobTemplateForm extends Component {
inventory: null, inventory: null,
labels: { results: [] }, labels: { results: [] },
project: null, project: null,
credentials: [],
}, },
isNew: true, isNew: true,
}, },
@@ -84,7 +86,8 @@ class JobTemplateForm extends Component {
const { validateField } = this.props; const { validateField } = this.props;
this.setState({ contentError: null, hasContentLoading: true }); this.setState({ contentError: null, hasContentLoading: true });
// TODO: determine when LabelSelect has finished loading labels // TODO: determine when LabelSelect has finished loading labels
Promise.all([this.loadRelatedInstanceGroups()]).then(() => { Promise.all([this.loadRelatedInstanceGroups(),
]).then(() => {
this.setState({ hasContentLoading: false }); this.setState({ hasContentLoading: false });
validateField('project'); validateField('project');
}); });
@@ -149,7 +152,6 @@ class JobTemplateForm extends Component {
isDisabled: false, isDisabled: false,
}, },
]; ];
const verbosityOptions = [ const verbosityOptions = [
{ value: '0', key: '0', label: i18n._(t`0 (Normal)`) }, { value: '0', key: '0', label: i18n._(t`0 (Normal)`) },
{ value: '1', key: '1', label: i18n._(t`1 (Verbose)`) }, { value: '1', key: '1', label: i18n._(t`1 (Verbose)`) },
@@ -319,6 +321,20 @@ class JobTemplateForm extends Component {
)} )}
/> />
</FormRow> </FormRow>
<FormRow>
<Field
name="credentials"
fieldId="template-credentials"
render={({ form }) => (
<CredentialsLookup
onError={err => this.setState({ contentError: err })}
credentials={template.summary_fields.credentials}
onChange={value => (form.setFieldValue('credentials', value))}
tooltip={i18n._(t`Select credentials that allow Tower to access the nodes this job will be ran against. You can only select one credential of each type. For machine credentials (SSH), checking "Prompt on launch" without selecting credentials will require you to select a machine credential at run time. If you select credentials and check "Prompt on launch", the selected credential(s) become the defaults that can be updated at run time.`)}
/>
)}
/>
</FormRow>
<AdvancedFieldsWrapper label="Advanced"> <AdvancedFieldsWrapper label="Advanced">
<FormRow> <FormRow>
<FormField <FormField
@@ -587,6 +603,8 @@ const FormikApp = withFormik({
organizationId: summary_fields.inventory.organization_id || null, organizationId: summary_fields.inventory.organization_id || null,
initialInstanceGroups: [], initialInstanceGroups: [],
instanceGroups: [], instanceGroups: [],
initialCredentials: summary_fields.credentials || [],
credentials: []
}; };
}, },
handleSubmit: (values, { props }) => props.handleSubmit(values), handleSubmit: (values, { props }) => props.handleSubmit(values),